xjackkx commited on
Commit
08dfd5a
Β·
verified Β·
1 Parent(s): d1f5b75

Upload 8 files

Browse files
gemini_web2api/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
- """gemini-web2api: Gemini Web to OpenAI API proxy."""
2
- __version__ = "1.1.0"
 
1
+ """gemini-web2api: Gemini Web to OpenAI API proxy."""
2
+ __version__ = "1.1.0"
gemini_web2api/__main__.py CHANGED
@@ -1,52 +1,51 @@
1
- """Entry point: python -m gemini_web2api"""
2
- import argparse
3
- import os
4
-
5
- from .config import CONFIG, load_config, apply_env_overrides, find_config
6
- from .models import MODELS
7
- from .gemini import HAS_HTTPX
8
- from .server import GeminiHandler, ThreadedServer
9
- from . import __version__
10
-
11
-
12
- def main():
13
- parser = argparse.ArgumentParser(description="Gemini Web to OpenAI API")
14
- parser.add_argument("--port", type=int, default=None)
15
- parser.add_argument("--config", type=str, default=None)
16
- parser.add_argument("--cookie-file", type=str, default=None)
17
- parser.add_argument("--proxy", type=str, default=None, help="HTTP proxy, e.g. http://127.0.0.1:7890")
18
- parser.add_argument("--version", action="version", version=f"gemini-web2api {__version__}")
19
- args = parser.parse_args()
20
-
21
- # Priority: CLI > env > config file > defaults
22
- config_path = args.config or os.environ.get("GEMINI_WEB2API_CONFIG") or find_config()
23
- if config_path:
24
- load_config(config_path)
25
- apply_env_overrides()
26
-
27
- if args.port:
28
- CONFIG["port"] = args.port
29
- if args.cookie_file:
30
- CONFIG["cookie_file"] = args.cookie_file
31
- if args.proxy:
32
- CONFIG["proxy"] = args.proxy
33
-
34
- port = CONFIG["port"]
35
- server = ThreadedServer((CONFIG["host"], port), GeminiHandler)
36
- print(f"gemini-web2api v{__version__}")
37
- print(f" Listening: http://0.0.0.0:{port}")
38
- print(f" Base URL: http://localhost:{port}/v1")
39
- print(f" Models: {', '.join(MODELS.keys())}")
40
- print(f" Cookie: {'yes' if CONFIG.get('cookie_file') else 'none (anonymous)'}")
41
- print(f" Proxy: {CONFIG.get('proxy') or 'system env'}")
42
- print(f" Streaming: {'httpx (true streaming)' if HAS_HTTPX else 'urllib (buffered)'}")
43
- print()
44
- try:
45
- server.serve_forever()
46
- except KeyboardInterrupt:
47
- print("\nStopped.")
48
- server.shutdown()
49
-
50
-
51
- if __name__ == "__main__":
52
- main()
 
1
+ """Entry point: python -m gemini_web2api"""
2
+ import argparse
3
+ import os
4
+
5
+ from .config import CONFIG, load_config, find_config
6
+ from .models import MODELS
7
+ from .gemini import HAS_HTTPX
8
+ from .server import GeminiHandler, ThreadedServer
9
+ from . import __version__
10
+
11
+
12
+ def main():
13
+ parser = argparse.ArgumentParser(description="Gemini Web to OpenAI API")
14
+ parser.add_argument("--port", type=int, default=None)
15
+ parser.add_argument("--config", type=str, default=None)
16
+ parser.add_argument("--cookie-file", type=str, default=None)
17
+ parser.add_argument("--proxy", type=str, default=None, help="HTTP proxy, e.g. http://127.0.0.1:7890")
18
+ parser.add_argument("--version", action="version", version=f"gemini-web2api {__version__}")
19
+ args = parser.parse_args()
20
+
21
+ config_path = args.config or os.environ.get("GEMINI_WEB2API_CONFIG") or find_config()
22
+ if config_path:
23
+ load_config(config_path)
24
+
25
+ if args.port:
26
+ CONFIG["port"] = args.port
27
+ if args.cookie_file:
28
+ CONFIG["cookie_file"] = args.cookie_file
29
+ if args.proxy:
30
+ CONFIG["proxy"] = args.proxy
31
+
32
+ port = CONFIG["port"]
33
+ server = ThreadedServer((CONFIG["host"], port), GeminiHandler)
34
+ print(f"gemini-web2api v{__version__}")
35
+ print(f" Listening: http://0.0.0.0:{port}")
36
+ print(f" Base URL: http://localhost:{port}/v1")
37
+ print(f" Models: {', '.join(MODELS.keys())}")
38
+ print(f" Cookie: {'yes' if CONFIG.get('cookie_file') else 'none (anonymous)'}")
39
+ print(f" Proxy: {CONFIG.get('proxy') or 'system env'}")
40
+ print(f" Streaming: {'httpx (true streaming)' if HAS_HTTPX else 'urllib (buffered)'}")
41
+ print(f" Temporary: {'yes' if CONFIG.get('temporary_chats', False) else 'no'}")
42
+ print()
43
+ try:
44
+ server.serve_forever()
45
+ except KeyboardInterrupt:
46
+ print("\nStopped.")
47
+ server.shutdown()
48
+
49
+
50
+ if __name__ == "__main__":
51
+ main()
 
gemini_web2api/config.py CHANGED
@@ -1,91 +1,38 @@
1
- """Configuration management."""
2
- import json
3
- import os
4
- import tempfile
5
-
6
- DEFAULT_CONFIG = {
7
- "port": 8081,
8
- "host": "0.0.0.0",
9
- "retry_attempts": 3,
10
- "retry_delay_sec": 2,
11
- "request_timeout_sec": 180,
12
- "gemini_bl": "boq_assistant-bard-web-server_20260716.08_p0",
13
- "auth_user": None,
14
- "xsrf_token": None,
15
- "default_model": "gemini-3.6-flash",
16
- "log_requests": True,
17
- "cookie_file": None,
18
- "proxy": None,
19
- "resin_proxy": None,
20
- "api_keys": [],
21
- }
22
-
23
- CONFIG = dict(DEFAULT_CONFIG)
24
-
25
-
26
- def load_config(path: str = None):
27
- """Load config from JSON file."""
28
- if path and os.path.exists(path):
29
- with open(path) as f:
30
- CONFIG.update(json.load(f))
31
- return CONFIG
32
-
33
-
34
- def apply_env_overrides():
35
- """Apply environment variables (Docker / Hugging Face Spaces secrets).
36
-
37
- Priority: CLI args (caller) > env > config file > defaults.
38
- Supported env:
39
- PORT / HOST / PROXY
40
- GEMINI_COOKIE_FILE / GEMINI_COOKIE (inline cookie file body)
41
- API_KEYS (comma-separated)
42
- AUTH_USER / XSRF_TOKEN
43
- GEMINI_BL / DEFAULT_MODEL
44
- LOG_REQUESTS (1/0 true/false)
45
- """
46
- if os.environ.get("PORT"):
47
- CONFIG["port"] = int(os.environ["PORT"])
48
- if os.environ.get("HOST"):
49
- CONFIG["host"] = os.environ["HOST"]
50
- if os.environ.get("PROXY"):
51
- CONFIG["proxy"] = os.environ["PROXY"] or None
52
- if os.environ.get("RESIN_PROXY"):
53
- CONFIG["resin_proxy"] = os.environ["RESIN_PROXY"] or None
54
-
55
- cookie_file = os.environ.get("GEMINI_COOKIE_FILE") or os.environ.get("COOKIE_FILE")
56
- if cookie_file:
57
- CONFIG["cookie_file"] = cookie_file
58
- elif os.environ.get("GEMINI_COOKIE"):
59
- # Write secret body to a temp path (Spaces has no durable volume on free tier)
60
- path = os.path.join(tempfile.gettempdir(), "gemini_web2api_cookies.txt")
61
- with open(path, "w", encoding="utf-8") as f:
62
- f.write(os.environ["GEMINI_COOKIE"])
63
- CONFIG["cookie_file"] = path
64
-
65
- if os.environ.get("API_KEYS") is not None:
66
- raw = os.environ["API_KEYS"].strip()
67
- CONFIG["api_keys"] = [k.strip() for k in raw.split(",") if k.strip()] if raw else []
68
-
69
- if "AUTH_USER" in os.environ:
70
- v = os.environ["AUTH_USER"].strip()
71
- CONFIG["auth_user"] = int(v) if v.isdigit() else (v or None)
72
- if "XSRF_TOKEN" in os.environ:
73
- CONFIG["xsrf_token"] = os.environ["XSRF_TOKEN"] or None
74
- if os.environ.get("GEMINI_BL"):
75
- CONFIG["gemini_bl"] = os.environ["GEMINI_BL"]
76
- if os.environ.get("DEFAULT_MODEL"):
77
- CONFIG["default_model"] = os.environ["DEFAULT_MODEL"]
78
- if os.environ.get("LOG_REQUESTS") is not None:
79
- CONFIG["log_requests"] = os.environ["LOG_REQUESTS"].strip().lower() in (
80
- "1", "true", "yes", "on",
81
- )
82
-
83
- return CONFIG
84
-
85
-
86
- def find_config():
87
- """Search for config file in standard locations."""
88
- for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
89
- if os.path.exists(p):
90
- return p
91
- return None
 
1
+ """Configuration management."""
2
+ import json
3
+ import os
4
+
5
+ DEFAULT_CONFIG = {
6
+ "port": 8081,
7
+ "host": "0.0.0.0",
8
+ "retry_attempts": 3,
9
+ "retry_delay_sec": 2,
10
+ "request_timeout_sec": 180,
11
+ "gemini_bl": "boq_assistant-bard-web-server_20260716.08_p0",
12
+ "auth_user": None,
13
+ "xsrf_token": None,
14
+ "default_model": "gemini-3.6-flash",
15
+ "log_requests": True,
16
+ "cookie_file": None,
17
+ "proxy": None,
18
+ "api_keys": [],
19
+ "temporary_chats": False,
20
+ }
21
+
22
+ CONFIG = dict(DEFAULT_CONFIG)
23
+
24
+
25
+ def load_config(path: str = None):
26
+ """Load config from JSON file."""
27
+ if path and os.path.exists(path):
28
+ with open(path) as f:
29
+ CONFIG.update(json.load(f))
30
+ return CONFIG
31
+
32
+
33
+ def find_config():
34
+ """Search for config file in standard locations."""
35
+ for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
36
+ if os.path.exists(p):
37
+ return p
38
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
gemini_web2api/gemini.py CHANGED
@@ -1,276 +1,280 @@
1
- """Gemini StreamGenerate protocol implementation with httpx streaming."""
2
- import json
3
- import time
4
- import uuid
5
- import re
6
- import urllib.request
7
- import urllib.parse
8
- import ssl
9
- import os
10
- import hashlib
11
-
12
- try:
13
- import httpx
14
- HAS_HTTPX = True
15
- except ImportError:
16
- HAS_HTTPX = False
17
-
18
- from .config import CONFIG
19
-
20
- _ssl_ctx = None
21
- _cookie_cache = {"str": "", "sapisid": None, "mtime": 0}
22
- _httpx_client = None
23
-
24
-
25
- def log(msg: str):
26
- if CONFIG["log_requests"]:
27
- import sys
28
- sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
29
- sys.stderr.flush()
30
-
31
-
32
- def _get_ssl_ctx():
33
- global _ssl_ctx
34
- if _ssl_ctx is None:
35
- _ssl_ctx = ssl.create_default_context()
36
- return _ssl_ctx
37
-
38
-
39
- def _get_httpx_client():
40
- global _httpx_client
41
- if _httpx_client is None and HAS_HTTPX:
42
- proxy = CONFIG.get("proxy")
43
- transport = httpx.HTTPTransport(proxy=proxy) if proxy else None
44
- _httpx_client = httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True)
45
- return _httpx_client
46
-
47
-
48
- def load_cookie() -> tuple:
49
- """Load cookie from file with mtime-based caching."""
50
- cookie_file = CONFIG.get("cookie_file")
51
- if not cookie_file or not os.path.exists(cookie_file):
52
- return "", None
53
- try:
54
- mtime = os.path.getmtime(cookie_file)
55
- if mtime == _cookie_cache["mtime"] and _cookie_cache["str"]:
56
- return _cookie_cache["str"], _cookie_cache["sapisid"]
57
- with open(cookie_file, "r") as f:
58
- content = f.read().strip()
59
- if content.startswith("{"):
60
- data = json.loads(content)
61
- cookie_str = data.get("cookie", "")
62
- sapisid = data.get("sapisid", "")
63
- else:
64
- cookie_str = content
65
- pairs = dict(p.split("=", 1) for p in cookie_str.split("; ") if "=" in p)
66
- sapisid = pairs.get("SAPISID", "")
67
- _cookie_cache.update({"str": cookie_str, "sapisid": sapisid or None, "mtime": mtime})
68
- return cookie_str, sapisid if sapisid else None
69
- except Exception as e:
70
- log(f"Cookie load error: {e}")
71
- return _cookie_cache["str"], _cookie_cache["sapisid"]
72
-
73
-
74
- def make_sapisidhash(sapisid: str) -> str:
75
- ts = int(time.time())
76
- h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
77
- return f"SAPISIDHASH {ts}_{h}"
78
-
79
-
80
- def _account_prefix() -> str:
81
- """Return the Gemini account path prefix for non-default Google accounts."""
82
- auth_user = CONFIG.get("auth_user")
83
- if auth_user is None or auth_user == "":
84
- return ""
85
- return f"/u/{auth_user}"
86
-
87
-
88
- def resin_proxy_url(url: str) -> str:
89
- """Rewrite an absolute https URL to go through a Resin reverse-proxy prefix.
90
-
91
- Config ``resin_proxy`` is the full prefix ending at the protocol segment,
92
- e.g. ``https://resin-host:port/<PROXY_TOKEN>/<Platform>/https/``.
93
- Then ``https://gemini.google.com/app`` -> ``<prefix>/gemini.google.com/app``.
94
-
95
- When ``resin_proxy`` is unset or the URL is not https, return it unchanged
96
- so the existing PROXY/urllib path still works.
97
- """
98
- prefix = (CONFIG.get("resin_proxy") or "").strip()
99
- if not prefix or not url.startswith("https://"):
100
- return url
101
- # strip trailing slashes, then re-add exactly one
102
- prefix = prefix.rstrip("/")
103
- # drop "https://" from the target, keep host + path + query
104
- return prefix + "/" + url[len("https://"):]
105
-
106
-
107
- def _build_headers() -> dict:
108
- account_prefix = _account_prefix()
109
- headers = {
110
- "Content-Type": "application/x-www-form-urlencoded",
111
- "Origin": "https://gemini.google.com",
112
- "Referer": f"https://gemini.google.com{account_prefix}/app",
113
- "X-Same-Domain": "1",
114
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
115
- }
116
- if account_prefix:
117
- headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
118
- cookie_str, sapisid = load_cookie()
119
- if cookie_str:
120
- headers["Cookie"] = cookie_str
121
- if sapisid:
122
- headers["Authorization"] = make_sapisidhash(sapisid)
123
- return headers
124
-
125
-
126
- def _build_payload(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
127
- inner = [None] * 102
128
- if file_refs:
129
- refs = [[None, None, ref] for ref in file_refs]
130
- inner[0] = [prompt, 0, None, refs, None, None, 0]
131
- else:
132
- inner[0] = [prompt, 0, None, None, None, None, 0]
133
- inner[1] = ["en"]
134
- inner[2] = ["", "", "", None, None, None, None, None, None, ""]
135
- inner[6] = [0]
136
- inner[7] = 1
137
- inner[10] = 1
138
- inner[11] = 0
139
- inner[17] = [[think_mode]]
140
- inner[18] = 0
141
- inner[27] = 1
142
- inner[30] = [4]
143
- inner[41] = [2]
144
- inner[53] = 0
145
- inner[59] = str(uuid.uuid4())
146
- inner[61] = []
147
- inner[68] = 1
148
- inner[79] = model_id
149
- if extra_fields:
150
- for k, v in extra_fields.items():
151
- inner[k] = v
152
- outer = [None, json.dumps(inner)]
153
- params = {"f.req": json.dumps(outer)}
154
- if CONFIG.get("xsrf_token"):
155
- params["at"] = CONFIG["xsrf_token"]
156
- return urllib.parse.urlencode(params)
157
-
158
-
159
- def _get_url() -> str:
160
- reqid = int(time.time()) % 1000000
161
- account_prefix = _account_prefix()
162
- return (
163
- f"https://gemini.google.com{account_prefix}/_/BardChatUi/data/"
164
- "assistant.lamda.BardFrontendService/StreamGenerate"
165
- f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
166
- )
167
-
168
-
169
- def clean_text(text: str) -> str:
170
- text = re.sub(
171
- r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
172
- '', text, flags=re.DOTALL
173
- )
174
- text = re.sub(r'http://googleusercontent\.com/card_content/\d+\n?', '', text)
175
- return text.strip()
176
-
177
-
178
- def _extract_texts_from_line(line: str) -> list:
179
- """Parse a single wrb.fr line and return list of text strings found."""
180
- if '"wrb.fr"' not in line or len(line) < 200:
181
- return []
182
- try:
183
- arr = json.loads(line)
184
- inner_str = arr[0][2]
185
- if not inner_str or len(inner_str) < 50:
186
- return []
187
- inner = json.loads(inner_str)
188
- if not (isinstance(inner, list) and len(inner) > 4 and inner[4]):
189
- return []
190
- texts = []
191
- for part in inner[4]:
192
- if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
193
- for t in part[1]:
194
- if isinstance(t, str) and t:
195
- texts.append(t)
196
- return texts
197
- except (json.JSONDecodeError, IndexError, TypeError):
198
- return []
199
-
200
-
201
- def extract_response_text(raw: str) -> str:
202
- """Parse full response to get final text."""
203
- last_text = ""
204
- for line in raw.split("\n"):
205
- for t in _extract_texts_from_line(line):
206
- if len(t) > len(last_text):
207
- last_text = t
208
- return clean_text(last_text)
209
-
210
-
211
- def generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
212
- """Non-streaming generation with retry."""
213
- body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields).encode()
214
- url = resin_proxy_url(_get_url())
215
- headers = _build_headers()
216
- ctx = _get_ssl_ctx()
217
- proxy = CONFIG.get("proxy")
218
-
219
- last_err = None
220
- for attempt in range(CONFIG["retry_attempts"]):
221
- try:
222
- req = urllib.request.Request(url, data=body, headers=headers, method="POST")
223
- if proxy:
224
- opener = urllib.request.build_opener(
225
- urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
226
- urllib.request.HTTPSHandler(context=ctx)
227
- )
228
- resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
229
- else:
230
- resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
231
- raw = resp.read().decode("utf-8", errors="replace")
232
- return extract_response_text(raw)
233
- except Exception as e:
234
- last_err = e
235
- if attempt < CONFIG["retry_attempts"] - 1:
236
- log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
237
- time.sleep(CONFIG["retry_delay_sec"])
238
- raise last_err
239
-
240
-
241
- def generate_stream(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None):
242
- """Streaming generation via httpx with retry on connection failure."""
243
- if not HAS_HTTPX:
244
- text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
245
- if text:
246
- yield text
247
- return
248
-
249
- body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields)
250
- url = resin_proxy_url(_get_url())
251
- headers = _build_headers()
252
- client = _get_httpx_client()
253
-
254
- last_err = None
255
- for attempt in range(CONFIG["retry_attempts"]):
256
- try:
257
- prev_text = ""
258
- with client.stream("POST", url, content=body, headers=headers) as resp:
259
- buf = ""
260
- for chunk in resp.iter_text():
261
- buf += chunk
262
- while "\n" in buf:
263
- line, buf = buf.split("\n", 1)
264
- for t in _extract_texts_from_line(line):
265
- if len(t) > len(prev_text):
266
- delta = clean_text(t[len(prev_text):])
267
- if delta:
268
- yield delta
269
- prev_text = t
270
- return
271
- except Exception as e:
272
- last_err = e
273
- if attempt < CONFIG["retry_attempts"] - 1:
274
- log(f"Stream retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
275
- time.sleep(CONFIG["retry_delay_sec"])
276
- raise last_err
 
 
 
 
 
1
+ """Gemini StreamGenerate protocol implementation with httpx streaming."""
2
+ import json
3
+ import time
4
+ import uuid
5
+ import re
6
+ import urllib.request
7
+ import urllib.parse
8
+ import ssl
9
+ import os
10
+ import hashlib
11
+
12
+ try:
13
+ import httpx
14
+ HAS_HTTPX = True
15
+ except ImportError:
16
+ HAS_HTTPX = False
17
+
18
+ from .config import CONFIG
19
+
20
+ _ssl_ctx = None
21
+ _cookie_cache = {"str": "", "sapisid": None, "mtime": 0}
22
+ _httpx_client = None
23
+
24
+
25
+ def log(msg: str):
26
+ if CONFIG["log_requests"]:
27
+ import sys
28
+ sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
29
+ sys.stderr.flush()
30
+
31
+
32
+ def _get_ssl_ctx():
33
+ global _ssl_ctx
34
+ if _ssl_ctx is None:
35
+ _ssl_ctx = ssl.create_default_context()
36
+ return _ssl_ctx
37
+
38
+
39
+ def _get_httpx_client():
40
+ global _httpx_client
41
+ if _httpx_client is None and HAS_HTTPX:
42
+ proxy = CONFIG.get("proxy")
43
+ transport = httpx.HTTPTransport(proxy=proxy) if proxy else None
44
+ _httpx_client = httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True)
45
+ return _httpx_client
46
+
47
+
48
+ def load_cookie() -> tuple:
49
+ """Load cookie from file with mtime-based caching."""
50
+ cookie_file = CONFIG.get("cookie_file")
51
+ if not cookie_file or not os.path.exists(cookie_file):
52
+ return "", None
53
+ try:
54
+ mtime = os.path.getmtime(cookie_file)
55
+ if mtime == _cookie_cache["mtime"] and _cookie_cache["str"]:
56
+ return _cookie_cache["str"], _cookie_cache["sapisid"]
57
+ with open(cookie_file, "r") as f:
58
+ content = f.read().strip()
59
+ if content.startswith("{"):
60
+ data = json.loads(content)
61
+ cookie_str = data.get("cookie", "")
62
+ sapisid = data.get("sapisid", "")
63
+ else:
64
+ cookie_str = content
65
+ pairs = dict(p.split("=", 1) for p in cookie_str.split("; ") if "=" in p)
66
+ sapisid = pairs.get("SAPISID", "")
67
+ _cookie_cache.update({"str": cookie_str, "sapisid": sapisid or None, "mtime": mtime})
68
+ return cookie_str, sapisid if sapisid else None
69
+ except Exception as e:
70
+ log(f"Cookie load error: {e}")
71
+ return _cookie_cache["str"], _cookie_cache["sapisid"]
72
+
73
+
74
+ def make_sapisidhash(sapisid: str) -> str:
75
+ ts = int(time.time())
76
+ h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
77
+ return f"SAPISIDHASH {ts}_{h}"
78
+
79
+
80
+ def _account_prefix() -> str:
81
+ """Return the Gemini account path prefix for non-default Google accounts."""
82
+ auth_user = CONFIG.get("auth_user")
83
+ if auth_user is None or auth_user == "":
84
+ return ""
85
+ return f"/u/{auth_user}"
86
+
87
+
88
+ def _build_headers() -> dict:
89
+ account_prefix = _account_prefix()
90
+ headers = {
91
+ "Content-Type": "application/x-www-form-urlencoded",
92
+ "Origin": "https://gemini.google.com",
93
+ "Referer": f"https://gemini.google.com{account_prefix}/app",
94
+ "X-Same-Domain": "1",
95
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
96
+ }
97
+ if account_prefix:
98
+ headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
99
+ cookie_str, sapisid = load_cookie()
100
+ if cookie_str:
101
+ headers["Cookie"] = cookie_str
102
+ if sapisid:
103
+ headers["Authorization"] = make_sapisidhash(sapisid)
104
+ return headers
105
+
106
+
107
+ def _apply_chat_persistence_flags(inner: list) -> None:
108
+ """Apply Gemini Web persistence flags to an outgoing request payload."""
109
+ if CONFIG.get("temporary_chats", False):
110
+ # Match Gemini Web temporary-chat requests.
111
+ inner[41] = [1]
112
+ inner[45] = 1
113
+ else:
114
+ inner[41] = [2]
115
+
116
+
117
+ def _build_payload(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
118
+ inner = [None] * 102
119
+ if file_refs:
120
+ refs = [[None, None, ref] for ref in file_refs]
121
+ inner[0] = [prompt, 0, None, refs, None, None, 0]
122
+ else:
123
+ inner[0] = [prompt, 0, None, None, None, None, 0]
124
+ inner[1] = ["en"]
125
+ inner[2] = ["", "", "", None, None, None, None, None, None, ""]
126
+ inner[6] = [0]
127
+ inner[7] = 1
128
+ inner[10] = 1
129
+ inner[11] = 0
130
+ inner[17] = [[think_mode]]
131
+ inner[18] = 0
132
+ inner[27] = 1
133
+ inner[30] = [4]
134
+ _apply_chat_persistence_flags(inner)
135
+ inner[53] = 0
136
+ inner[59] = str(uuid.uuid4())
137
+ inner[61] = []
138
+ inner[68] = 1
139
+ inner[79] = model_id
140
+ if extra_fields:
141
+ for k, v in extra_fields.items():
142
+ inner[k] = v
143
+ outer = [None, json.dumps(inner)]
144
+ params = {"f.req": json.dumps(outer)}
145
+ if CONFIG.get("xsrf_token"):
146
+ params["at"] = CONFIG["xsrf_token"]
147
+ return urllib.parse.urlencode(params)
148
+
149
+
150
+ def _get_url() -> str:
151
+ reqid = int(time.time()) % 1000000
152
+ account_prefix = _account_prefix()
153
+ return (
154
+ f"https://gemini.google.com{account_prefix}/_/BardChatUi/data/"
155
+ "assistant.lamda.BardFrontendService/StreamGenerate"
156
+ f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
157
+ )
158
+
159
+
160
+ def clean_text(text: str, strip: bool = True) -> str:
161
+ text = re.sub(
162
+ r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
163
+ '', text, flags=re.DOTALL
164
+ )
165
+ text = re.sub(r'http://googleusercontent\.com/card_content/\d+\n?', '', text)
166
+ return text.strip() if strip else text
167
+
168
+
169
+ def _extract_texts_from_line(line: str) -> list:
170
+ """Parse a single wrb.fr line and return list of text strings found."""
171
+ if '"wrb.fr"' not in line or len(line) < 200:
172
+ return []
173
+ try:
174
+ arr = json.loads(line)
175
+ inner_str = arr[0][2]
176
+ if not inner_str or len(inner_str) < 50:
177
+ return []
178
+ inner = json.loads(inner_str)
179
+ if not (isinstance(inner, list) and len(inner) > 4 and inner[4]):
180
+ return []
181
+ texts = []
182
+ for part in inner[4]:
183
+ if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
184
+ for t in part[1]:
185
+ if isinstance(t, str) and t:
186
+ texts.append(t)
187
+ return texts
188
+ except (json.JSONDecodeError, IndexError, TypeError):
189
+ return []
190
+
191
+
192
+ def extract_response_text(raw: str) -> str:
193
+ """Parse full response to get final text."""
194
+ bard_err = re.search(r'BardErrorInfo\s*\[(\d+)\]', raw)
195
+ if bard_err:
196
+ raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{bard_err.group(1)}]")
197
+ last_text = ""
198
+ for line in raw.split("\n"):
199
+ for t in _extract_texts_from_line(line):
200
+ if len(t) > len(last_text):
201
+ last_text = t
202
+ return clean_text(last_text)
203
+
204
+
205
+ def generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
206
+ """Non-streaming generation with retry."""
207
+ body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields).encode()
208
+ url = _get_url()
209
+ headers = _build_headers()
210
+ ctx = _get_ssl_ctx()
211
+ proxy = CONFIG.get("proxy")
212
+
213
+ last_err = None
214
+ for attempt in range(CONFIG["retry_attempts"]):
215
+ try:
216
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
217
+ if proxy:
218
+ opener = urllib.request.build_opener(
219
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
220
+ urllib.request.HTTPSHandler(context=ctx)
221
+ )
222
+ resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
223
+ else:
224
+ resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
225
+ raw = resp.read().decode("utf-8", errors="replace")
226
+ return extract_response_text(raw)
227
+ except Exception as e:
228
+ last_err = e
229
+ if attempt < CONFIG["retry_attempts"] - 1:
230
+ log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
231
+ time.sleep(CONFIG["retry_delay_sec"])
232
+ raise last_err
233
+
234
+
235
+ def generate_stream(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None):
236
+ """Streaming generation via httpx with retry on connection failure."""
237
+ if not HAS_HTTPX:
238
+ text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
239
+ if text:
240
+ yield text
241
+ return
242
+
243
+ body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields)
244
+ url = _get_url()
245
+ headers = _build_headers()
246
+ client = _get_httpx_client()
247
+
248
+ last_err = None
249
+ emitted_raw_text = ""
250
+ for attempt in range(CONFIG["retry_attempts"]):
251
+ try:
252
+ with client.stream("POST", url, content=body, headers=headers) as resp:
253
+ resp.raise_for_status()
254
+ buf = ""
255
+ for chunk in resp.iter_text():
256
+ buf += chunk
257
+ if "BardErrorInfo" in buf:
258
+ bard_err = re.search(r'BardErrorInfo\s*\[(\d+)\]', buf)
259
+ if bard_err:
260
+ raise RuntimeError(
261
+ f"Gemini upstream rejected request: BardErrorInfo [{bard_err.group(1)}]"
262
+ )
263
+ while "\n" in buf:
264
+ line, buf = buf.split("\n", 1)
265
+ for t in _extract_texts_from_line(line):
266
+ if t == emitted_raw_text or emitted_raw_text.startswith(t):
267
+ continue
268
+ if not t.startswith(emitted_raw_text):
269
+ raise RuntimeError("Gemini stream content changed during retry")
270
+ delta = clean_text(t[len(emitted_raw_text):], strip=False)
271
+ emitted_raw_text = t
272
+ if delta:
273
+ yield delta
274
+ return
275
+ except Exception as e:
276
+ last_err = e
277
+ if attempt < CONFIG["retry_attempts"] - 1:
278
+ log(f"Stream retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
279
+ time.sleep(CONFIG["retry_delay_sec"])
280
+ raise last_err
gemini_web2api/models.py CHANGED
@@ -1,64 +1,68 @@
1
- """Model definitions and mapping from Gemini frontend JS source."""
2
-
3
- # MODE_CATEGORY enum from 028-6eb337387583.js:
4
- # 1=FAST, 2=THINKING, 3=PRO, 4=AUTO, 5=FAST_DYNAMIC_THINKING, 6=FLASH_LITE
5
-
6
- MODELS = {
7
- "gemini-3.6-flash": {
8
- "mode": 1, "think": 4,
9
- "desc": "Latest all-around model (Gemini 3.6 Flash)",
10
- },
11
- "gemini-3.5-flash": {
12
- "mode": 1, "think": 4,
13
- "desc": "Alias for gemini-3.6-flash (backend upgraded)",
14
- },
15
- "gemini-3.5-flash-thinking": {
16
- "mode": 2, "think": 0,
17
- "desc": "Deep thinking mode, longest output (~20k chars)",
18
- },
19
- "gemini-3.1-pro": {
20
- "mode": 3, "think": 4,
21
- "desc": "Pro model (requires cookie for real routing)",
22
- },
23
- "gemini-3.1-pro-enhanced": {
24
- "mode": 3, "think": 4, "extra": {31: 2, 80: 3},
25
- "desc": "Pro with enhanced output (experimental)",
26
- },
27
- "gemini-auto": {
28
- "mode": 4, "think": 4,
29
- "desc": "Auto model selection",
30
- },
31
- "gemini-3.5-flash-thinking-lite": {
32
- "mode": 5, "think": 0,
33
- "desc": "Dynamic thinking with adaptive depth",
34
- },
35
- "gemini-flash-lite": {
36
- "mode": 6, "think": 4,
37
- "desc": "Lightweight fast model",
38
- },
39
- }
40
-
41
-
42
- def resolve_model(model_name: str, default: str = "gemini-3.6-flash"):
43
- """Resolve model name to (name, mode_id, think_mode, error, extra_fields).
44
-
45
- Unknown model names fall back to default rather than erroring,
46
- since upstream clients may request arbitrary model identifiers.
47
- """
48
- think_override = None
49
- if "@think=" in model_name:
50
- model_name, think_str = model_name.rsplit("@think=", 1)
51
- try:
52
- think_override = int(think_str)
53
- except ValueError:
54
- return None, None, None, f"Invalid think level: {think_str}", None
55
- cfg = MODELS.get(model_name)
56
- if not cfg:
57
- from .gemini import log
58
- log(f"Unknown model '{model_name}', falling back to '{default}'")
59
- model_name = default
60
- cfg = MODELS[default]
61
- mode_id = cfg["mode"]
62
- think_mode = think_override if think_override is not None else cfg["think"]
63
- extra = cfg.get("extra")
64
- return model_name, mode_id, think_mode, None, extra
 
 
 
 
 
1
+ """Model definitions and mapping from Gemini frontend JS source."""
2
+
3
+ # MODE_CATEGORY enum from 028-6eb337387583.js:
4
+ # 1=FAST, 2=THINKING, 3=PRO, 4=AUTO, 5=FAST_DYNAMIC_THINKING, 6=FLASH_LITE
5
+
6
+ MODELS = {
7
+ "gemini-3.7-flash": {
8
+ "mode": 1, "think": 4,
9
+ "desc": "Latest all-around model (Gemini 3.7 Flash)",
10
+ },
11
+ "gemini-3.6-flash": {
12
+ "mode": 1, "think": 4,
13
+ "desc": "All-around model (Gemini 3.6 Flash)",
14
+ },
15
+ "gemini-3.5-flash": {
16
+ "mode": 1, "think": 4,
17
+ "desc": "Alias for gemini-3.6-flash (backend upgraded)",
18
+ },
19
+ "gemini-3.5-flash-thinking": {
20
+ "mode": 2, "think": 0,
21
+ "desc": "Deep thinking mode, longest output (~20k chars)",
22
+ },
23
+ "gemini-3.1-pro": {
24
+ "mode": 3, "think": 4,
25
+ "desc": "Pro model (requires cookie for real routing)",
26
+ },
27
+ "gemini-3.1-pro-enhanced": {
28
+ "mode": 3, "think": 4, "extra": {31: 2, 80: 3},
29
+ "desc": "Pro with enhanced output (experimental)",
30
+ },
31
+ "gemini-auto": {
32
+ "mode": 4, "think": 4,
33
+ "desc": "Auto model selection",
34
+ },
35
+ "gemini-3.5-flash-thinking-lite": {
36
+ "mode": 5, "think": 0,
37
+ "desc": "Dynamic thinking with adaptive depth",
38
+ },
39
+ "gemini-flash-lite": {
40
+ "mode": 6, "think": 4,
41
+ "desc": "Lightweight fast model",
42
+ },
43
+ }
44
+
45
+
46
+ def resolve_model(model_name: str, default: str = "gemini-3.6-flash"):
47
+ """Resolve model name to (name, mode_id, think_mode, error, extra_fields).
48
+
49
+ Unknown model names fall back to default rather than erroring,
50
+ since upstream clients may request arbitrary model identifiers.
51
+ """
52
+ think_override = None
53
+ if "@think=" in model_name:
54
+ model_name, think_str = model_name.rsplit("@think=", 1)
55
+ try:
56
+ think_override = int(think_str)
57
+ except ValueError:
58
+ return None, None, None, f"Invalid think level: {think_str}", None
59
+ cfg = MODELS.get(model_name)
60
+ if not cfg:
61
+ from .gemini import log
62
+ log(f"Unknown model '{model_name}', falling back to '{default}'")
63
+ model_name = default
64
+ cfg = MODELS[default]
65
+ mode_id = cfg["mode"]
66
+ think_mode = think_override if think_override is not None else cfg["think"]
67
+ extra = cfg.get("extra")
68
+ return model_name, mode_id, think_mode, None, extra
gemini_web2api/multimodal.py CHANGED
@@ -1,127 +1,175 @@
1
- """Multimodal: Scotty resumable upload for Gemini image input."""
2
- import json
3
- import base64
4
- import urllib.request
5
- import urllib.parse
6
- import time
7
- import ssl
8
- import re
9
-
10
- from .config import CONFIG
11
- from .gemini import load_cookie, make_sapisidhash, _get_ssl_ctx, log, resin_proxy_url
12
-
13
-
14
- def _get_page_tokens() -> dict:
15
- """Fetch WIZ_global_data tokens from Gemini page (Push-ID, X-Client-Pctx)."""
16
- headers = {
17
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
18
- }
19
- cookie_str, sapisid = load_cookie()
20
- if cookie_str:
21
- headers["Cookie"] = cookie_str
22
- try:
23
- req = urllib.request.Request(resin_proxy_url("https://gemini.google.com/app"), headers=headers)
24
- resp = urllib.request.urlopen(req, context=_get_ssl_ctx(), timeout=30)
25
- html = resp.read().decode()
26
- tokens = {}
27
- for key, pattern in [
28
- ("push_id", r'"qKIAYe":"([^"]+)"'),
29
- ("pctx", r'"Ylro7b":"([^"]+)"'),
30
- ("at", r'"thykhd":"([^"]+)"'),
31
- ]:
32
- m = re.search(pattern, html)
33
- if m:
34
- tokens[key] = m.group(1)
35
- return tokens
36
- except Exception as e:
37
- log(f"Page token fetch failed: {e}")
38
- return {}
39
-
40
-
41
- _page_tokens_cache = {"tokens": {}, "ts": 0}
42
-
43
-
44
- def _cached_page_tokens() -> dict:
45
- now = time.time()
46
- if now - _page_tokens_cache["ts"] > 600:
47
- _page_tokens_cache["tokens"] = _get_page_tokens()
48
- _page_tokens_cache["ts"] = now
49
- return _page_tokens_cache["tokens"]
50
-
51
-
52
- def upload_image(image_bytes: bytes, filename: str = "image.png", mime_type: str = "image/png") -> str:
53
- """Upload image via Scotty resumable upload. Returns file reference path."""
54
- tokens = _cached_page_tokens()
55
- push_id = tokens.get("push_id", "feeds/mcudyrk2a4khkz")
56
- pctx = tokens.get("pctx", "CgcSBWjK7pYx")
57
-
58
- cookie_str, sapisid = load_cookie()
59
- ctx = _get_ssl_ctx()
60
- proxy = CONFIG.get("proxy")
61
-
62
- # Step 1: Initiate resumable upload
63
- start_headers = {
64
- "Push-ID": push_id,
65
- "X-Tenant-Id": "bard-storage",
66
- "X-Client-Pctx": pctx,
67
- "X-Goog-Upload-Header-Content-Length": str(len(image_bytes)),
68
- "X-Goog-Upload-Header-Content-Type": mime_type,
69
- "X-Goog-Upload-Protocol": "resumable",
70
- "X-Goog-Upload-Command": "start",
71
- "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
72
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
73
- }
74
- if cookie_str:
75
- start_headers["Cookie"] = cookie_str
76
- if sapisid:
77
- start_headers["Authorization"] = make_sapisidhash(sapisid)
78
-
79
- start_url = resin_proxy_url("https://content-push.googleapis.com/upload/")
80
- req = urllib.request.Request(start_url, data=b"", headers=start_headers, method="POST")
81
-
82
- if proxy:
83
- opener = urllib.request.build_opener(
84
- urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
85
- urllib.request.HTTPSHandler(context=ctx)
86
- )
87
- resp = opener.open(req, timeout=30)
88
- else:
89
- resp = urllib.request.urlopen(req, context=ctx, timeout=30)
90
-
91
- upload_url = resp.headers.get("X-Goog-Upload-URL") or resp.headers.get("x-goog-upload-url")
92
- if not upload_url:
93
- raise RuntimeError(f"No upload URL in response headers: {dict(resp.headers)}")
94
-
95
- log(f"Upload session started: {upload_url[:80]}...")
96
-
97
- # Step 2: Upload file data + finalize
98
- upload_headers = {
99
- "X-Goog-Upload-Command": "upload, finalize",
100
- "X-Goog-Upload-Offset": "0",
101
- "Content-Type": "application/octet-stream",
102
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
103
- }
104
-
105
- req2 = urllib.request.Request(resin_proxy_url(upload_url), data=image_bytes, headers=upload_headers, method="POST")
106
- if proxy:
107
- resp2 = opener.open(req2, timeout=60)
108
- else:
109
- resp2 = urllib.request.urlopen(req2, context=ctx, timeout=60)
110
-
111
- file_ref = resp2.read().decode().strip()
112
- if not file_ref or not file_ref.startswith("/"):
113
- raise RuntimeError(f"Invalid file reference: {file_ref[:100]}")
114
-
115
- log(f"Image uploaded: {filename} -> {file_ref[:50]}...")
116
- return file_ref
117
-
118
-
119
- def fetch_image_bytes(url: str) -> bytes:
120
- """Fetch image from URL."""
121
- try:
122
- req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
123
- resp = urllib.request.urlopen(req, timeout=30)
124
- return resp.read()
125
- except Exception as e:
126
- log(f"Image fetch failed: {e}")
127
- return b""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multimodal: Scotty resumable upload for Gemini image input."""
2
+ import json
3
+ import base64
4
+ import urllib.request
5
+ import urllib.parse
6
+ import time
7
+ import ssl
8
+ import re
9
+ from urllib.parse import urlparse
10
+
11
+ from .config import CONFIG
12
+ from .gemini import load_cookie, make_sapisidhash, _get_ssl_ctx, log
13
+
14
+
15
+ def _get_page_tokens() -> dict:
16
+ """Fetch WIZ_global_data tokens from Gemini page (Push-ID, X-Client-Pctx)."""
17
+ headers = {
18
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
19
+ }
20
+ cookie_str, sapisid = load_cookie()
21
+ if cookie_str:
22
+ headers["Cookie"] = cookie_str
23
+ if sapisid:
24
+ headers["Authorization"] = make_sapisidhash(sapisid)
25
+ try:
26
+ req = urllib.request.Request("https://gemini.google.com/app", headers=headers)
27
+ proxy = CONFIG.get("proxy")
28
+ if proxy:
29
+ opener = urllib.request.build_opener(
30
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
31
+ urllib.request.HTTPSHandler(context=_get_ssl_ctx()),
32
+ )
33
+ resp = opener.open(req, timeout=30)
34
+ else:
35
+ resp = urllib.request.urlopen(req, context=_get_ssl_ctx(), timeout=30)
36
+ html = resp.read().decode()
37
+ tokens = {}
38
+ for key, pattern in [
39
+ ("push_id", r'"qKIAYe":"([^"]+)"'),
40
+ ("pctx", r'"Ylro7b":"([^"]+)"'),
41
+ ("at", r'"thykhd":"([^"]+)"'),
42
+ ]:
43
+ m = re.search(pattern, html)
44
+ if m:
45
+ tokens[key] = m.group(1)
46
+ return tokens
47
+ except Exception as e:
48
+ log(f"Page token fetch failed: {e}")
49
+ return {}
50
+
51
+
52
+ _page_tokens_cache = {"tokens": {}, "ts": 0}
53
+
54
+
55
+ def _cached_page_tokens() -> dict:
56
+ now = time.time()
57
+ if now - _page_tokens_cache["ts"] > 600:
58
+ _page_tokens_cache["tokens"] = _get_page_tokens()
59
+ _page_tokens_cache["ts"] = now
60
+ return _page_tokens_cache["tokens"]
61
+
62
+
63
+ def detect_image_mime(image_bytes: bytes, fallback: str = "image/png") -> str:
64
+ """Infer a common raster image MIME type from its file signature."""
65
+ if not isinstance(image_bytes, bytes):
66
+ return fallback
67
+ if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
68
+ return "image/png"
69
+ if image_bytes.startswith(b"\xff\xd8\xff"):
70
+ return "image/jpeg"
71
+ if image_bytes.startswith((b"GIF87a", b"GIF89a")):
72
+ return "image/gif"
73
+ if image_bytes.startswith(b"RIFF") and image_bytes[8:12] == b"WEBP":
74
+ return "image/webp"
75
+ if image_bytes.startswith(b"BM"):
76
+ return "image/bmp"
77
+ if image_bytes.startswith((b"II*\x00", b"MM\x00*")):
78
+ return "image/tiff"
79
+ if len(image_bytes) >= 12 and image_bytes[4:8] == b"ftyp":
80
+ brand = image_bytes[8:12]
81
+ if brand in (b"avif", b"avis"):
82
+ return "image/avif"
83
+ if brand in (b"heic", b"heix", b"hevc", b"hevx"):
84
+ return "image/heic"
85
+ return fallback
86
+
87
+
88
+ def upload_image(image_bytes: bytes, filename: str = "image.png", mime_type: str = "image/png") -> str:
89
+ """Upload image via Scotty resumable upload. Returns file reference path."""
90
+ tokens = _cached_page_tokens()
91
+ push_id = tokens.get("push_id", "feeds/mcudyrk2a4khkz")
92
+ pctx = tokens.get("pctx", "CgcSBWjK7pYx")
93
+
94
+ cookie_str, sapisid = load_cookie()
95
+ ctx = _get_ssl_ctx()
96
+ proxy = CONFIG.get("proxy")
97
+
98
+ # Step 1: Initiate resumable upload
99
+ start_headers = {
100
+ "Push-ID": push_id,
101
+ "X-Tenant-Id": "bard-storage",
102
+ "X-Client-Pctx": pctx,
103
+ "X-Goog-Upload-Header-Content-Length": str(len(image_bytes)),
104
+ "X-Goog-Upload-Header-Content-Type": mime_type,
105
+ "X-Goog-Upload-Protocol": "resumable",
106
+ "X-Goog-Upload-Command": "start",
107
+ "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
108
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
109
+ }
110
+ if cookie_str:
111
+ start_headers["Cookie"] = cookie_str
112
+ if sapisid:
113
+ start_headers["Authorization"] = make_sapisidhash(sapisid)
114
+
115
+ start_url = "https://content-push.googleapis.com/upload/"
116
+ req = urllib.request.Request(start_url, data=b"", headers=start_headers, method="POST")
117
+
118
+ if proxy:
119
+ opener = urllib.request.build_opener(
120
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
121
+ urllib.request.HTTPSHandler(context=ctx)
122
+ )
123
+ resp = opener.open(req, timeout=30)
124
+ else:
125
+ resp = urllib.request.urlopen(req, context=ctx, timeout=30)
126
+
127
+ upload_url = resp.headers.get("X-Goog-Upload-URL") or resp.headers.get("x-goog-upload-url")
128
+ if not upload_url:
129
+ raise RuntimeError(f"No upload URL in response headers: {dict(resp.headers)}")
130
+
131
+ log(f"Upload session started: {upload_url[:80]}...")
132
+
133
+ # Step 2: Upload file data + finalize
134
+ upload_headers = {
135
+ "X-Goog-Upload-Command": "upload, finalize",
136
+ "X-Goog-Upload-Offset": "0",
137
+ "Content-Type": "application/octet-stream",
138
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
139
+ }
140
+
141
+ req2 = urllib.request.Request(upload_url, data=image_bytes, headers=upload_headers, method="POST")
142
+ if proxy:
143
+ resp2 = opener.open(req2, timeout=60)
144
+ else:
145
+ resp2 = urllib.request.urlopen(req2, context=ctx, timeout=60)
146
+
147
+ file_ref = resp2.read().decode().strip()
148
+ if not file_ref or not file_ref.startswith("/"):
149
+ raise RuntimeError(f"Invalid file reference: {file_ref[:100]}")
150
+
151
+ log(f"Image uploaded: {filename} -> {file_ref[:50]}...")
152
+ return file_ref
153
+
154
+
155
+ def fetch_image_bytes(url: str) -> bytes:
156
+ """Fetch image from URL."""
157
+ parsed = urlparse(url)
158
+ if parsed.scheme not in ("http", "https"):
159
+ log(f"Image fetch skipped for unsupported URL scheme: {parsed.scheme or 'none'}")
160
+ return b""
161
+ try:
162
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
163
+ proxy = CONFIG.get("proxy")
164
+ if proxy:
165
+ opener = urllib.request.build_opener(
166
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
167
+ urllib.request.HTTPSHandler(context=_get_ssl_ctx()),
168
+ )
169
+ resp = opener.open(req, timeout=30)
170
+ else:
171
+ resp = urllib.request.urlopen(req, context=_get_ssl_ctx(), timeout=30)
172
+ return resp.read()
173
+ except Exception as e:
174
+ log(f"Image fetch failed: {e}")
175
+ return b""
gemini_web2api/server.py CHANGED
@@ -1,424 +1,596 @@
1
- """HTTP server: OpenAI-compatible API endpoints."""
2
- import json
3
- import time
4
- import uuid
5
- import re
6
- from http.server import HTTPServer, BaseHTTPRequestHandler
7
- from socketserver import ThreadingMixIn
8
-
9
- from .config import CONFIG
10
- from .models import MODELS, resolve_model
11
- from .gemini import generate, generate_stream, log
12
- from .tools import messages_to_prompt, parse_tool_calls, google_contents_to_prompt, parse_google_function_calls
13
- from .multimodal import upload_image, fetch_image_bytes
14
- from . import __version__
15
-
16
-
17
- def _usage(prompt: str, text: str) -> dict:
18
- p = len(prompt) // 4
19
- c = len(text or "") // 4
20
- return {"prompt_tokens": p, "completion_tokens": c, "total_tokens": p + c}
21
-
22
-
23
- def _upload_images(images: list) -> list:
24
- """Upload images and return list of file references. Returns None if no images."""
25
- if not images:
26
- return None
27
- file_refs = []
28
- for item in images:
29
- try:
30
- if isinstance(item, tuple) and len(item) == 2:
31
- data, mime = item
32
- if isinstance(data, str):
33
- data = fetch_image_bytes(data)
34
- mime = mime or "image/png"
35
- if data:
36
- ref = upload_image(data, "image.png", mime or "image/png")
37
- file_refs.append(ref)
38
- except Exception as e:
39
- log(f"Image upload failed: {e}")
40
- return file_refs if file_refs else None
41
-
42
-
43
- class GeminiHandler(BaseHTTPRequestHandler):
44
- def log_message(self, fmt, *args):
45
- log(fmt % args)
46
-
47
- def send_json(self, data, status=200):
48
- body = json.dumps(data, ensure_ascii=False).encode()
49
- self.send_response(status)
50
- self.send_header("Content-Type", "application/json")
51
- self.send_header("Access-Control-Allow-Origin", "*")
52
- self.send_header("Content-Length", str(len(body)))
53
- self.end_headers()
54
- self.wfile.write(body)
55
-
56
- def _start_sse(self):
57
- self.send_response(200)
58
- self.send_header("Content-Type", "text/event-stream")
59
- self.send_header("Cache-Control", "no-cache")
60
- self.send_header("Access-Control-Allow-Origin", "*")
61
- self.end_headers()
62
-
63
- def _parse_body(self, body: bytes) -> dict:
64
- try:
65
- return json.loads(body)
66
- except (json.JSONDecodeError, ValueError):
67
- return None
68
-
69
- def _authorized(self):
70
- keys = CONFIG.get("api_keys") or []
71
- if not keys:
72
- return True
73
- # Authorization: Bearer <key>
74
- auth = self.headers.get("Authorization", "")
75
- if auth.startswith("Bearer ") and auth[7:] in keys:
76
- return True
77
- # header keys (OpenAI x-api-key / Google x-goog-api-key)
78
- for h in ("x-api-key", "x-goog-api-key"):
79
- if self.headers.get(h, "") in keys:
80
- return True
81
- # query param ?key= (Gemini CLI native style)
82
- if "?" in self.path:
83
- for pair in self.path.split("?", 1)[1].split("&"):
84
- if pair.startswith("key=") and pair[4:] in keys:
85
- return True
86
- return False
87
-
88
- def do_OPTIONS(self):
89
- self.send_response(204)
90
- self.send_header("Access-Control-Allow-Origin", "*")
91
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
92
- self.send_header("Access-Control-Allow-Headers", "*")
93
- self.end_headers()
94
-
95
- def do_GET(self):
96
- try:
97
- if self.path.startswith("/v1") and not self._authorized():
98
- self.send_json({"error": {"message": "invalid api key"}}, 401)
99
- return
100
- if self.path == "/v1/models":
101
- self.send_json({"object": "list", "data": [
102
- {"id": n, "object": "model", "created": 1700000000,
103
- "owned_by": "google", "description": c["desc"]}
104
- for n, c in MODELS.items()
105
- ]})
106
- elif self.path.startswith("/v1beta/models"):
107
- self.send_json({"models": [
108
- {"name": f"models/{n}", "displayName": n, "description": c["desc"],
109
- "supportedGenerationMethods": ["generateContent", "streamGenerateContent"]}
110
- for n, c in MODELS.items()
111
- ]})
112
- elif self.path == "/":
113
- self.send_json({"status": "ok", "version": __version__, "models": list(MODELS.keys())})
114
- else:
115
- self.send_json({"error": "not found"}, 404)
116
- except (BrokenPipeError, ConnectionResetError):
117
- pass
118
-
119
- def do_POST(self):
120
- try:
121
- if self.path.startswith("/v1") and not self._authorized():
122
- self.send_json({"error": {"message": "invalid api key"}}, 401)
123
- return
124
- length = int(self.headers.get("Content-Length", 0))
125
- body = self.rfile.read(length) if length else b""
126
- if self.path == "/v1/chat/completions":
127
- self._handle_chat(body)
128
- elif self.path == "/v1/responses":
129
- self._handle_responses(body)
130
- elif ":generateContent" in self.path:
131
- self._handle_google_generate(body, stream=False)
132
- elif ":streamGenerateContent" in self.path:
133
- self._handle_google_generate(body, stream=True)
134
- else:
135
- self.send_json({"error": "not found"}, 404)
136
- except (BrokenPipeError, ConnectionResetError):
137
- pass
138
- except Exception as e:
139
- log(f"POST error: {e}")
140
- try:
141
- self.send_json({"error": {"message": str(e)}}, 500)
142
- except:
143
- pass
144
-
145
- # ─── /v1/chat/completions ─────────────────────────────────────────────────
146
-
147
- def _handle_chat(self, body: bytes):
148
- req = self._parse_body(body)
149
- if req is None:
150
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
151
- return
152
- model_name, model_id, think_mode, err, extra_fields = resolve_model(
153
- req.get("model", CONFIG["default_model"]))
154
- if err:
155
- self.send_json({"error": {"message": err}}, 400)
156
- return
157
-
158
- tools = req.get("tools")
159
- tool_choice = req.get("tool_choice", "auto")
160
- prompt, images = messages_to_prompt(req.get("messages", []), tools, tool_choice)
161
- if not prompt.strip():
162
- self.send_json({"error": {"message": "empty prompt"}}, 400)
163
- return
164
-
165
- stream = req.get("stream", False)
166
- cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
167
-
168
- if stream and (not tools or tool_choice == "none"):
169
- try:
170
- self._start_sse()
171
- for delta in generate_stream(prompt, model_id, think_mode, _upload_images(images), extra_fields):
172
- chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
173
- "model": model_name, "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}]}
174
- self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
175
- self.wfile.flush()
176
- end = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
177
- "model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
178
- self.wfile.write(f"data: {json.dumps(end)}\n\n".encode())
179
- self.wfile.write(b"data: [DONE]\n\n")
180
- self.wfile.flush()
181
- except (BrokenPipeError, ConnectionResetError):
182
- pass
183
- return
184
-
185
- try:
186
- text = generate(prompt, model_id, think_mode, _upload_images(images), extra_fields)
187
- except Exception as e:
188
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
189
- return
190
-
191
- tool_calls = None
192
- if tools and text and tool_choice != "none":
193
- text, tool_calls = parse_tool_calls(text)
194
- msg = {"role": "assistant", "content": text or None}
195
- if tool_calls:
196
- msg["tool_calls"] = tool_calls
197
- finish = "tool_calls" if tool_calls else "stop"
198
-
199
- if stream:
200
- self._start_sse()
201
- chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
202
- "model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
203
- self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
204
- self.wfile.write(b"data: [DONE]\n\n")
205
- self.wfile.flush()
206
- else:
207
- self.send_json({
208
- "id": cid, "object": "chat.completion", "created": int(time.time()),
209
- "model": model_name,
210
- "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
211
- "usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text or "")//4,
212
- "total_tokens": (len(prompt)+len(text or ""))//4},
213
- })
214
-
215
- # ─── /v1/responses (Codex CLI) ───────────────────────────────────────────
216
-
217
- def _handle_responses(self, body: bytes):
218
- req = self._parse_body(body)
219
- if req is None:
220
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
221
- return
222
- model_name, model_id, think_mode, err, extra_fields = resolve_model(
223
- req.get("model", CONFIG["default_model"]))
224
- if err:
225
- self.send_json({"error": {"message": err}}, 400)
226
- return
227
-
228
- input_items = req.get("input", [])
229
- tools = req.get("tools")
230
- messages = []
231
- if req.get("instructions"):
232
- messages.append({"role": "system", "content": req["instructions"]})
233
- if isinstance(input_items, str):
234
- messages.append({"role": "user", "content": input_items})
235
- elif isinstance(input_items, list):
236
- for item in input_items:
237
- if isinstance(item, str):
238
- messages.append({"role": "user", "content": item})
239
- elif isinstance(item, dict):
240
- if item.get("type") == "function_call_output":
241
- messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
242
- "name": item.get("name", ""), "content": item.get("output", "")})
243
- elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
244
- cp = item.get("content", [])
245
- text_acc, tc_list = "", []
246
- if isinstance(cp, list):
247
- for c in cp:
248
- if isinstance(c, dict):
249
- if c.get("type") == "output_text": text_acc += c.get("text", "")
250
- elif c.get("type") == "function_call": tc_list.append(c)
251
- elif isinstance(cp, str):
252
- text_acc = cp
253
- m = {"role": "assistant", "content": text_acc or None}
254
- if tc_list:
255
- m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
256
- "function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
257
- for i, tc in enumerate(tc_list)]
258
- messages.append(m)
259
- else:
260
- role = item.get("role", "user")
261
- content = item.get("content", "")
262
- if isinstance(content, list):
263
- content = " ".join(c.get("text", "") for c in content if c.get("type") in ("text", "input_text"))
264
- messages.append({"role": role, "content": content})
265
-
266
- if tools:
267
- tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
268
- if t.get("type") == "function" and "function" not in t else t for t in tools]
269
-
270
- tool_choice = req.get("tool_choice", "auto")
271
- prompt, images = messages_to_prompt(messages, tools, tool_choice)
272
- if not prompt.strip():
273
- self.send_json({"error": {"message": "empty input"}}, 400)
274
- return
275
-
276
- try:
277
- text = generate(prompt, model_id, think_mode, _upload_images(images), extra_fields)
278
- except Exception as e:
279
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
280
- return
281
-
282
- tool_calls = None
283
- if tools and text and tool_choice != "none":
284
- text, tool_calls = parse_tool_calls(text)
285
-
286
- rid = f"resp_{uuid.uuid4().hex[:16]}"
287
- mid = f"msg_{uuid.uuid4().hex[:12]}"
288
- output = []
289
- if tool_calls:
290
- for tc in tool_calls:
291
- output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
292
- "name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
293
- if text or not tool_calls:
294
- output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
295
- "content": [{"type": "output_text", "text": text or "", "annotations": []}]})
296
-
297
- if req.get("stream"):
298
- self.send_response(200)
299
- self.send_header("Content-Type", "text/event-stream")
300
- self.send_header("Cache-Control", "no-cache")
301
- self.send_header("Access-Control-Allow-Origin", "*")
302
- self.end_headers()
303
- ev = {"type": "response.created", "response": {"id": rid, "object": "response", "status": "in_progress", "model": model_name, "output": []}}
304
- self.wfile.write(f"event: response.created\ndata: {json.dumps(ev)}\n\n".encode())
305
- for item in output:
306
- if item["type"] == "function_call":
307
- ev = {"type": "response.function_call_arguments.done", "item_id": item["id"], "call_id": item["call_id"], "name": item["name"], "arguments": item["arguments"]}
308
- self.wfile.write(f"event: response.function_call_arguments.done\ndata: {json.dumps(ev)}\n\n".encode())
309
- elif item["type"] == "message":
310
- for ci, cp in enumerate(item["content"]):
311
- ev = {"type": "response.output_text.done", "item_id": item["id"], "content_index": ci, "text": cp["text"]}
312
- self.wfile.write(f"event: response.output_text.done\ndata: {json.dumps(ev)}\n\n".encode())
313
- resp_obj = {"id": rid, "object": "response", "status": "completed", "model": model_name, "output": output,
314
- "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text or "")//4, "total_tokens": (len(prompt)+len(text or ""))//4}}
315
- self.wfile.write(f"event: response.completed\ndata: {json.dumps({'type': 'response.completed', 'response': resp_obj})}\n\n".encode())
316
- self.wfile.flush()
317
- else:
318
- self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
319
- "model": model_name, "output": output,
320
- "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text or "")//4, "total_tokens": (len(prompt)+len(text or ""))//4}})
321
-
322
- # ─── /v1beta/models (Google Gemini CLI) ──────────────────────────────────
323
-
324
- def _handle_google_generate(self, body: bytes, stream: bool):
325
- req = self._parse_body(body)
326
- if req is None:
327
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
328
- return
329
- m = re.match(r'/v1beta/models/([^:?]+)', self.path)
330
- model_name = m.group(1) if m else CONFIG["default_model"]
331
- model_name, model_id, think_mode, err, extra_fields = resolve_model(model_name)
332
- if err:
333
- self.send_json({"error": {"message": err}}, 400)
334
- return
335
-
336
- tool_config = req.get("toolConfig", {})
337
- fc_mode = tool_config.get("functionCallingConfig", {}).get("mode", "AUTO")
338
- has_tools = bool(req.get("tools")) and fc_mode != "NONE"
339
- prompt, images = google_contents_to_prompt(req)
340
- if not prompt.strip():
341
- self.send_json({"error": {"message": "empty content"}}, 400)
342
- return
343
-
344
- file_refs = _upload_images(images)
345
- log(f"Google API: model={model_name} stream={stream} tools={has_tools} prompt_len={len(prompt)}")
346
-
347
- if stream and not has_tools:
348
- try:
349
- self._start_sse()
350
- full_text = ""
351
- for delta in generate_stream(prompt, model_id, think_mode, file_refs, extra_fields):
352
- if not delta:
353
- continue
354
- full_text += delta
355
- chunk_obj = {
356
- "candidates": [{"content": {"parts": [{"text": delta}], "role": "model"}, "index": 0}],
357
- "modelVersion": model_name,
358
- }
359
- self.wfile.write(f"data: {json.dumps(chunk_obj, ensure_ascii=False)}\n\n".encode())
360
- self.wfile.flush()
361
- final_chunk = {
362
- "candidates": [{"finishReason": "STOP", "index": 0}],
363
- "usageMetadata": {
364
- "promptTokenCount": len(prompt) // 4,
365
- "candidatesTokenCount": len(full_text) // 4,
366
- "totalTokenCount": (len(prompt) + len(full_text)) // 4,
367
- },
368
- "modelVersion": model_name,
369
- }
370
- self.wfile.write(f"data: {json.dumps(final_chunk, ensure_ascii=False)}\n\n".encode())
371
- self.wfile.flush()
372
- except (BrokenPipeError, ConnectionResetError):
373
- pass
374
- return
375
-
376
- try:
377
- text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
378
- except Exception as e:
379
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
380
- return
381
-
382
- if not text:
383
- log("Warning: empty response from Gemini")
384
-
385
- response_parts = []
386
- if has_tools and text:
387
- clean_text, function_calls = parse_google_function_calls(text)
388
- if function_calls:
389
- if clean_text:
390
- response_parts.append({"text": clean_text})
391
- for fc in function_calls:
392
- response_parts.append({"functionCall": {"name": fc["name"], "args": fc["args"]}})
393
- else:
394
- response_parts.append({"text": text})
395
- else:
396
- response_parts.append({"text": text or "I apologize, but I was unable to generate a response. Please try again."})
397
-
398
- candidate = {
399
- "content": {"parts": response_parts, "role": "model"},
400
- "finishReason": "STOP",
401
- "index": 0,
402
- }
403
- usage = {
404
- "promptTokenCount": len(prompt) // 4,
405
- "candidatesTokenCount": len(text or "") // 4,
406
- "totalTokenCount": (len(prompt) + len(text or "")) // 4,
407
- }
408
- response_obj = {
409
- "candidates": [candidate],
410
- "usageMetadata": usage,
411
- "modelVersion": model_name,
412
- }
413
-
414
- if stream:
415
- self._start_sse()
416
- self.wfile.write(f"data: {json.dumps(response_obj, ensure_ascii=False)}\n\n".encode())
417
- self.wfile.flush()
418
- else:
419
- self.send_json(response_obj)
420
-
421
-
422
- class ThreadedServer(ThreadingMixIn, HTTPServer):
423
- daemon_threads = True
424
- allow_reuse_address = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP server: OpenAI-compatible API endpoints."""
2
+ import json
3
+ import time
4
+ import uuid
5
+ import re
6
+ from http.server import HTTPServer, BaseHTTPRequestHandler
7
+ from socketserver import ThreadingMixIn
8
+
9
+ from .config import CONFIG
10
+ from .models import MODELS, resolve_model
11
+ from .gemini import generate, generate_stream, log
12
+ from .tools import messages_to_prompt, parse_tool_calls, google_contents_to_prompt, parse_google_function_calls
13
+ from .multimodal import detect_image_mime, fetch_image_bytes, upload_image
14
+ from . import __version__
15
+
16
+
17
+ def _usage(prompt: str, text: str) -> dict:
18
+ p = len(prompt) // 4
19
+ c = len(text or "") // 4
20
+ return {"prompt_tokens": p, "completion_tokens": c, "total_tokens": p + c}
21
+
22
+
23
+ def _upload_images(images: list) -> list:
24
+ """Upload images and return list of file references. Returns None if no images."""
25
+ if not images:
26
+ return None
27
+ file_refs = []
28
+ for item in images:
29
+ if not (isinstance(item, tuple) and len(item) == 2):
30
+ continue
31
+ data, mime = item
32
+ if isinstance(data, str):
33
+ data = fetch_image_bytes(data)
34
+ mime = mime or "image/png"
35
+ if not data:
36
+ raise RuntimeError("image fetch failed")
37
+ mime = detect_image_mime(data, mime or "image/png")
38
+ try:
39
+ ref = upload_image(data, "image.png", mime or "image/png")
40
+ file_refs.append(ref)
41
+ except Exception as e:
42
+ raise RuntimeError(f"image upload failed: {e}") from e
43
+ return file_refs if file_refs else None
44
+
45
+
46
+ class GeminiHandler(BaseHTTPRequestHandler):
47
+ def log_message(self, fmt, *args):
48
+ client_ip = self.client_address[0] if self.client_address else "-"
49
+ log(f"{client_ip} {fmt % args}")
50
+
51
+ def send_json(self, data, status=200):
52
+ body = json.dumps(data, ensure_ascii=False).encode()
53
+ self.send_response(status)
54
+ self.send_header("Content-Type", "application/json")
55
+ self.send_header("Access-Control-Allow-Origin", "*")
56
+ self.send_header("Content-Length", str(len(body)))
57
+ self.end_headers()
58
+ self.wfile.write(body)
59
+
60
+ def _start_sse(self):
61
+ self.send_response(200)
62
+ self.send_header("Content-Type", "text/event-stream")
63
+ self.send_header("Cache-Control", "no-cache")
64
+ self.send_header("Access-Control-Allow-Origin", "*")
65
+ self.end_headers()
66
+
67
+ def _parse_body(self, body: bytes) -> dict:
68
+ try:
69
+ return json.loads(body)
70
+ except (json.JSONDecodeError, ValueError):
71
+ return None
72
+
73
+ def _read_request_body(self) -> bytes:
74
+ transfer_encoding = self.headers.get("Transfer-Encoding", "")
75
+ if "chunked" in transfer_encoding.lower():
76
+ chunks = []
77
+ while True:
78
+ size_line = self.rfile.readline()
79
+ if not size_line:
80
+ break
81
+ size_text = size_line.split(b";", 1)[0].strip()
82
+ try:
83
+ size = int(size_text, 16)
84
+ except ValueError:
85
+ raise ValueError("invalid chunked request body")
86
+ if size == 0:
87
+ while True:
88
+ trailer = self.rfile.readline()
89
+ if trailer in (b"\r\n", b"\n", b""):
90
+ break
91
+ break
92
+ chunks.append(self.rfile.read(size))
93
+ self.rfile.read(2)
94
+ return b"".join(chunks)
95
+
96
+ length = int(self.headers.get("Content-Length", 0))
97
+ return self.rfile.read(length) if length else b""
98
+
99
+ def _authorized(self):
100
+ keys = CONFIG.get("api_keys") or []
101
+ if not keys:
102
+ return True
103
+ # Authorization: Bearer <key>
104
+ auth = self.headers.get("Authorization", "")
105
+ if auth.startswith("Bearer ") and auth[7:] in keys:
106
+ return True
107
+ # header keys (OpenAI x-api-key / Google x-goog-api-key)
108
+ for h in ("x-api-key", "x-goog-api-key"):
109
+ if self.headers.get(h, "") in keys:
110
+ return True
111
+ # query param ?key= (Gemini CLI native style)
112
+ if "?" in self.path:
113
+ for pair in self.path.split("?", 1)[1].split("&"):
114
+ if pair.startswith("key=") and pair[4:] in keys:
115
+ return True
116
+ return False
117
+
118
+ def do_OPTIONS(self):
119
+ self.send_response(204)
120
+ self.send_header("Access-Control-Allow-Origin", "*")
121
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
122
+ self.send_header("Access-Control-Allow-Headers", "*")
123
+ self.end_headers()
124
+
125
+ def do_GET(self):
126
+ try:
127
+ if self.path.startswith("/v1") and not self._authorized():
128
+ self.send_json({"error": {"message": "invalid api key"}}, 401)
129
+ return
130
+ if self.path == "/v1/models":
131
+ self.send_json({"object": "list", "data": [
132
+ {"id": n, "object": "model", "created": 1700000000,
133
+ "owned_by": "google", "description": c["desc"]}
134
+ for n, c in MODELS.items()
135
+ ]})
136
+ elif self.path.startswith("/v1beta/models"):
137
+ self.send_json({"models": [
138
+ {"name": f"models/{n}", "displayName": n, "description": c["desc"],
139
+ "supportedGenerationMethods": ["generateContent", "streamGenerateContent"]}
140
+ for n, c in MODELS.items()
141
+ ]})
142
+ elif self.path == "/":
143
+ self.send_json({"status": "ok", "version": __version__, "models": list(MODELS.keys())})
144
+ else:
145
+ self.send_json({"error": "not found"}, 404)
146
+ except (BrokenPipeError, ConnectionResetError):
147
+ pass
148
+
149
+ def do_POST(self):
150
+ try:
151
+ if self.path.startswith("/v1") and not self._authorized():
152
+ self.send_json({"error": {"message": "invalid api key"}}, 401)
153
+ return
154
+ body = self._read_request_body()
155
+ if self.path == "/v1/chat/completions":
156
+ self._handle_chat(body)
157
+ elif self.path == "/v1/responses":
158
+ self._handle_responses(body)
159
+ elif ":streamGenerateContent" in self.path:
160
+ self._handle_google_generate(body, stream=True)
161
+ elif ":generateContent" in self.path:
162
+ self._handle_google_generate(body, stream=False)
163
+ else:
164
+ self.send_json({"error": "not found"}, 404)
165
+ except (BrokenPipeError, ConnectionResetError):
166
+ pass
167
+ except Exception as e:
168
+ log(f"POST error: {e}")
169
+ try:
170
+ self.send_json({"error": {"message": str(e)}}, 500)
171
+ except:
172
+ pass
173
+
174
+ # ─── /v1/chat/completions ─────────────────────────────────────────────────
175
+
176
+ def _handle_chat(self, body: bytes):
177
+ req = self._parse_body(body)
178
+ if req is None:
179
+ self.send_json({"error": {"message": "invalid JSON"}}, 400)
180
+ return
181
+ model_name, model_id, think_mode, err, extra_fields = resolve_model(
182
+ req.get("model", CONFIG["default_model"]))
183
+ if err:
184
+ self.send_json({"error": {"message": err}}, 400)
185
+ return
186
+
187
+ tools = req.get("tools")
188
+ tool_choice = req.get("tool_choice", "auto")
189
+ prompt, images = messages_to_prompt(req.get("messages", []), tools, tool_choice)
190
+ if not prompt.strip():
191
+ self.send_json({"error": {"message": "empty prompt"}}, 400)
192
+ return
193
+
194
+ stream = req.get("stream", False)
195
+ cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
196
+ try:
197
+ file_refs = _upload_images(images)
198
+ except RuntimeError as e:
199
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
200
+ return
201
+
202
+ if stream and (not tools or tool_choice == "none"):
203
+ try:
204
+ self._start_sse()
205
+ first_chunk = {
206
+ "id": cid,
207
+ "object": "chat.completion.chunk",
208
+ "created": int(time.time()),
209
+ "model": model_name,
210
+ "choices": [{
211
+ "index": 0,
212
+ "delta": {"role": "assistant"},
213
+ "finish_reason": None,
214
+ }],
215
+ }
216
+ self.wfile.write(f"data: {json.dumps(first_chunk)}\n\n".encode())
217
+ self.wfile.flush()
218
+ for delta in generate_stream(prompt, model_id, think_mode, file_refs, extra_fields):
219
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
220
+ "model": model_name, "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}]}
221
+ self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
222
+ self.wfile.flush()
223
+ end = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
224
+ "model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
225
+ self.wfile.write(f"data: {json.dumps(end)}\n\n".encode())
226
+ self.wfile.write(b"data: [DONE]\n\n")
227
+ self.wfile.flush()
228
+ except (BrokenPipeError, ConnectionResetError):
229
+ pass
230
+ except Exception as e:
231
+ log(f"Stream error: {e}")
232
+ return
233
+
234
+ try:
235
+ text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
236
+ except Exception as e:
237
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
238
+ return
239
+
240
+ tool_calls = None
241
+ if tools and text and tool_choice != "none":
242
+ text, tool_calls = parse_tool_calls(text)
243
+ msg = {"role": "assistant", "content": text or None}
244
+ if tool_calls:
245
+ msg["tool_calls"] = tool_calls
246
+ finish = "tool_calls" if tool_calls else "stop"
247
+
248
+ if stream:
249
+ self._start_sse()
250
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
251
+ "model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
252
+ self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
253
+ self.wfile.write(b"data: [DONE]\n\n")
254
+ self.wfile.flush()
255
+ else:
256
+ self.send_json({
257
+ "id": cid, "object": "chat.completion", "created": int(time.time()),
258
+ "model": model_name,
259
+ "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
260
+ "usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text or "")//4,
261
+ "total_tokens": (len(prompt)+len(text or ""))//4},
262
+ })
263
+
264
+ # ─── /v1/responses (Codex CLI) ───────────────────────────────────────────
265
+
266
+ def _handle_responses(self, body: bytes):
267
+ req = self._parse_body(body)
268
+ if req is None:
269
+ self.send_json({"error": {"message": "invalid JSON"}}, 400)
270
+ return
271
+ model_name, model_id, think_mode, err, extra_fields = resolve_model(
272
+ req.get("model", CONFIG["default_model"]))
273
+ if err:
274
+ self.send_json({"error": {"message": err}}, 400)
275
+ return
276
+
277
+ input_items = req.get("input", [])
278
+ tools = req.get("tools")
279
+ messages = []
280
+ if req.get("instructions"):
281
+ messages.append({"role": "system", "content": req["instructions"]})
282
+ if isinstance(input_items, str):
283
+ messages.append({"role": "user", "content": input_items})
284
+ elif isinstance(input_items, list):
285
+ for item in input_items:
286
+ if isinstance(item, str):
287
+ messages.append({"role": "user", "content": item})
288
+ elif isinstance(item, dict):
289
+ if item.get("type") == "function_call_output":
290
+ messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
291
+ "name": item.get("name", ""), "content": item.get("output", "")})
292
+ elif item.get("type") in ("input_text", "input_image", "image"):
293
+ messages.append({"role": "user", "content": [item]})
294
+ elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
295
+ cp = item.get("content", [])
296
+ text_acc, tc_list = "", []
297
+ if isinstance(cp, list):
298
+ for c in cp:
299
+ if isinstance(c, dict):
300
+ if c.get("type") == "output_text":
301
+ text_acc += c.get("text", "")
302
+ elif c.get("type") == "function_call":
303
+ tc_list.append(c)
304
+ elif isinstance(cp, str):
305
+ text_acc = cp
306
+ m = {"role": "assistant", "content": text_acc or None}
307
+ if tc_list:
308
+ m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
309
+ "function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
310
+ for i, tc in enumerate(tc_list)]
311
+ messages.append(m)
312
+ else:
313
+ role = item.get("role", "user")
314
+ messages.append({"role": role, "content": item.get("content", "")})
315
+
316
+ if tools:
317
+ tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
318
+ if t.get("type") == "function" and "function" not in t else t for t in tools]
319
+
320
+ tool_choice = req.get("tool_choice", "auto")
321
+ prompt, images = messages_to_prompt(messages, tools, tool_choice)
322
+ if not prompt.strip():
323
+ self.send_json({"error": {"message": "empty input"}}, 400)
324
+ return
325
+
326
+ try:
327
+ file_refs = _upload_images(images)
328
+ text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
329
+ except Exception as e:
330
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
331
+ return
332
+
333
+ tool_calls = None
334
+ if tools and text and tool_choice != "none":
335
+ text, tool_calls = parse_tool_calls(text)
336
+
337
+ rid = f"resp_{uuid.uuid4().hex[:16]}"
338
+ mid = f"msg_{uuid.uuid4().hex[:12]}"
339
+ output = []
340
+ if tool_calls:
341
+ for tc in tool_calls:
342
+ output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
343
+ "name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
344
+ if text or not tool_calls:
345
+ output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
346
+ "content": [{"type": "output_text", "text": text or "", "annotations": []}]})
347
+
348
+ if req.get("stream"):
349
+ self._start_sse()
350
+ sequence_number = 0
351
+
352
+ def emit(event_type, **fields):
353
+ nonlocal sequence_number
354
+ sequence_number += 1
355
+ event = {
356
+ "type": event_type,
357
+ "sequence_number": sequence_number,
358
+ **fields,
359
+ }
360
+ self.wfile.write(
361
+ f"event: {event_type}\ndata: {json.dumps(event)}\n\n".encode()
362
+ )
363
+
364
+ usage = {
365
+ "input_tokens": len(prompt) // 4,
366
+ "output_tokens": len(text or "") // 4,
367
+ "total_tokens": (len(prompt) + len(text or "")) // 4,
368
+ }
369
+ base_response = {
370
+ "id": rid,
371
+ "object": "response",
372
+ "created_at": int(time.time()),
373
+ "model": model_name,
374
+ }
375
+ emit(
376
+ "response.created",
377
+ response={
378
+ **base_response,
379
+ "status": "in_progress",
380
+ "output": [],
381
+ "usage": None,
382
+ },
383
+ )
384
+ emit(
385
+ "response.in_progress",
386
+ response={
387
+ **base_response,
388
+ "status": "in_progress",
389
+ "output": [],
390
+ "usage": None,
391
+ },
392
+ )
393
+ for output_index, item in enumerate(output):
394
+ if item["type"] == "function_call":
395
+ pending_item = {
396
+ "type": "function_call",
397
+ "id": item["id"],
398
+ "call_id": item["call_id"],
399
+ "name": item["name"],
400
+ "arguments": "",
401
+ "status": "in_progress",
402
+ }
403
+ emit(
404
+ "response.output_item.added",
405
+ output_index=output_index,
406
+ item=pending_item,
407
+ )
408
+ emit(
409
+ "response.function_call_arguments.delta",
410
+ item_id=item["id"],
411
+ output_index=output_index,
412
+ delta=item["arguments"],
413
+ )
414
+ emit(
415
+ "response.function_call_arguments.done",
416
+ item_id=item["id"],
417
+ output_index=output_index,
418
+ arguments=item["arguments"],
419
+ )
420
+ emit(
421
+ "response.output_item.done",
422
+ output_index=output_index,
423
+ item=item,
424
+ )
425
+ elif item["type"] == "message":
426
+ pending_item = {
427
+ "type": "message",
428
+ "id": item["id"],
429
+ "role": "assistant",
430
+ "status": "in_progress",
431
+ "content": [],
432
+ }
433
+ emit(
434
+ "response.output_item.added",
435
+ output_index=output_index,
436
+ item=pending_item,
437
+ )
438
+ for content_index, content_part in enumerate(item["content"]):
439
+ event_fields = {
440
+ "item_id": item["id"],
441
+ "output_index": output_index,
442
+ "content_index": content_index,
443
+ }
444
+ emit(
445
+ "response.content_part.added",
446
+ **event_fields,
447
+ part={
448
+ "type": "output_text",
449
+ "text": "",
450
+ "annotations": [],
451
+ },
452
+ )
453
+ emit(
454
+ "response.output_text.delta",
455
+ **event_fields,
456
+ delta=content_part["text"],
457
+ )
458
+ emit(
459
+ "response.output_text.done",
460
+ **event_fields,
461
+ text=content_part["text"],
462
+ )
463
+ emit(
464
+ "response.content_part.done",
465
+ **event_fields,
466
+ part=content_part,
467
+ )
468
+ emit(
469
+ "response.output_item.done",
470
+ output_index=output_index,
471
+ item=item,
472
+ )
473
+ emit(
474
+ "response.completed",
475
+ response={
476
+ **base_response,
477
+ "status": "completed",
478
+ "output": output,
479
+ "usage": usage,
480
+ },
481
+ )
482
+ self.wfile.flush()
483
+ else:
484
+ self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
485
+ "model": model_name, "output": output,
486
+ "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text or "")//4, "total_tokens": (len(prompt)+len(text or ""))//4}})
487
+
488
+ # ─── /v1beta/models (Google Gemini CLI) ──────────────────────────────────
489
+
490
+ def _handle_google_generate(self, body: bytes, stream: bool):
491
+ req = self._parse_body(body)
492
+ if req is None:
493
+ self.send_json({"error": {"message": "invalid JSON"}}, 400)
494
+ return
495
+ m = re.match(r'/v1beta/models/([^:?]+)', self.path)
496
+ model_name = m.group(1) if m else CONFIG["default_model"]
497
+ model_name, model_id, think_mode, err, extra_fields = resolve_model(model_name)
498
+ if err:
499
+ self.send_json({"error": {"message": err}}, 400)
500
+ return
501
+
502
+ tool_config = req.get("toolConfig", {})
503
+ fc_mode = tool_config.get("functionCallingConfig", {}).get("mode", "AUTO")
504
+ has_tools = bool(req.get("tools")) and fc_mode != "NONE"
505
+ prompt, images = google_contents_to_prompt(req)
506
+ if not prompt.strip():
507
+ self.send_json({"error": {"message": "empty content"}}, 400)
508
+ return
509
+
510
+ try:
511
+ file_refs = _upload_images(images)
512
+ except RuntimeError as e:
513
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
514
+ return
515
+ log(f"Google API: model={model_name} stream={stream} tools={has_tools} prompt_len={len(prompt)}")
516
+
517
+ if stream and not has_tools:
518
+ try:
519
+ self._start_sse()
520
+ full_text = ""
521
+ for delta in generate_stream(prompt, model_id, think_mode, file_refs, extra_fields):
522
+ if not delta:
523
+ continue
524
+ full_text += delta
525
+ chunk_obj = {
526
+ "candidates": [{"content": {"parts": [{"text": delta}], "role": "model"}, "index": 0}],
527
+ "modelVersion": model_name,
528
+ }
529
+ self.wfile.write(f"data: {json.dumps(chunk_obj, ensure_ascii=False)}\n\n".encode())
530
+ self.wfile.flush()
531
+ final_chunk = {
532
+ "candidates": [{"finishReason": "STOP", "index": 0}],
533
+ "usageMetadata": {
534
+ "promptTokenCount": len(prompt) // 4,
535
+ "candidatesTokenCount": len(full_text) // 4,
536
+ "totalTokenCount": (len(prompt) + len(full_text)) // 4,
537
+ },
538
+ "modelVersion": model_name,
539
+ }
540
+ self.wfile.write(f"data: {json.dumps(final_chunk, ensure_ascii=False)}\n\n".encode())
541
+ self.wfile.flush()
542
+ except (BrokenPipeError, ConnectionResetError):
543
+ pass
544
+ except Exception as e:
545
+ log(f"Google stream error: {e}")
546
+ return
547
+
548
+ try:
549
+ text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
550
+ except Exception as e:
551
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
552
+ return
553
+
554
+ if not text:
555
+ log("Warning: empty response from Gemini")
556
+
557
+ response_parts = []
558
+ if has_tools and text:
559
+ clean_text, function_calls = parse_google_function_calls(text)
560
+ if function_calls:
561
+ if clean_text:
562
+ response_parts.append({"text": clean_text})
563
+ for fc in function_calls:
564
+ response_parts.append({"functionCall": {"name": fc["name"], "args": fc["args"]}})
565
+ else:
566
+ response_parts.append({"text": text})
567
+ else:
568
+ response_parts.append({"text": text or "I apologize, but I was unable to generate a response. Please try again."})
569
+
570
+ candidate = {
571
+ "content": {"parts": response_parts, "role": "model"},
572
+ "finishReason": "STOP",
573
+ "index": 0,
574
+ }
575
+ usage = {
576
+ "promptTokenCount": len(prompt) // 4,
577
+ "candidatesTokenCount": len(text or "") // 4,
578
+ "totalTokenCount": (len(prompt) + len(text or "")) // 4,
579
+ }
580
+ response_obj = {
581
+ "candidates": [candidate],
582
+ "usageMetadata": usage,
583
+ "modelVersion": model_name,
584
+ }
585
+
586
+ if stream:
587
+ self._start_sse()
588
+ self.wfile.write(f"data: {json.dumps(response_obj, ensure_ascii=False)}\n\n".encode())
589
+ self.wfile.flush()
590
+ else:
591
+ self.send_json(response_obj)
592
+
593
+
594
+ class ThreadedServer(ThreadingMixIn, HTTPServer):
595
+ daemon_threads = True
596
+ allow_reuse_address = True
gemini_web2api/tools.py CHANGED
@@ -1,287 +1,344 @@
1
- """Tool calling and multimodal message parsing."""
2
- import json
3
- import re
4
- import uuid
5
- import base64
6
- import io
7
-
8
- MAX_IMAGE_B64_SIZE = 50000 # ~37KB raw image
9
-
10
-
11
- def _compress_b64_if_needed(b64: str) -> str:
12
- """Compress image if base64 is too large for text embedding."""
13
- if len(b64) <= MAX_IMAGE_B64_SIZE:
14
- return b64
15
- try:
16
- from PIL import Image
17
- img_data = base64.b64decode(b64)
18
- img = Image.open(io.BytesIO(img_data))
19
- # Resize to max 256px on longest side
20
- max_dim = 256
21
- ratio = min(max_dim / img.width, max_dim / img.height)
22
- if ratio < 1:
23
- img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
24
- # Convert to JPEG with quality reduction
25
- buf = io.BytesIO()
26
- img.convert("RGB").save(buf, format="JPEG", quality=60)
27
- compressed = base64.b64encode(buf.getvalue()).decode()
28
- return compressed
29
- except Exception:
30
- # If PIL not available, truncate (model will get partial data)
31
- return b64[:MAX_IMAGE_B64_SIZE]
32
-
33
-
34
- def _build_tool_choice_instruction(tool_choice, tool_defs: list) -> str:
35
- """Build tool_choice constraint instruction.
36
-
37
- tool_choice values:
38
- - "none": do not call any tool
39
- - "auto": decide whether to call tools (default)
40
- - "required": must call at least one tool
41
- - {"type": "function", "function": {"name": "xxx"}}: must call specific tool
42
- """
43
- if tool_choice == "none":
44
- return "\n\nIMPORTANT: Do NOT call any tools. Respond with text only."
45
- if tool_choice == "required":
46
- return "\n\nIMPORTANT: You MUST call at least one tool. Do not respond with text only."
47
- if isinstance(tool_choice, dict):
48
- fn_name = tool_choice.get("function", {}).get("name", "")
49
- if fn_name:
50
- return f'\n\nIMPORTANT: You MUST call the tool "{fn_name}". Do not call other tools.'
51
- return ""
52
-
53
-
54
- def messages_to_prompt(messages: list, tools: list = None, tool_choice=None) -> tuple:
55
- """Convert OpenAI messages to (prompt_str, images_list).
56
-
57
- Returns (prompt, images) where images is a list of (bytes, mime_type) tuples.
58
- """
59
- parts = []
60
- images = []
61
-
62
- if tools and tool_choice != "none":
63
- tool_defs = []
64
- for tool in tools:
65
- fn = tool.get("function", tool) if tool.get("type") == "function" else tool
66
- tool_defs.append({
67
- "name": fn.get("name", tool.get("name", "")),
68
- "description": fn.get("description", tool.get("description", "")),
69
- "parameters": fn.get("parameters", tool.get("parameters", {})),
70
- })
71
- if tool_defs:
72
- constraint = _build_tool_choice_instruction(tool_choice, tool_defs)
73
- parts.append(
74
- "# Tool Use\n\n"
75
- "You can call the following tools. Call format:\n"
76
- '```tool_call\n{"name": "func_name", "arguments": {...}}\n```\n'
77
- "When calling tools, output ONLY the tool_call block(s).\n\n"
78
- f"Available tools:\n{json.dumps(tool_defs, indent=2)}"
79
- f"{constraint}"
80
- )
81
-
82
- for msg in messages:
83
- role = msg.get("role", "user")
84
- content = msg.get("content", "")
85
-
86
- if isinstance(content, list):
87
- text_parts = []
88
- for c in content:
89
- if c.get("type") in ("text", "input_text"):
90
- text_parts.append(c.get("text", ""))
91
- elif c.get("type") == "image_url":
92
- text_parts.append("[Note: Image input not supported in this API. Please describe the image in text.]")
93
- elif c.get("type") == "image":
94
- text_parts.append("[Note: Image input not supported in this API. Please describe the image in text.]")
95
- content = " ".join(text_parts)
96
-
97
- if role == "system":
98
- parts.append(f"[System instruction]: {content}")
99
- elif role == "assistant":
100
- if msg.get("tool_calls"):
101
- tc_strs = []
102
- for tc in msg["tool_calls"]:
103
- fn = tc.get("function", {})
104
- tc_strs.append(
105
- f'```tool_call\n{{"name": "{fn.get("name")}", '
106
- f'"arguments": {fn.get("arguments", "{}")}}}\n```'
107
- )
108
- parts.append(f"[Assistant]: {content or ''}\n" + "\n".join(tc_strs))
109
- else:
110
- parts.append(f"[Assistant]: {content}")
111
- elif role == "tool":
112
- parts.append(f"[Tool result for {msg.get('name', '')}]: {content}")
113
- else:
114
- parts.append(content if content else "")
115
-
116
- prompt = "\n\n".join(p for p in parts if p)
117
- return prompt, images
118
-
119
-
120
- def parse_tool_calls(text: str) -> tuple:
121
- """Extract tool_call blocks. Returns (clean_text, tool_calls_list)."""
122
- tool_calls = []
123
- pattern = r'```tool_call\s*\n(.*?)\n```'
124
- clean_parts = []
125
- last_end = 0
126
- for m in re.finditer(pattern, text, re.DOTALL):
127
- clean_parts.append(text[last_end:m.start()])
128
- last_end = m.end()
129
- try:
130
- data = json.loads(m.group(1).strip())
131
- tool_calls.append({
132
- "id": f"call_{uuid.uuid4().hex[:8]}",
133
- "type": "function",
134
- "function": {
135
- "name": data["name"],
136
- "arguments": json.dumps(data.get("arguments", {}), ensure_ascii=False),
137
- },
138
- })
139
- except (json.JSONDecodeError, KeyError):
140
- pass
141
- clean_parts.append(text[last_end:])
142
- clean = "".join(clean_parts).strip()
143
- return clean, tool_calls
144
-
145
-
146
- # ─── Google Native API helpers ─────────────────────────────────────────────────
147
-
148
-
149
- def build_tool_prompt(tool_defs: list) -> str:
150
- """Build natural tool-use prompt for Gemini Web that avoids prompt-injection detection."""
151
- tool_spec = json.dumps(tool_defs, indent=2, ensure_ascii=False)
152
- return (
153
- "# Tool Use\n\n"
154
- "You can call the following tools to help accomplish tasks. "
155
- "These tools connect to the user's local environment and will execute when called.\n\n"
156
- "Call format (use this exact format):\n"
157
- "```function_call\n"
158
- '{"name": "<tool_name>", "args": {<arguments>}}\n'
159
- "```\n\n"
160
- "When calling tools:\n"
161
- "- Output ONLY the function_call block(s), nothing else\n"
162
- "- You may call multiple tools with multiple blocks\n"
163
- "- After receiving a [Tool result for ...], use that data to answer the user\n\n"
164
- f"Available tools:\n{tool_spec}"
165
- )
166
-
167
-
168
- def _google_tool_choice_instruction(req: dict) -> str:
169
- """Extract tool_choice constraint from Google API toolConfig."""
170
- tool_config = req.get("toolConfig", {})
171
- fc_config = tool_config.get("functionCallingConfig", {})
172
- mode = fc_config.get("mode", "AUTO")
173
- allowed = fc_config.get("allowedFunctionNames", [])
174
-
175
- if mode == "NONE":
176
- return "\n\nIMPORTANT: Do NOT call any tools. Respond with text only."
177
- if mode == "ANY":
178
- if allowed:
179
- names = ", ".join(f'"{n}"' for n in allowed)
180
- return f"\n\nIMPORTANT: You MUST call one of these tools: {names}. Do not respond with text only."
181
- return "\n\nIMPORTANT: You MUST call at least one tool. Do not respond with text only."
182
- return ""
183
-
184
-
185
- def google_contents_to_prompt(req: dict) -> tuple:
186
- """Convert Google API contents/tools/systemInstruction to (prompt_str, images_list).
187
-
188
- Returns (prompt, images) where images is a list of (bytes, mime_type) tuples.
189
- """
190
- parts = []
191
- images = []
192
-
193
- tool_config = req.get("toolConfig", {})
194
- fc_mode = tool_config.get("functionCallingConfig", {}).get("mode", "AUTO")
195
-
196
- tools = req.get("tools")
197
- tool_defs = []
198
- if tools and fc_mode != "NONE":
199
- for tool_group in tools:
200
- for fn in tool_group.get("functionDeclarations", []):
201
- td = {"name": fn.get("name", ""), "description": fn.get("description", "")}
202
- params = fn.get("parameters") or fn.get("parametersJsonSchema")
203
- if params:
204
- td["parameters"] = params
205
- tool_defs.append(td)
206
-
207
- sys_inst = req.get("systemInstruction")
208
- if sys_inst:
209
- sys_parts = sys_inst.get("parts", [])
210
- sys_text = " ".join(p.get("text", "") for p in sys_parts if p.get("text"))
211
- if sys_text:
212
- if tool_defs:
213
- constraint = _google_tool_choice_instruction(req)
214
- parts.append(sys_text + "\n\n" + build_tool_prompt(tool_defs) + constraint)
215
- else:
216
- parts.append(sys_text)
217
- elif tool_defs:
218
- constraint = _google_tool_choice_instruction(req)
219
- parts.append(build_tool_prompt(tool_defs) + constraint)
220
-
221
- for content in req.get("contents", []):
222
- role = content.get("role", "user")
223
- msg_parts = []
224
- for p in content.get("parts", []):
225
- if p.get("text"):
226
- msg_parts.append(p["text"])
227
- elif p.get("inlineData"):
228
- data = p["inlineData"]
229
- mime = data.get("mimeType", "image/png")
230
- images.append((base64.b64decode(data["data"]), mime))
231
- elif p.get("functionCall"):
232
- fc = p["functionCall"]
233
- msg_parts.append(
234
- f'```function_call\n{json.dumps({"name": fc["name"], "args": fc.get("args", {})}, ensure_ascii=False)}\n```'
235
- )
236
- elif p.get("functionResponse"):
237
- fr = p["functionResponse"]
238
- msg_parts.append(
239
- f'[Tool result for {fr.get("name", "")}]: {json.dumps(fr.get("response", {}), ensure_ascii=False)}'
240
- )
241
- text = "\n".join(msg_parts)
242
- if role == "model":
243
- parts.append(f"[Assistant]: {text}")
244
- else:
245
- parts.append(text)
246
-
247
- return "\n\n".join(p for p in parts if p), images
248
-
249
-
250
- def parse_google_function_calls(text: str) -> tuple:
251
- """Extract function_call blocks from model output.
252
-
253
- Handles 3 formats:
254
- 1. ```function_call\\n{...}\\n``` (standard)
255
- 2. function_call\\n{...} (without backticks)
256
- 3. Raw JSON with "name" + "args" keys
257
-
258
- Returns (clean_text, [{"name": ..., "args": ...}])
259
- """
260
- function_calls = []
261
- pattern1 = r'```function_call\s*\n(.*?)\n```'
262
- pattern2 = r'(?:^|\n)function_call\s*\n(\{[^`]*?\})'
263
- clean = text
264
- for pattern in [pattern1, pattern2]:
265
- for match in re.findall(pattern, clean, re.DOTALL):
266
- try:
267
- data = json.loads(match.strip())
268
- if "name" in data:
269
- function_calls.append({
270
- "name": data["name"],
271
- "args": data.get("args", data.get("arguments", {})),
272
- })
273
- except (json.JSONDecodeError, KeyError):
274
- pass
275
- clean = re.sub(pattern, '', clean, flags=re.DOTALL).strip()
276
- if not function_calls and clean.strip().startswith("{"):
277
- try:
278
- data = json.loads(clean.strip())
279
- if "name" in data and ("args" in data or "arguments" in data):
280
- function_calls.append({
281
- "name": data["name"],
282
- "args": data.get("args", data.get("arguments", {})),
283
- })
284
- clean = ""
285
- except (json.JSONDecodeError, KeyError):
286
- pass
287
- return clean, function_calls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tool calling and multimodal message parsing."""
2
+ import json
3
+ import re
4
+ import uuid
5
+ import base64
6
+ import binascii
7
+ import io
8
+ from urllib.parse import unquote_to_bytes
9
+
10
+ MAX_IMAGE_B64_SIZE = 50000 # ~37KB raw image
11
+
12
+
13
+ def _compress_b64_if_needed(b64: str) -> str:
14
+ """Compress image if base64 is too large for text embedding."""
15
+ if len(b64) <= MAX_IMAGE_B64_SIZE:
16
+ return b64
17
+ try:
18
+ from PIL import Image
19
+ img_data = base64.b64decode(b64)
20
+ img = Image.open(io.BytesIO(img_data))
21
+ # Resize to max 256px on longest side
22
+ max_dim = 256
23
+ ratio = min(max_dim / img.width, max_dim / img.height)
24
+ if ratio < 1:
25
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
26
+ # Convert to JPEG with quality reduction
27
+ buf = io.BytesIO()
28
+ img.convert("RGB").save(buf, format="JPEG", quality=60)
29
+ compressed = base64.b64encode(buf.getvalue()).decode()
30
+ return compressed
31
+ except Exception:
32
+ # If PIL not available, truncate (model will get partial data)
33
+ return b64[:MAX_IMAGE_B64_SIZE]
34
+
35
+
36
+ def _build_tool_choice_instruction(tool_choice, tool_defs: list) -> str:
37
+ """Build tool_choice constraint instruction.
38
+
39
+ tool_choice values:
40
+ - "none": do not call any tool
41
+ - "auto": decide whether to call tools (default)
42
+ - "required": must call at least one tool
43
+ - {"type": "function", "function": {"name": "xxx"}}: must call specific tool
44
+ """
45
+ if tool_choice == "none":
46
+ return "\n\nIMPORTANT: Do NOT call any tools. Respond with text only."
47
+ if tool_choice == "required":
48
+ return "\n\nIMPORTANT: You MUST call at least one tool. Do not respond with text only."
49
+ if isinstance(tool_choice, dict):
50
+ fn_name = tool_choice.get("function", {}).get("name", "")
51
+ if fn_name:
52
+ return f'\n\nIMPORTANT: You MUST call the tool "{fn_name}". Do not call other tools.'
53
+ return ""
54
+
55
+
56
+ def _decode_data_url(url: str):
57
+ match = re.match(r"^data:([^;,]+)?(;base64)?,(.*)$", url, re.DOTALL)
58
+ if not match:
59
+ return None
60
+ mime = match.group(1) or "image/png"
61
+ is_base64 = bool(match.group(2))
62
+ data = match.group(3)
63
+ try:
64
+ if is_base64:
65
+ return base64.b64decode(data, validate=True), mime
66
+ return unquote_to_bytes(data), mime
67
+ except (ValueError, TypeError, binascii.Error):
68
+ return None
69
+
70
+
71
+ def _image_from_url(url: str, mime: str = None):
72
+ if not isinstance(url, str) or not url:
73
+ return None
74
+ if url.startswith("data:"):
75
+ return _decode_data_url(url)
76
+ return url, mime or "image/png"
77
+
78
+
79
+ def _image_from_part(part: dict):
80
+ part_type = part.get("type")
81
+ if part_type == "image_url":
82
+ image_url = part.get("image_url", {})
83
+ if isinstance(image_url, dict):
84
+ return _image_from_url(image_url.get("url"), image_url.get("mime_type"))
85
+ return _image_from_url(image_url)
86
+ if part_type in ("input_image", "image"):
87
+ image_url = part.get("image_url") or part.get("url")
88
+ if isinstance(image_url, dict):
89
+ return _image_from_url(image_url.get("url"), image_url.get("mime_type"))
90
+ if image_url:
91
+ return _image_from_url(image_url, part.get("mime_type"))
92
+ image_data = part.get("data") or part.get("base64")
93
+ if isinstance(image_data, str):
94
+ mime = part.get("mime_type") or part.get("media_type") or "image/png"
95
+ if image_data.startswith("data:"):
96
+ return _decode_data_url(image_data)
97
+ try:
98
+ return base64.b64decode(image_data, validate=True), mime
99
+ except (ValueError, TypeError, binascii.Error):
100
+ return None
101
+ return None
102
+
103
+
104
+ def messages_to_prompt(messages: list, tools: list = None, tool_choice=None) -> tuple:
105
+ """Convert OpenAI messages to (prompt_str, images_list).
106
+
107
+ Returns (prompt, images) where images is a list of (bytes, mime_type) tuples.
108
+ """
109
+ parts = []
110
+ images = []
111
+
112
+ if tools and tool_choice != "none":
113
+ tool_defs = []
114
+ for tool in tools:
115
+ fn = tool.get("function", tool) if tool.get("type") == "function" else tool
116
+ tool_defs.append({
117
+ "name": fn.get("name", tool.get("name", "")),
118
+ "description": fn.get("description", tool.get("description", "")),
119
+ "parameters": fn.get("parameters", tool.get("parameters", {})),
120
+ })
121
+ if tool_defs:
122
+ constraint = _build_tool_choice_instruction(tool_choice, tool_defs)
123
+ parts.append(
124
+ "# Tool Use\n\n"
125
+ "You can call the following tools. Call format:\n"
126
+ '```tool_call\n{"name": "func_name", "arguments": {...}}\n```\n'
127
+ "When calling tools, output ONLY the tool_call block(s).\n\n"
128
+ f"Available tools:\n{json.dumps(tool_defs, indent=2)}"
129
+ f"{constraint}"
130
+ )
131
+
132
+ for msg in messages:
133
+ role = msg.get("role", "user")
134
+ content = msg.get("content", "")
135
+
136
+ if isinstance(content, list):
137
+ text_parts = []
138
+ for c in content:
139
+ if c.get("type") in ("text", "input_text"):
140
+ text_parts.append(c.get("text", ""))
141
+ else:
142
+ image = _image_from_part(c)
143
+ if image:
144
+ images.append(image)
145
+ text_parts.append("[Image attached]")
146
+ content = " ".join(text_parts)
147
+
148
+ if role == "system":
149
+ parts.append(f"[System instruction]: {content}")
150
+ elif role == "assistant":
151
+ if msg.get("tool_calls"):
152
+ tc_strs = []
153
+ for tc in msg["tool_calls"]:
154
+ fn = tc.get("function", {})
155
+ tc_strs.append(
156
+ f'```tool_call\n{{"name": "{fn.get("name")}", '
157
+ f'"arguments": {fn.get("arguments", "{}")}}}\n```'
158
+ )
159
+ parts.append(f"[Assistant]: {content or ''}\n" + "\n".join(tc_strs))
160
+ else:
161
+ parts.append(f"[Assistant]: {content}")
162
+ elif role == "tool":
163
+ parts.append(f"[Tool result for {msg.get('name', '')}]: {content}")
164
+ else:
165
+ parts.append(content if content else "")
166
+
167
+ prompt = "\n\n".join(p for p in parts if p)
168
+ return prompt, images
169
+
170
+
171
+ def parse_tool_calls(text: str) -> tuple:
172
+ """Extract tool_call blocks. Returns (clean_text, tool_calls_list)."""
173
+ tool_calls = []
174
+ pattern = r'```tool_call\s*\n(.*?)\n```'
175
+ clean_parts = []
176
+ last_end = 0
177
+ for m in re.finditer(pattern, text, re.DOTALL):
178
+ clean_parts.append(text[last_end:m.start()])
179
+ last_end = m.end()
180
+ try:
181
+ data = json.loads(m.group(1).strip())
182
+ tool_calls.append({
183
+ "id": f"call_{uuid.uuid4().hex[:8]}",
184
+ "type": "function",
185
+ "function": {
186
+ "name": data["name"],
187
+ "arguments": json.dumps(data.get("arguments", {}), ensure_ascii=False),
188
+ },
189
+ })
190
+ except (json.JSONDecodeError, KeyError):
191
+ pass
192
+ clean_parts.append(text[last_end:])
193
+ clean = "".join(clean_parts).strip()
194
+ return clean, tool_calls
195
+
196
+
197
+ # ─── Google Native API helpers ─────────────────────────────────────────────────
198
+
199
+
200
+ def build_tool_prompt(tool_defs: list) -> str:
201
+ """Build natural tool-use prompt for Gemini Web that avoids prompt-injection detection."""
202
+ tool_spec = json.dumps(tool_defs, indent=2, ensure_ascii=False)
203
+ return (
204
+ "# Tool Use\n\n"
205
+ "You can call the following tools to help accomplish tasks. "
206
+ "These tools connect to the user's local environment and will execute when called.\n\n"
207
+ "Call format (use this exact format):\n"
208
+ "```function_call\n"
209
+ '{"name": "<tool_name>", "args": {<arguments>}}\n'
210
+ "```\n\n"
211
+ "When calling tools:\n"
212
+ "- Output ONLY the function_call block(s), nothing else\n"
213
+ "- You may call multiple tools with multiple blocks\n"
214
+ "- After receiving a [Tool result for ...], use that data to answer the user\n\n"
215
+ f"Available tools:\n{tool_spec}"
216
+ )
217
+
218
+
219
+ def _google_tool_choice_instruction(req: dict) -> str:
220
+ """Extract tool_choice constraint from Google API toolConfig."""
221
+ tool_config = req.get("toolConfig", {})
222
+ fc_config = tool_config.get("functionCallingConfig", {})
223
+ mode = fc_config.get("mode", "AUTO")
224
+ allowed = fc_config.get("allowedFunctionNames", [])
225
+
226
+ if mode == "NONE":
227
+ return "\n\nIMPORTANT: Do NOT call any tools. Respond with text only."
228
+ if mode == "ANY":
229
+ if allowed:
230
+ names = ", ".join(f'"{n}"' for n in allowed)
231
+ return f"\n\nIMPORTANT: You MUST call one of these tools: {names}. Do not respond with text only."
232
+ return "\n\nIMPORTANT: You MUST call at least one tool. Do not respond with text only."
233
+ return ""
234
+
235
+
236
+ def google_contents_to_prompt(req: dict) -> tuple:
237
+ """Convert Google API contents/tools/systemInstruction to (prompt_str, images_list).
238
+
239
+ Returns (prompt, images) where images is a list of (bytes, mime_type) tuples.
240
+ """
241
+ parts = []
242
+ images = []
243
+
244
+ tool_config = req.get("toolConfig", {})
245
+ fc_mode = tool_config.get("functionCallingConfig", {}).get("mode", "AUTO")
246
+
247
+ tools = req.get("tools")
248
+ tool_defs = []
249
+ if tools and fc_mode != "NONE":
250
+ for tool_group in tools:
251
+ for fn in tool_group.get("functionDeclarations", []):
252
+ td = {"name": fn.get("name", ""), "description": fn.get("description", "")}
253
+ params = fn.get("parameters") or fn.get("parametersJsonSchema")
254
+ if params:
255
+ td["parameters"] = params
256
+ tool_defs.append(td)
257
+
258
+ sys_inst = req.get("systemInstruction")
259
+ if sys_inst:
260
+ sys_parts = sys_inst.get("parts", [])
261
+ sys_text = " ".join(p.get("text", "") for p in sys_parts if p.get("text"))
262
+ if sys_text:
263
+ if tool_defs:
264
+ constraint = _google_tool_choice_instruction(req)
265
+ parts.append(sys_text + "\n\n" + build_tool_prompt(tool_defs) + constraint)
266
+ else:
267
+ parts.append(sys_text)
268
+ elif tool_defs:
269
+ constraint = _google_tool_choice_instruction(req)
270
+ parts.append(build_tool_prompt(tool_defs) + constraint)
271
+
272
+ for content in req.get("contents", []):
273
+ role = content.get("role", "user")
274
+ msg_parts = []
275
+ for p in content.get("parts", []):
276
+ if p.get("text"):
277
+ msg_parts.append(p["text"])
278
+ elif p.get("inlineData"):
279
+ data = p["inlineData"]
280
+ try:
281
+ images.append((
282
+ base64.b64decode(data["data"], validate=True),
283
+ data.get("mimeType", "image/png"),
284
+ ))
285
+ msg_parts.append("[Image attached]")
286
+ except (KeyError, ValueError, TypeError, binascii.Error):
287
+ pass
288
+ elif p.get("functionCall"):
289
+ fc = p["functionCall"]
290
+ msg_parts.append(
291
+ f'```function_call\n{json.dumps({"name": fc["name"], "args": fc.get("args", {})}, ensure_ascii=False)}\n```'
292
+ )
293
+ elif p.get("functionResponse"):
294
+ fr = p["functionResponse"]
295
+ msg_parts.append(
296
+ f'[Tool result for {fr.get("name", "")}]: {json.dumps(fr.get("response", {}), ensure_ascii=False)}'
297
+ )
298
+ text = "\n".join(msg_parts)
299
+ if role == "model":
300
+ parts.append(f"[Assistant]: {text}")
301
+ else:
302
+ parts.append(text)
303
+
304
+ return "\n\n".join(p for p in parts if p), images
305
+
306
+
307
+ def parse_google_function_calls(text: str) -> tuple:
308
+ """Extract function_call blocks from model output.
309
+
310
+ Handles 3 formats:
311
+ 1. ```function_call\\n{...}\\n``` (standard)
312
+ 2. function_call\\n{...} (without backticks)
313
+ 3. Raw JSON with "name" + "args" keys
314
+
315
+ Returns (clean_text, [{"name": ..., "args": ...}])
316
+ """
317
+ function_calls = []
318
+ pattern1 = r'```function_call\s*\n(.*?)\n```'
319
+ pattern2 = r'(?:^|\n)function_call\s*\n(\{[^`]*?\})'
320
+ clean = text
321
+ for pattern in [pattern1, pattern2]:
322
+ for match in re.findall(pattern, clean, re.DOTALL):
323
+ try:
324
+ data = json.loads(match.strip())
325
+ if "name" in data:
326
+ function_calls.append({
327
+ "name": data["name"],
328
+ "args": data.get("args", data.get("arguments", {})),
329
+ })
330
+ except (json.JSONDecodeError, KeyError):
331
+ pass
332
+ clean = re.sub(pattern, '', clean, flags=re.DOTALL).strip()
333
+ if not function_calls and clean.strip().startswith("{"):
334
+ try:
335
+ data = json.loads(clean.strip())
336
+ if "name" in data and ("args" in data or "arguments" in data):
337
+ function_calls.append({
338
+ "name": data["name"],
339
+ "args": data.get("args", data.get("arguments", {})),
340
+ })
341
+ clean = ""
342
+ except (json.JSONDecodeError, KeyError):
343
+ pass
344
+ return clean, function_calls