2024-02-23 10:33:38 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
import base64
|
|
|
|
import json
|
2024-02-26 10:28:35 +00:00
|
|
|
from aiohttp import ClientSession, BaseConnector
|
2024-02-23 10:33:38 +00:00
|
|
|
|
|
|
|
from ..typing import AsyncResult, Messages, ImageType
|
|
|
|
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
|
|
|
|
from ..image import to_bytes, is_accepted_format
|
2024-02-24 00:31:17 +00:00
|
|
|
from ..errors import MissingAuthError
|
2024-02-26 10:28:35 +00:00
|
|
|
from .helper import get_connector
|
2024-02-23 10:33:38 +00:00
|
|
|
|
|
|
|
class GeminiPro(AsyncGeneratorProvider, ProviderModelMixin):
|
2024-04-22 16:08:04 +00:00
|
|
|
label = "Gemini API"
|
2024-02-23 10:33:38 +00:00
|
|
|
url = "https://ai.google.dev"
|
|
|
|
working = True
|
|
|
|
supports_message_history = True
|
2024-02-25 08:41:39 +00:00
|
|
|
needs_auth = True
|
2024-04-22 16:08:04 +00:00
|
|
|
default_model = "gemini-1.5-pro-latest"
|
|
|
|
default_vision_model = default_model
|
|
|
|
models = [default_model, "gemini-pro", "gemini-pro-vision"]
|
2024-02-23 10:33:38 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def create_async_generator(
|
|
|
|
cls,
|
|
|
|
model: str,
|
|
|
|
messages: Messages,
|
|
|
|
stream: bool = False,
|
|
|
|
proxy: str = None,
|
|
|
|
api_key: str = None,
|
2024-03-08 10:01:38 +00:00
|
|
|
api_base: str = "https://generativelanguage.googleapis.com/v1beta",
|
|
|
|
use_auth_header: bool = False,
|
2024-02-23 10:33:38 +00:00
|
|
|
image: ImageType = None,
|
2024-02-26 10:28:35 +00:00
|
|
|
connector: BaseConnector = None,
|
2024-02-23 10:33:38 +00:00
|
|
|
**kwargs
|
|
|
|
) -> AsyncResult:
|
|
|
|
model = cls.get_model(model)
|
2024-02-25 08:41:39 +00:00
|
|
|
|
2024-02-25 14:48:03 +00:00
|
|
|
if not api_key:
|
2024-04-22 16:08:04 +00:00
|
|
|
raise MissingAuthError('Add a "api_key"')
|
2024-02-26 01:31:14 +00:00
|
|
|
|
|
|
|
headers = params = None
|
2024-03-08 10:01:38 +00:00
|
|
|
if use_auth_header:
|
2024-02-26 01:31:14 +00:00
|
|
|
headers = {"Authorization": f"Bearer {api_key}"}
|
|
|
|
else:
|
|
|
|
params = {"key": api_key}
|
|
|
|
|
2024-02-25 08:41:39 +00:00
|
|
|
method = "streamGenerateContent" if stream else "generateContent"
|
|
|
|
url = f"{api_base.rstrip('/')}/models/{model}:{method}"
|
2024-02-26 10:28:35 +00:00
|
|
|
async with ClientSession(headers=headers, connector=get_connector(connector, proxy)) as session:
|
2024-02-23 10:33:38 +00:00
|
|
|
contents = [
|
|
|
|
{
|
2024-03-08 10:01:38 +00:00
|
|
|
"role": "model" if message["role"] == "assistant" else "user",
|
2024-02-23 10:33:38 +00:00
|
|
|
"parts": [{"text": message["content"]}]
|
|
|
|
}
|
|
|
|
for message in messages
|
|
|
|
]
|
2024-03-08 10:01:38 +00:00
|
|
|
if image is not None:
|
2024-02-23 10:33:38 +00:00
|
|
|
image = to_bytes(image)
|
|
|
|
contents[-1]["parts"].append({
|
|
|
|
"inline_data": {
|
|
|
|
"mime_type": is_accepted_format(image),
|
|
|
|
"data": base64.b64encode(image).decode()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
data = {
|
|
|
|
"contents": contents,
|
2024-02-24 00:31:17 +00:00
|
|
|
"generationConfig": {
|
|
|
|
"stopSequences": kwargs.get("stop"),
|
|
|
|
"temperature": kwargs.get("temperature"),
|
|
|
|
"maxOutputTokens": kwargs.get("max_tokens"),
|
|
|
|
"topP": kwargs.get("top_p"),
|
|
|
|
"topK": kwargs.get("top_k"),
|
|
|
|
}
|
2024-02-23 10:33:38 +00:00
|
|
|
}
|
2024-02-26 10:28:35 +00:00
|
|
|
async with session.post(url, params=params, json=data) as response:
|
2024-02-23 10:33:38 +00:00
|
|
|
if not response.ok:
|
|
|
|
data = await response.json()
|
2024-02-26 01:31:14 +00:00
|
|
|
data = data[0] if isinstance(data, list) else data
|
2024-04-07 08:36:13 +00:00
|
|
|
raise RuntimeError(f"Response {response.status}: {data['error']['message']}")
|
2024-02-23 10:33:38 +00:00
|
|
|
if stream:
|
|
|
|
lines = []
|
|
|
|
async for chunk in response.content:
|
|
|
|
if chunk == b"[{\n":
|
|
|
|
lines = [b"{\n"]
|
|
|
|
elif chunk == b",\r\n" or chunk == b"]":
|
|
|
|
try:
|
2024-03-08 10:01:38 +00:00
|
|
|
data = b"".join(lines)
|
|
|
|
data = json.loads(data)
|
2024-02-23 10:33:38 +00:00
|
|
|
yield data["candidates"][0]["content"]["parts"][0]["text"]
|
|
|
|
except:
|
2024-04-06 21:54:41 +00:00
|
|
|
data = data.decode(errors="ignore") if isinstance(data, bytes) else data
|
2024-02-25 14:48:03 +00:00
|
|
|
raise RuntimeError(f"Read chunk failed: {data}")
|
2024-02-23 10:33:38 +00:00
|
|
|
lines = []
|
|
|
|
else:
|
|
|
|
lines.append(chunk)
|
|
|
|
else:
|
|
|
|
data = await response.json()
|
|
|
|
yield data["candidates"][0]["content"]["parts"][0]["text"]
|