summaryrefslogtreecommitdiffstats
path: root/g4f/Provider/GeminiPro.py
blob: a2e3538d4b6bebdf89012d633e8d7ca1b5e113b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
from __future__ import annotations

import base64
import json
from aiohttp import ClientSession, BaseConnector

from ..typing import AsyncResult, Messages, ImageType
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
from ..image import to_bytes, is_accepted_format
from ..errors import MissingAuthError
from .helper import get_connector

class GeminiPro(AsyncGeneratorProvider, ProviderModelMixin):
    url = "https://ai.google.dev"
    working = True
    supports_message_history = True
    needs_auth = True
    default_model = "gemini-pro"
    models = ["gemini-pro", "gemini-pro-vision"]

    @classmethod
    async def create_async_generator(
        cls,
        model: str,
        messages: Messages,
        stream: bool = False,
        proxy: str = None,
        api_key: str = None,
        api_base: str = None,
        image: ImageType = None,
        connector: BaseConnector = None,
        **kwargs
    ) -> AsyncResult:
        model = "gemini-pro-vision" if not model and image else model
        model = cls.get_model(model)

        if not api_key:
            raise MissingAuthError('Missing "api_key"')

        headers = params = None
        if api_base:
            headers = {"Authorization": f"Bearer {api_key}"}
        else:
            params = {"key": api_key}

        if not api_base:
            api_base = f"https://generativelanguage.googleapis.com/v1beta"

        method = "streamGenerateContent" if stream else "generateContent"
        url = f"{api_base.rstrip('/')}/models/{model}:{method}"
        async with ClientSession(headers=headers, connector=get_connector(connector, proxy)) as session:
            contents = [
                {
                    "role": "model" if message["role"] == "assistant" else message["role"],
                    "parts": [{"text": message["content"]}]
                }
                for message in messages
            ]
            if image:
                image = to_bytes(image)
                contents[-1]["parts"].append({
                    "inline_data": {
                        "mime_type": is_accepted_format(image),
                        "data": base64.b64encode(image).decode()
                    }
                })
            data = {
                "contents": contents,
                "generationConfig": {
                    "stopSequences": kwargs.get("stop"),
                    "temperature": kwargs.get("temperature"),
                    "maxOutputTokens": kwargs.get("max_tokens"),
                    "topP": kwargs.get("top_p"),
                    "topK": kwargs.get("top_k"),
                }
            }
            async with session.post(url, params=params, json=data) as response:
                if not response.ok:
                    data = await response.json()
                    data = data[0] if isinstance(data, list) else data
                    raise RuntimeError(data["error"]["message"])
                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:
                                data = json.loads(b"".join(lines))
                                yield data["candidates"][0]["content"]["parts"][0]["text"]
                            except:
                                data = data.decode() if isinstance(data, bytes) else data
                                raise RuntimeError(f"Read chunk failed: {data}")
                            lines = []
                        else:
                            lines.append(chunk)
                else:
                    data = await response.json()
                    yield data["candidates"][0]["content"]["parts"][0]["text"]