GeminiPro.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. from __future__ import annotations
  2. import base64
  3. import json
  4. from aiohttp import ClientSession, BaseConnector
  5. from ...typing import AsyncResult, Messages, ImageType
  6. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  7. from ...image import to_bytes, is_accepted_format
  8. from ...errors import MissingAuthError
  9. from ..helper import get_connector
  10. class GeminiPro(AsyncGeneratorProvider, ProviderModelMixin):
  11. label = "Gemini API"
  12. url = "https://ai.google.dev"
  13. working = True
  14. supports_message_history = True
  15. needs_auth = True
  16. default_model = "gemini-1.5-pro"
  17. default_vision_model = default_model
  18. models = [default_model, "gemini-pro", "gemini-1.5-flash", "gemini-1.5-flash-8b"]
  19. @classmethod
  20. async def create_async_generator(
  21. cls,
  22. model: str,
  23. messages: Messages,
  24. stream: bool = False,
  25. proxy: str = None,
  26. api_key: str = None,
  27. api_base: str = "https://generativelanguage.googleapis.com/v1beta",
  28. use_auth_header: bool = False,
  29. image: ImageType = None,
  30. connector: BaseConnector = None,
  31. **kwargs
  32. ) -> AsyncResult:
  33. model = cls.get_model(model)
  34. if not api_key:
  35. raise MissingAuthError('Add a "api_key"')
  36. headers = params = None
  37. if use_auth_header:
  38. headers = {"Authorization": f"Bearer {api_key}"}
  39. else:
  40. params = {"key": api_key}
  41. method = "streamGenerateContent" if stream else "generateContent"
  42. url = f"{api_base.rstrip('/')}/models/{model}:{method}"
  43. async with ClientSession(headers=headers, connector=get_connector(connector, proxy)) as session:
  44. contents = [
  45. {
  46. "role": "model" if message["role"] == "assistant" else "user",
  47. "parts": [{"text": message["content"]}]
  48. }
  49. for message in messages
  50. if message["role"] != "system"
  51. ]
  52. if image is not None:
  53. image = to_bytes(image)
  54. contents[-1]["parts"].append({
  55. "inline_data": {
  56. "mime_type": is_accepted_format(image),
  57. "data": base64.b64encode(image).decode()
  58. }
  59. })
  60. data = {
  61. "contents": contents,
  62. "generationConfig": {
  63. "stopSequences": kwargs.get("stop"),
  64. "temperature": kwargs.get("temperature"),
  65. "maxOutputTokens": kwargs.get("max_tokens"),
  66. "topP": kwargs.get("top_p"),
  67. "topK": kwargs.get("top_k"),
  68. }
  69. }
  70. system_prompt = "\n".join(
  71. message["content"]
  72. for message in messages
  73. if message["role"] == "system"
  74. )
  75. if system_prompt:
  76. data["system_instruction"] = {"parts": {"text": system_prompt}}
  77. async with session.post(url, params=params, json=data) as response:
  78. if not response.ok:
  79. data = await response.json()
  80. data = data[0] if isinstance(data, list) else data
  81. raise RuntimeError(f"Response {response.status}: {data['error']['message']}")
  82. if stream:
  83. lines = []
  84. async for chunk in response.content:
  85. if chunk == b"[{\n":
  86. lines = [b"{\n"]
  87. elif chunk == b",\r\n" or chunk == b"]":
  88. try:
  89. data = b"".join(lines)
  90. data = json.loads(data)
  91. yield data["candidates"][0]["content"]["parts"][0]["text"]
  92. except:
  93. data = data.decode(errors="ignore") if isinstance(data, bytes) else data
  94. raise RuntimeError(f"Read chunk failed: {data}")
  95. lines = []
  96. else:
  97. lines.append(chunk)
  98. else:
  99. data = await response.json()
  100. candidate = data["candidates"][0]
  101. if candidate["finishReason"] == "STOP":
  102. yield candidate["content"]["parts"][0]["text"]
  103. else:
  104. yield candidate["finishReason"] + ' ' + candidate["safetyRatings"]