xjackkx commited on
Commit
73aaeaa
·
verified ·
1 Parent(s): 95093c0

Upload 23 files

Browse files
.dockerignore CHANGED
@@ -1,9 +1,15 @@
1
- .git
2
- .idea
3
- .venv
4
- __pycache__
5
- *.pyc
6
- config.json
7
- cookie.txt
8
- cookie.json
9
- .env
 
 
 
 
 
 
 
1
+ .git
2
+ .idea
3
+ .venv
4
+ __pycache__
5
+ *.pyc
6
+ config.json
7
+ cookie.txt
8
+ cookie.json
9
+ .env
10
+ huggingface
11
+ .github
12
+ *.md
13
+ logo.png
14
+ LICENSE
15
+ docker-compose*.yml
.gitignore CHANGED
@@ -1,8 +1,8 @@
1
- __pycache__/
2
- *.pyc
3
- config.json
4
- cookie.txt
5
- cookie.json
6
- .env
7
- .idea
8
- .DS_Store
 
1
+ __pycache__/
2
+ *.pyc
3
+ config.json
4
+ cookie.txt
5
+ cookie.json
6
+ .env
7
+ .idea
8
+ .DS_Store
Dockerfile CHANGED
@@ -1,25 +1,26 @@
1
  FROM python:3.12-slim
2
 
3
- # 创建非 root 用户
4
  RUN groupadd -r appuser && useradd -r -g appuser -m appuser
5
 
6
  WORKDIR /app
7
 
8
- # 安装依赖
9
  COPY requirements.txt ./
10
  RUN pip install --no-cache-dir -r requirements.txt
11
 
12
- # 复制应用代码和启动脚本
13
  COPY gemini_web2api/ ./gemini_web2api/
14
  COPY entrypoint.sh /entrypoint.sh
15
- RUN chmod +x /entrypoint.sh
 
 
 
 
 
 
 
16
 
17
- # HF Spaces 强制要求 7860 端口
18
  EXPOSE 7860
19
 
20
- # 设置权限
21
- RUN chown -R appuser:appuser /app
22
  USER appuser
23
 
24
- # 使用 entrypoint 启动
25
  CMD ["/entrypoint.sh"]
 
1
  FROM python:3.12-slim
2
 
3
+ # Non-root user (Hugging Face Spaces requirement)
4
  RUN groupadd -r appuser && useradd -r -g appuser -m appuser
5
 
6
  WORKDIR /app
7
 
 
8
  COPY requirements.txt ./
9
  RUN pip install --no-cache-dir -r requirements.txt
10
 
 
11
  COPY gemini_web2api/ ./gemini_web2api/
12
  COPY entrypoint.sh /entrypoint.sh
13
+ RUN chmod +x /entrypoint.sh \
14
+ && chown -R appuser:appuser /app
15
+
16
+ # HF Spaces free tier requires listening on 7860.
17
+ # Local Docker: map host 8081 -> container 7860, or set PORT=8081.
18
+ ENV PORT=7860 \
19
+ HOST=0.0.0.0 \
20
+ PYTHONUNBUFFERED=1
21
 
 
22
  EXPOSE 7860
23
 
 
 
24
  USER appuser
25
 
 
26
  CMD ["/entrypoint.sh"]
entrypoint.sh CHANGED
@@ -1,37 +1,40 @@
1
  #!/bin/bash
2
  set -e
3
 
4
- echo "🚀 Starting gemini-web2api for Hugging Face Spaces..."
 
 
5
 
6
- # 1. 动态生成 config.json
7
- # 优先使用用户通过 Secret 传入的 Base64 编码配置
8
- if [ -n "$CONFIG_JSON_B64" ]; then
9
- echo "$CONFIG_JSON_B64" | base64 -d > /app/config.json
10
- echo "✅ config.json loaded from CONFIG_JSON_B64 secret."
 
 
 
11
  else
12
- # 否则生成默认配置,【强制 host 为 0.0.0.0】
13
- cat > /app/config.json <<EOF
14
  {
15
- "host": "0.0.0.0",
16
- "port": 7860,
17
- "cookie_file": "/app/cookies.txt",
18
- "proxy": null
 
19
  }
20
  EOF
21
- echo "✅ Default config.json generated (host: 0.0.0.0, port: 7860)."
22
  fi
23
 
24
- # 2. 处理 Gemini Cookie (通过 Spaces Secrets 注入)
25
- if [ -n "$GEMINI_COOKIE" ]; then
26
- echo "$GEMINI_COOKIE" > /app/cookies.txt
27
- echo "✅ Cookie file generated from GEMINI_COOKIE secret."
28
- else
29
- echo "⚠️ Warning: GEMINI_COOKIE secret not found. Running in anonymous mode (may be limited)."
30
- # 如果没 cookie,把 config 里的 cookie_file 置空防止报错
31
- sed -i 's|"cookie_file": "/app/cookies.txt"|"cookie_file": null|g' /app/config.json
32
  fi
33
 
34
- # 3. 启动应用
35
- # 强制通过命令行指定 --port 7860 (双重保险)
36
- echo "🌟 Launching server..."
37
- exec python -m gemini_web2api --config /app/config.json --port 7860
 
1
  #!/bin/bash
2
  set -e
3
 
4
+ PORT="${PORT:-7860}"
5
+ HOST="${HOST:-0.0.0.0}"
6
+ CONFIG_PATH="${GEMINI_WEB2API_CONFIG:-/app/config.json}"
7
 
8
+ echo "Starting gemini-web2api (host=${HOST}, port=${PORT})..."
9
+
10
+ # 1) config.json: CONFIG_JSON_B64 secret > existing mount > generate default
11
+ if [ -n "${CONFIG_JSON_B64:-}" ]; then
12
+ echo "${CONFIG_JSON_B64}" | base64 -d > "${CONFIG_PATH}"
13
+ echo "config.json loaded from CONFIG_JSON_B64."
14
+ elif [ -f "${CONFIG_PATH}" ]; then
15
+ echo "config.json found at ${CONFIG_PATH}."
16
  else
17
+ cat > "${CONFIG_PATH}" <<EOF
 
18
  {
19
+ "host": "${HOST}",
20
+ "port": ${PORT},
21
+ "cookie_file": null,
22
+ "proxy": null,
23
+ "api_keys": []
24
  }
25
  EOF
26
+ echo "Default config.json generated."
27
  fi
28
 
29
+ # 2) Cookie from Space/Docker secret (plain text cookie file content)
30
+ if [ -n "${GEMINI_COOKIE:-}" ]; then
31
+ COOKIE_PATH="${COOKIE_FILE:-/tmp/cookies.txt}"
32
+ printf '%s\n' "${GEMINI_COOKIE}" > "${COOKIE_PATH}"
33
+ export GEMINI_COOKIE_FILE="${COOKIE_PATH}"
34
+ echo "Cookie written to ${COOKIE_PATH}."
35
+ elif [ -z "${GEMINI_COOKIE_FILE:-}" ]; then
36
+ echo "Warning: no GEMINI_COOKIE / GEMINI_COOKIE_FILE; anonymous mode (limited)."
37
  fi
38
 
39
+ # 3) Launch (env overrides + CLI port as final lock for HF 7860)
40
+ exec python -m gemini_web2api --config "${CONFIG_PATH}" --port "${PORT}"
 
 
gemini_web2api.py ADDED
@@ -0,0 +1,859 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ gemini-web2api - Gemini Web to OpenAI API proxy.
4
+
5
+ Converts Google Gemini's web interface into an OpenAI-compatible API server.
6
+ Zero authentication required. Works on any platform (Windows/macOS/Linux).
7
+
8
+ Usage:
9
+ pip install httpx
10
+ python gemini_web2api.py [--port 8081] [--config config.json]
11
+
12
+ Client configuration (Cherry Studio, ChatBox, etc.):
13
+ Base URL: http://localhost:8081/v1
14
+ API Key: (anything or empty)
15
+
16
+ How it works:
17
+ Sends requests directly to Gemini's public StreamGenerate endpoint.
18
+ The backend does not verify authentication for basic text generation.
19
+ Model selection via MODE_CATEGORY field [79] in the request payload.
20
+ This is NOT a user-tier spoofing attack - the endpoint simply doesn't
21
+ require auth for anonymous access.
22
+ """
23
+ import json
24
+ import urllib.request
25
+ import urllib.parse
26
+ import time
27
+ import ssl
28
+ import sys
29
+ import uuid
30
+ import re
31
+ import os
32
+ import hashlib
33
+ import argparse
34
+ import base64
35
+ from http.server import HTTPServer, BaseHTTPRequestHandler
36
+ from socketserver import ThreadingMixIn
37
+
38
+ try:
39
+ import httpx
40
+ HAS_HTTPX = True
41
+ except ImportError:
42
+ HAS_HTTPX = False
43
+
44
+ __version__ = "1.1.0"
45
+
46
+ # ─── Configuration ───────────────────────────────────────────────────────────
47
+
48
+ DEFAULT_CONFIG = {
49
+ "port": 8081,
50
+ "host": "0.0.0.0",
51
+ "retry_attempts": 3,
52
+ "retry_delay_sec": 2,
53
+ "request_timeout_sec": 180,
54
+ "gemini_bl": "boq_assistant-bard-web-server_20260525.09_p0",
55
+ "auth_user": None,
56
+ "xsrf_token": None,
57
+ "default_model": "gemini-3.5-flash",
58
+ "log_requests": True,
59
+ "cookie_file": None,
60
+ "proxy": None,
61
+ "api_keys": [],
62
+ }
63
+
64
+ CONFIG = dict(DEFAULT_CONFIG)
65
+
66
+ # ─── Models ──────────────────────────────────────────────────────────────────
67
+ # Mapping from JS source: MODE_CATEGORY enum (028-6eb337387583.js)
68
+ # 1=FAST, 2=THINKING, 3=PRO, 4=AUTO, 5=FAST_DYNAMIC_THINKING, 6=FLASH_LITE
69
+
70
+ MODELS = {
71
+ "gemini-3.5-flash": {
72
+ "mode": 1, "think": 4,
73
+ "desc": "Fast general-purpose model",
74
+ },
75
+ "gemini-3.5-flash-thinking": {
76
+ "mode": 2, "think": 0,
77
+ "desc": "Deep thinking mode, longest output (~20k chars)",
78
+ },
79
+ "gemini-3.1-pro": {
80
+ "mode": 3, "think": 4,
81
+ "desc": "Pro model (requires cookie for real routing)",
82
+ },
83
+ "gemini-auto": {
84
+ "mode": 4, "think": 4,
85
+ "desc": "Auto model selection",
86
+ },
87
+ "gemini-3.5-flash-thinking-lite": {
88
+ "mode": 5, "think": 0,
89
+ "desc": "Dynamic thinking with adaptive depth",
90
+ },
91
+ "gemini-flash-lite": {
92
+ "mode": 6, "think": 4,
93
+ "desc": "Lightweight fast model",
94
+ },
95
+ }
96
+
97
+ # ─── Utilities ───────────────────────────────────────────────────────────────
98
+
99
+ def log(msg: str):
100
+ if CONFIG["log_requests"]:
101
+ sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
102
+ sys.stderr.flush()
103
+
104
+
105
+ def load_cookie() -> tuple:
106
+ """Load cookie from file. Returns (cookie_str, sapisid)."""
107
+ cookie_file = CONFIG.get("cookie_file")
108
+ if not cookie_file:
109
+ return "", None
110
+ if not os.path.exists(cookie_file):
111
+ return "", None
112
+ try:
113
+ with open(cookie_file, "r") as f:
114
+ content = f.read().strip()
115
+ if content.startswith("{"):
116
+ data = json.loads(content)
117
+ cookie_str = data.get("cookie", "")
118
+ sapisid = data.get("sapisid", "")
119
+ else:
120
+ cookie_str = content
121
+ pairs = dict(p.split("=", 1) for p in cookie_str.split("; ") if "=" in p)
122
+ sapisid = pairs.get("SAPISID", "")
123
+ return cookie_str, sapisid if sapisid else None
124
+ except Exception as e:
125
+ log(f"Cookie load error: {e}")
126
+ return "", None
127
+
128
+
129
+ def make_sapisidhash(sapisid: str) -> str:
130
+ ts = int(time.time())
131
+ h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
132
+ return f"SAPISIDHASH {ts}_{h}"
133
+
134
+
135
+ def account_prefix() -> str:
136
+ """Return the Gemini account path prefix for non-default Google accounts."""
137
+ auth_user = CONFIG.get("auth_user")
138
+ if auth_user is None or auth_user == "":
139
+ return ""
140
+ return f"/u/{auth_user}"
141
+
142
+
143
+ # ─── Gemini Protocol ─────────────────────────────────────────────────────────
144
+
145
+ def gemini_stream_generate(prompt: str, model_id: int, think_mode: int) -> str:
146
+ """Send prompt to Gemini StreamGenerate with retry."""
147
+ inner = [None] * 80
148
+ inner[0] = [prompt, 0, None, None, None, None, 0]
149
+ inner[1] = ["en"]
150
+ inner[2] = ["", "", "", None, None, None, None, None, None, ""]
151
+ inner[6] = [0]
152
+ inner[7] = 1
153
+ inner[10] = 1
154
+ inner[11] = 0
155
+ inner[17] = [[think_mode]]
156
+ inner[18] = 0
157
+ inner[27] = 1
158
+ inner[30] = [4]
159
+ inner[41] = [2]
160
+ inner[53] = 0
161
+ inner[59] = str(uuid.uuid4())
162
+ inner[61] = []
163
+ inner[68] = 1
164
+ inner[79] = model_id
165
+
166
+ outer = [None, json.dumps(inner)]
167
+ params = {"f.req": json.dumps(outer)}
168
+ if CONFIG.get("xsrf_token"):
169
+ params["at"] = CONFIG["xsrf_token"]
170
+ body = urllib.parse.urlencode(params).encode()
171
+ reqid = int(time.time()) % 1000000
172
+ prefix = account_prefix()
173
+ url = (
174
+ f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
175
+ "assistant.lamda.BardFrontendService/StreamGenerate"
176
+ f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
177
+ )
178
+ headers = {
179
+ "Content-Type": "application/x-www-form-urlencoded",
180
+ "Origin": "https://gemini.google.com",
181
+ "Referer": f"https://gemini.google.com{prefix}/app",
182
+ "X-Same-Domain": "1",
183
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
184
+ }
185
+ if prefix:
186
+ headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
187
+
188
+ cookie_str, sapisid = load_cookie()
189
+ if cookie_str:
190
+ headers["Cookie"] = cookie_str
191
+ if sapisid:
192
+ headers["Authorization"] = make_sapisidhash(sapisid)
193
+
194
+ last_err = None
195
+ for attempt in range(CONFIG["retry_attempts"]):
196
+ try:
197
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
198
+ ctx = ssl.create_default_context()
199
+ proxy = CONFIG.get("proxy")
200
+ if proxy:
201
+ opener = urllib.request.build_opener(
202
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
203
+ urllib.request.HTTPSHandler(context=ctx)
204
+ )
205
+ resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
206
+ else:
207
+ resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
208
+ return resp.read().decode("utf-8", errors="replace")
209
+ except Exception as e:
210
+ last_err = e
211
+ if attempt < CONFIG["retry_attempts"] - 1:
212
+ log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
213
+ time.sleep(CONFIG["retry_delay_sec"])
214
+ raise last_err
215
+
216
+
217
+ def gemini_stream_generate_iter(prompt: str, model_id: int, think_mode: int):
218
+ """Send prompt and yield incremental text deltas using httpx streaming."""
219
+ inner = [None] * 80
220
+ inner[0] = [prompt, 0, None, None, None, None, 0]
221
+ inner[1] = ["en"]
222
+ inner[2] = ["", "", "", None, None, None, None, None, None, ""]
223
+ inner[6] = [0]
224
+ inner[7] = 1
225
+ inner[10] = 1
226
+ inner[11] = 0
227
+ inner[17] = [[think_mode]]
228
+ inner[18] = 0
229
+ inner[27] = 1
230
+ inner[30] = [4]
231
+ inner[41] = [2]
232
+ inner[53] = 0
233
+ inner[59] = str(uuid.uuid4())
234
+ inner[61] = []
235
+ inner[68] = 1
236
+ inner[79] = model_id
237
+
238
+ outer = [None, json.dumps(inner)]
239
+ params = {"f.req": json.dumps(outer)}
240
+ if CONFIG.get("xsrf_token"):
241
+ params["at"] = CONFIG["xsrf_token"]
242
+ body = urllib.parse.urlencode(params)
243
+ reqid = int(time.time()) % 1000000
244
+ prefix = account_prefix()
245
+ url = (
246
+ f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
247
+ "assistant.lamda.BardFrontendService/StreamGenerate"
248
+ f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
249
+ )
250
+ headers = {
251
+ "Content-Type": "application/x-www-form-urlencoded",
252
+ "Origin": "https://gemini.google.com",
253
+ "Referer": f"https://gemini.google.com{prefix}/app",
254
+ "X-Same-Domain": "1",
255
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
256
+ }
257
+ if prefix:
258
+ headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
259
+ cookie_str, sapisid = load_cookie()
260
+ if cookie_str:
261
+ headers["Cookie"] = cookie_str
262
+ if sapisid:
263
+ headers["Authorization"] = make_sapisidhash(sapisid)
264
+
265
+ proxy = CONFIG.get("proxy")
266
+
267
+ if not HAS_HTTPX:
268
+ # Fallback: non-streaming with urllib
269
+ raw = gemini_stream_generate(prompt, model_id, think_mode)
270
+ text = extract_response_text(raw)
271
+ if text:
272
+ yield text
273
+ return
274
+
275
+ prev_text = ""
276
+ transport = httpx.HTTPTransport(proxy=proxy) if proxy else None
277
+ with httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True) as client:
278
+ with client.stream("POST", url, content=body, headers=headers) as resp:
279
+ buf = ""
280
+ for chunk in resp.iter_text():
281
+ buf += chunk
282
+ if "BardErrorInfo" in buf:
283
+ import re as _re
284
+ m = _re.search(r'BardErrorInfo\s*\[(\d+)\]', buf)
285
+ if m:
286
+ raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{m.group(1)}]")
287
+ while "\n" in buf:
288
+ line, buf = buf.split("\n", 1)
289
+ if '"wrb.fr"' not in line or len(line) < 200:
290
+ continue
291
+ try:
292
+ arr = json.loads(line)
293
+ inner_str = arr[0][2]
294
+ if not inner_str or len(inner_str) < 50:
295
+ continue
296
+ inner2 = json.loads(inner_str)
297
+ if isinstance(inner2, list) and len(inner2) > 4 and inner2[4]:
298
+ for part in inner2[4]:
299
+ if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
300
+ for t in part[1]:
301
+ if isinstance(t, str) and len(t) > len(prev_text):
302
+ delta = t[len(prev_text):]
303
+ delta = clean_gemini_text(delta)
304
+ if delta:
305
+ yield delta
306
+ prev_text = t
307
+ except (json.JSONDecodeError, IndexError, TypeError):
308
+ pass
309
+
310
+
311
+ def clean_gemini_text(text: str) -> str:
312
+ """Remove internal code execution artifacts."""
313
+ text = re.sub(
314
+ r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
315
+ '', text, flags=re.DOTALL
316
+ )
317
+ return text.strip()
318
+
319
+
320
+ def extract_response_text(raw: str) -> str:
321
+ """Parse StreamGenerate response to extract final text."""
322
+ import re as _re
323
+ bard_err = _re.search(r'BardErrorInfo\s*\[(\d+)\]', raw)
324
+ if bard_err:
325
+ raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{bard_err.group(1)}]")
326
+ texts = []
327
+ for line in raw.split("\n"):
328
+ if '"wrb.fr"' not in line or len(line) < 200:
329
+ continue
330
+ try:
331
+ arr = json.loads(line)
332
+ inner_str = arr[0][2]
333
+ if not inner_str or len(inner_str) < 50:
334
+ continue
335
+ inner = json.loads(inner_str)
336
+ if isinstance(inner, list) and len(inner) > 4 and inner[4]:
337
+ for part in inner[4]:
338
+ if isinstance(part, list) and len(part) > 1 and part[1]:
339
+ if isinstance(part[1], list):
340
+ for t in part[1]:
341
+ if isinstance(t, str) and len(t) > 0:
342
+ texts.append(t)
343
+ except (json.JSONDecodeError, IndexError, TypeError):
344
+ pass
345
+ text = ""
346
+ for t in reversed(texts):
347
+ if t.strip():
348
+ text = t
349
+ break
350
+ return clean_gemini_text(text)
351
+
352
+
353
+ # ─── OpenAI Format Helpers ───────────────────────────────────────────────────
354
+
355
+ def messages_to_prompt(messages: list, tools: list = None) -> str:
356
+ """Convert OpenAI messages to prompt string."""
357
+ parts = []
358
+ if tools:
359
+ tool_defs = []
360
+ for tool in tools:
361
+ fn = tool.get("function", tool) if tool.get("type") == "function" else tool
362
+ tool_defs.append({
363
+ "name": fn.get("name", tool.get("name", "")),
364
+ "description": fn.get("description", tool.get("description", "")),
365
+ "parameters": fn.get("parameters", tool.get("parameters", {})),
366
+ })
367
+ if tool_defs:
368
+ parts.append(
369
+ "[System instruction]: You have access to tools. "
370
+ "To call a tool, respond with:\n"
371
+ '```tool_call\n{"name": "func_name", "arguments": {...}}\n```\n'
372
+ "Only use tool_call blocks when needed.\n\n"
373
+ f"Available tools:\n{json.dumps(tool_defs, indent=2)}"
374
+ )
375
+ for msg in messages:
376
+ role = msg.get("role", "user")
377
+ content = msg.get("content", "")
378
+ if isinstance(content, list):
379
+ content = " ".join(
380
+ c.get("text", "") for c in content
381
+ if c.get("type") in ("text", "input_text")
382
+ )
383
+ if role == "system":
384
+ parts.append(f"[System instruction]: {content}")
385
+ elif role == "assistant":
386
+ if msg.get("tool_calls"):
387
+ tc_strs = []
388
+ for tc in msg["tool_calls"]:
389
+ fn = tc.get("function", {})
390
+ tc_strs.append(
391
+ f'```tool_call\n{{"name": "{fn.get("name")}", '
392
+ f'"arguments": {fn.get("arguments", "{}")}}}\n```'
393
+ )
394
+ parts.append(f"[Assistant]: {content or ''}\n" + "\n".join(tc_strs))
395
+ else:
396
+ parts.append(f"[Assistant]: {content}")
397
+ elif role == "tool":
398
+ parts.append(f"[Tool result for {msg.get('name', '')}]: {content}")
399
+ else:
400
+ parts.append(content if content else "")
401
+ return "\n\n".join(p for p in parts if p)
402
+
403
+
404
+ def parse_tool_calls(text: str) -> tuple:
405
+ """Extract tool_call blocks. Returns (clean_text, tool_calls_list)."""
406
+ tool_calls = []
407
+ pattern = r'```tool_call\s*\n(.*?)\n```'
408
+ for match in re.findall(pattern, text, re.DOTALL):
409
+ try:
410
+ data = json.loads(match.strip())
411
+ tool_calls.append({
412
+ "id": f"call_{uuid.uuid4().hex[:8]}",
413
+ "type": "function",
414
+ "function": {
415
+ "name": data["name"],
416
+ "arguments": json.dumps(data.get("arguments", {}), ensure_ascii=False),
417
+ },
418
+ })
419
+ except (json.JSONDecodeError, KeyError):
420
+ pass
421
+ clean = re.sub(pattern, '', text, flags=re.DOTALL).strip()
422
+ return clean, tool_calls
423
+
424
+
425
+ # ─── HTTP Handler ────────────────────────────────────────────────────────────
426
+
427
+ class GeminiHandler(BaseHTTPRequestHandler):
428
+ def log_message(self, fmt, *args):
429
+ log(fmt % args)
430
+
431
+ def send_json(self, data, status=200):
432
+ body = json.dumps(data, ensure_ascii=False).encode()
433
+ self.send_response(status)
434
+ self.send_header("Content-Type", "application/json")
435
+ self.send_header("Access-Control-Allow-Origin", "*")
436
+ self.send_header("Content-Length", str(len(body)))
437
+ self.end_headers()
438
+ self.wfile.write(body)
439
+
440
+ def _authorized(self):
441
+ keys = CONFIG.get("api_keys") or []
442
+ if not keys:
443
+ return True
444
+ # Authorization: Bearer <key>
445
+ auth = self.headers.get("Authorization", "")
446
+ if auth.startswith("Bearer ") and auth[7:] in keys:
447
+ return True
448
+ # header keys (OpenAI x-api-key / Google x-goog-api-key)
449
+ for h in ("x-api-key", "x-goog-api-key"):
450
+ if self.headers.get(h, "") in keys:
451
+ return True
452
+ # query param ?key= (Gemini CLI native style)
453
+ if "?" in self.path:
454
+ for pair in self.path.split("?", 1)[1].split("&"):
455
+ if pair.startswith("key=") and pair[4:] in keys:
456
+ return True
457
+ return False
458
+
459
+ def do_OPTIONS(self):
460
+ self.send_response(204)
461
+ self.send_header("Access-Control-Allow-Origin", "*")
462
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
463
+ self.send_header("Access-Control-Allow-Headers", "*")
464
+ self.end_headers()
465
+
466
+ def do_GET(self):
467
+ try:
468
+ if self.path.startswith("/v1") and not self._authorized():
469
+ self.send_json({"error": {"message": "invalid api key"}}, 401)
470
+ return
471
+ if self.path == "/v1/models":
472
+ self.send_json({"object": "list", "data": [
473
+ {"id": n, "object": "model", "created": 1700000000,
474
+ "owned_by": "google", "description": c["desc"]}
475
+ for n, c in MODELS.items()
476
+ ]})
477
+ elif self.path.startswith("/v1beta/models"):
478
+ self._handle_google_models_list()
479
+ elif self.path == "/":
480
+ self.send_json({"status": "ok", "version": __version__,
481
+ "models": list(MODELS.keys())})
482
+ else:
483
+ self.send_json({"error": "not found"}, 404)
484
+ except (BrokenPipeError, ConnectionResetError):
485
+ pass
486
+ except Exception as e:
487
+ log(f"GET error: {e}")
488
+
489
+ def do_POST(self):
490
+ try:
491
+ if self.path.startswith("/v1") and not self._authorized():
492
+ self.send_json({"error": {"message": "invalid api key"}}, 401)
493
+ return
494
+ length = int(self.headers.get("Content-Length", 0))
495
+ body = self.rfile.read(length) if length else b""
496
+ if self.path == "/v1/chat/completions":
497
+ self.handle_chat(body)
498
+ elif self.path == "/v1/responses":
499
+ self.handle_responses(body)
500
+ elif ":generateContent" in self.path:
501
+ self._handle_google_generate(body, stream=False)
502
+ elif ":streamGenerateContent" in self.path:
503
+ self._handle_google_generate(body, stream=True)
504
+ else:
505
+ self.send_json({"error": "not found"}, 404)
506
+ except (BrokenPipeError, ConnectionResetError):
507
+ pass
508
+ except Exception as e:
509
+ log(f"POST error: {e}")
510
+ try:
511
+ self.send_json({"error": {"message": str(e)}}, 500)
512
+ except:
513
+ pass
514
+
515
+ def _resolve_model(self, model_name):
516
+ think_override = None
517
+ if "@think=" in model_name:
518
+ model_name, think_str = model_name.rsplit("@think=", 1)
519
+ think_override = int(think_str)
520
+ cfg = MODELS.get(model_name)
521
+ if not cfg:
522
+ return None, None, None, f"Unknown model: {model_name}"
523
+ return model_name, cfg["mode"], (think_override if think_override is not None else cfg["think"]), None
524
+
525
+ def _call_gemini(self, prompt, model_id, think_mode, tools):
526
+ raw = gemini_stream_generate(prompt, model_id, think_mode)
527
+ text = extract_response_text(raw)
528
+ tool_calls = None
529
+ if tools and text:
530
+ text, tool_calls = parse_tool_calls(text)
531
+ return text or "", tool_calls
532
+
533
+ def handle_chat(self, body: bytes):
534
+ req = json.loads(body)
535
+ model_name, model_id, think_mode, err = self._resolve_model(
536
+ req.get("model", CONFIG["default_model"]))
537
+ if err:
538
+ self.send_json({"error": {"message": err}}, 400)
539
+ return
540
+
541
+ tools = req.get("tools")
542
+ prompt = messages_to_prompt(req.get("messages", []), tools)
543
+ if not prompt.strip():
544
+ self.send_json({"error": {"message": "empty prompt"}}, 400)
545
+ return
546
+
547
+ stream = req.get("stream", False)
548
+ cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
549
+
550
+ if stream and not tools:
551
+ # True streaming: forward chunks as they arrive
552
+ try:
553
+ self.send_response(200)
554
+ self.send_header("Content-Type", "text/event-stream")
555
+ self.send_header("Cache-Control", "no-cache")
556
+ self.send_header("Access-Control-Allow-Origin", "*")
557
+ self.end_headers()
558
+ for delta_text in gemini_stream_generate_iter(prompt, model_id, think_mode):
559
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
560
+ "model": model_name, "choices": [{"index": 0, "delta": {"content": delta_text}, "finish_reason": None}]}
561
+ self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
562
+ self.wfile.flush()
563
+ # Final chunk
564
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
565
+ "model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
566
+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
567
+ self.wfile.write(b"data: [DONE]\n\n")
568
+ self.wfile.flush()
569
+ except (BrokenPipeError, ConnectionResetError):
570
+ pass
571
+ except Exception as e:
572
+ log(f"Stream error: {e}")
573
+ return
574
+
575
+ # Non-streaming (or tool calling which needs full response)
576
+ try:
577
+ text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools)
578
+ except Exception as e:
579
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
580
+ return
581
+
582
+ msg = {"role": "assistant", "content": text or None}
583
+ if tool_calls:
584
+ msg["tool_calls"] = tool_calls
585
+ finish = "tool_calls" if tool_calls else "stop"
586
+
587
+ if stream:
588
+ # Stream mode with tools: send as single chunk (need full parse for tool_calls)
589
+ self.send_response(200)
590
+ self.send_header("Content-Type", "text/event-stream")
591
+ self.send_header("Cache-Control", "no-cache")
592
+ self.send_header("Access-Control-Allow-Origin", "*")
593
+ self.end_headers()
594
+ chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
595
+ "model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
596
+ self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
597
+ self.wfile.write(b"data: [DONE]\n\n")
598
+ self.wfile.flush()
599
+ else:
600
+ self.send_json({
601
+ "id": cid, "object": "chat.completion", "created": int(time.time()),
602
+ "model": model_name,
603
+ "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
604
+ "usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text)//4,
605
+ "total_tokens": (len(prompt)+len(text))//4},
606
+ })
607
+
608
+ def handle_responses(self, body: bytes):
609
+ """OpenAI Responses API for Codex CLI compatibility."""
610
+ req = json.loads(body)
611
+ model_name, model_id, think_mode, err = self._resolve_model(
612
+ req.get("model", CONFIG["default_model"]))
613
+ if err:
614
+ self.send_json({"error": {"message": err}}, 400)
615
+ return
616
+
617
+ input_items = req.get("input", [])
618
+ tools = req.get("tools")
619
+
620
+ messages = []
621
+ if req.get("instructions"):
622
+ messages.append({"role": "system", "content": req["instructions"]})
623
+ if isinstance(input_items, str):
624
+ messages.append({"role": "user", "content": input_items})
625
+ elif isinstance(input_items, list):
626
+ for item in input_items:
627
+ if isinstance(item, str):
628
+ messages.append({"role": "user", "content": item})
629
+ elif isinstance(item, dict):
630
+ if item.get("type") == "function_call_output":
631
+ messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
632
+ "name": item.get("name", ""), "content": item.get("output", "")})
633
+ elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
634
+ cp = item.get("content", [])
635
+ text_acc, tc_list = "", []
636
+ if isinstance(cp, list):
637
+ for c in cp:
638
+ if isinstance(c, dict):
639
+ if c.get("type") == "output_text": text_acc += c.get("text", "")
640
+ elif c.get("type") == "function_call": tc_list.append(c)
641
+ elif isinstance(cp, str):
642
+ text_acc = cp
643
+ m = {"role": "assistant", "content": text_acc or None}
644
+ if tc_list:
645
+ m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
646
+ "function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
647
+ for i, tc in enumerate(tc_list)]
648
+ messages.append(m)
649
+ else:
650
+ role = item.get("role", "user")
651
+ content = item.get("content", "")
652
+ if isinstance(content, list):
653
+ content = " ".join(c.get("text", "") for c in content if c.get("type") in ("text", "input_text"))
654
+ messages.append({"role": role, "content": content})
655
+
656
+ if tools:
657
+ tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
658
+ if t.get("type") == "function" and "function" not in t else t for t in tools]
659
+
660
+ prompt = messages_to_prompt(messages, tools)
661
+ if not prompt.strip():
662
+ self.send_json({"error": {"message": "empty input"}}, 400)
663
+ return
664
+
665
+ try:
666
+ text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools)
667
+ except Exception as e:
668
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
669
+ return
670
+
671
+ rid = f"resp_{uuid.uuid4().hex[:16]}"
672
+ mid = f"msg_{uuid.uuid4().hex[:12]}"
673
+ output = []
674
+ if tool_calls:
675
+ for tc in tool_calls:
676
+ output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
677
+ "name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
678
+ if text or not tool_calls:
679
+ output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
680
+ "content": [{"type": "output_text", "text": text or "", "annotations": []}]})
681
+
682
+ if req.get("stream"):
683
+ self.send_response(200)
684
+ self.send_header("Content-Type", "text/event-stream")
685
+ self.send_header("Cache-Control", "no-cache")
686
+ self.send_header("Access-Control-Allow-Origin", "*")
687
+ self.end_headers()
688
+ ev = {"type": "response.created", "response": {"id": rid, "object": "response", "status": "in_progress", "model": model_name, "output": []}}
689
+ self.wfile.write(f"event: response.created\ndata: {json.dumps(ev)}\n\n".encode())
690
+ for item in output:
691
+ if item["type"] == "function_call":
692
+ ev = {"type": "response.function_call_arguments.done", "item_id": item["id"], "call_id": item["call_id"], "name": item["name"], "arguments": item["arguments"]}
693
+ self.wfile.write(f"event: response.function_call_arguments.done\ndata: {json.dumps(ev)}\n\n".encode())
694
+ elif item["type"] == "message":
695
+ for ci, cp in enumerate(item["content"]):
696
+ ev = {"type": "response.output_text.done", "item_id": item["id"], "content_index": ci, "text": cp["text"]}
697
+ self.wfile.write(f"event: response.output_text.done\ndata: {json.dumps(ev)}\n\n".encode())
698
+ resp_obj = {"id": rid, "object": "response", "status": "completed", "model": model_name, "output": output,
699
+ "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}}
700
+ self.wfile.write(f"event: response.completed\ndata: {json.dumps({'type': 'response.completed', 'response': resp_obj})}\n\n".encode())
701
+ self.wfile.flush()
702
+ else:
703
+ self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
704
+ "model": model_name, "output": output,
705
+ "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}})
706
+
707
+
708
+ # ─── Google Native API (Gemini CLI compatible) ────────────────────────────
709
+
710
+ def _parse_google_model_from_path(self):
711
+ """Extract model name from /v1beta/models/{model}:method path."""
712
+ m = re.match(r'/v1beta/models/([^:?]+)', self.path)
713
+ if m:
714
+ return m.group(1)
715
+ return None
716
+
717
+ def _handle_google_models_list(self):
718
+ """GET /v1beta/models — Google AI format model list."""
719
+ models = []
720
+ for name, cfg in MODELS.items():
721
+ models.append({
722
+ "name": f"models/{name}",
723
+ "displayName": name,
724
+ "description": cfg["desc"],
725
+ "supportedGenerationMethods": ["generateContent", "streamGenerateContent"],
726
+ })
727
+ self.send_json({"models": models})
728
+
729
+ def _google_contents_to_prompt(self, req: dict) -> str:
730
+ """Convert Google API contents format to prompt string."""
731
+ parts = []
732
+ sys_inst = req.get("systemInstruction")
733
+ if sys_inst:
734
+ sys_parts = sys_inst.get("parts", [])
735
+ sys_text = " ".join(p.get("text", "") for p in sys_parts if p.get("text"))
736
+ if sys_text:
737
+ parts.append(f"[System instruction]: {sys_text}")
738
+
739
+ for content in req.get("contents", []):
740
+ role = content.get("role", "user")
741
+ text_parts = []
742
+ for p in content.get("parts", []):
743
+ if p.get("text"):
744
+ text_parts.append(p["text"])
745
+ text = " ".join(text_parts)
746
+ if role == "model":
747
+ parts.append(f"[Assistant]: {text}")
748
+ else:
749
+ parts.append(text)
750
+ return "\n\n".join(p for p in parts if p)
751
+
752
+ def _handle_google_generate(self, body: bytes, stream: bool):
753
+ """Handle Google native generateContent / streamGenerateContent."""
754
+ req = json.loads(body)
755
+ model_name = self._parse_google_model_from_path()
756
+ if not model_name:
757
+ self.send_json({"error": {"message": "model not specified in path"}}, 400)
758
+ return
759
+
760
+ model_name, model_id, think_mode, err = self._resolve_model(model_name)
761
+ if err:
762
+ self.send_json({"error": {"message": err}}, 400)
763
+ return
764
+
765
+ prompt = self._google_contents_to_prompt(req)
766
+ if not prompt.strip():
767
+ self.send_json({"error": {"message": "empty content"}}, 400)
768
+ return
769
+
770
+ try:
771
+ text, _ = self._call_gemini(prompt, model_id, think_mode, None)
772
+ except Exception as e:
773
+ self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
774
+ return
775
+
776
+ candidate = {
777
+ "content": {"parts": [{"text": text or ""}], "role": "model"},
778
+ "finishReason": "STOP",
779
+ "index": 0,
780
+ }
781
+ usage = {
782
+ "promptTokenCount": len(prompt) // 4,
783
+ "candidatesTokenCount": len(text) // 4,
784
+ "totalTokenCount": (len(prompt) + len(text)) // 4,
785
+ }
786
+ response_obj = {
787
+ "candidates": [candidate],
788
+ "usageMetadata": usage,
789
+ "modelVersion": model_name,
790
+ }
791
+
792
+ if stream:
793
+ self.send_response(200)
794
+ self.send_header("Content-Type", "text/event-stream")
795
+ self.send_header("Cache-Control", "no-cache")
796
+ self.send_header("Access-Control-Allow-Origin", "*")
797
+ self.end_headers()
798
+ self.wfile.write(f"data: {json.dumps(response_obj)}\n\n".encode())
799
+ self.wfile.flush()
800
+ else:
801
+ self.send_json(response_obj)
802
+
803
+
804
+ # ─── Main ────────────────────────────────────────────────────────────────────
805
+
806
+ def load_config(path: str):
807
+ if path and os.path.exists(path):
808
+ with open(path) as f:
809
+ CONFIG.update(json.load(f))
810
+ log(f"Config loaded: {path}")
811
+
812
+
813
+ def main():
814
+ parser = argparse.ArgumentParser(description="Gemini Web to OpenAI API")
815
+ parser.add_argument("--port", type=int, default=None)
816
+ parser.add_argument("--config", type=str, default=None)
817
+ parser.add_argument("--cookie-file", type=str, default=None, help="Path to cookie file")
818
+ parser.add_argument("--proxy", type=str, default=None, help="HTTP proxy, e.g. http://127.0.0.1:7890")
819
+ parser.add_argument("--version", action="version", version=f"gemini-web2api {__version__}")
820
+ args = parser.parse_args()
821
+
822
+ config_path = args.config or os.environ.get("GEMINI_WEB2API_CONFIG")
823
+ if not config_path:
824
+ for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
825
+ if os.path.exists(p):
826
+ config_path = p
827
+ break
828
+ load_config(config_path)
829
+
830
+ if args.port:
831
+ CONFIG["port"] = args.port
832
+ if args.cookie_file:
833
+ CONFIG["cookie_file"] = args.cookie_file
834
+ if args.proxy:
835
+ CONFIG["proxy"] = args.proxy
836
+
837
+ class ThreadedServer(ThreadingMixIn, HTTPServer):
838
+ daemon_threads = True
839
+ allow_reuse_address = True
840
+
841
+ port = CONFIG["port"]
842
+ server = ThreadedServer((CONFIG["host"], port), GeminiHandler)
843
+ print(f"gemini-web2api v{__version__}")
844
+ print(f" Listening: http://0.0.0.0:{port}")
845
+ print(f" Base URL: http://localhost:{port}/v1")
846
+ print(f" Models: {', '.join(MODELS.keys())}")
847
+ print(f" Cookie: {'yes (' + CONFIG['cookie_file'] + ')' if CONFIG.get('cookie_file') else 'none (anonymous)'}")
848
+ print(f" Proxy: {CONFIG.get('proxy') or 'none (uses system env HTTP_PROXY/HTTPS_PROXY)'}")
849
+ print(f" Retry: {CONFIG['retry_attempts']}x / {CONFIG['retry_delay_sec']}s")
850
+ print()
851
+ try:
852
+ server.serve_forever()
853
+ except KeyboardInterrupt:
854
+ print("\nStopped.")
855
+ server.shutdown()
856
+
857
+
858
+ if __name__ == "__main__":
859
+ main()
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,50 +1,52 @@
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()
42
- try:
43
- server.serve_forever()
44
- except KeyboardInterrupt:
45
- print("\nStopped.")
46
- server.shutdown()
47
-
48
-
49
- if __name__ == "__main__":
50
- main()
 
 
 
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()
gemini_web2api/__pycache__/__init__.cpython-314.pyc ADDED
Binary file (241 Bytes). View file
 
gemini_web2api/__pycache__/__main__.cpython-314.pyc ADDED
Binary file (3.4 kB). View file
 
gemini_web2api/__pycache__/config.cpython-314.pyc ADDED
Binary file (5.5 kB). View file
 
gemini_web2api/__pycache__/gemini.cpython-314.pyc ADDED
Binary file (15.9 kB). View file
 
gemini_web2api/__pycache__/models.cpython-314.pyc ADDED
Binary file (2.42 kB). View file
 
gemini_web2api/__pycache__/multimodal.cpython-314.pyc ADDED
Binary file (6.91 kB). View file
 
gemini_web2api/__pycache__/server.cpython-314.pyc ADDED
Binary file (28.3 kB). View file
 
gemini_web2api/__pycache__/tools.cpython-314.pyc ADDED
Binary file (17 kB). View file
 
gemini_web2api/config.py CHANGED
@@ -1,35 +1,88 @@
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_20260525.09_p0",
12
- "default_model": "gemini-3.5-flash",
13
- "log_requests": True,
14
- "cookie_file": None,
15
- "proxy": None,
16
- "api_keys": [],
17
- }
18
-
19
- CONFIG = dict(DEFAULT_CONFIG)
20
-
21
-
22
- def load_config(path: str = None):
23
- """Load config from JSON file."""
24
- if path and os.path.exists(path):
25
- with open(path) as f:
26
- CONFIG.update(json.load(f))
27
- return CONFIG
28
-
29
-
30
- def find_config():
31
- """Search for config file in standard locations."""
32
- for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
33
- if os.path.exists(p):
34
- return p
35
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "api_keys": [],
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 apply_env_overrides():
34
+ """Apply environment variables (Docker / Hugging Face Spaces secrets).
35
+
36
+ Priority: CLI args (caller) > env > config file > defaults.
37
+ Supported env:
38
+ PORT / HOST / PROXY
39
+ GEMINI_COOKIE_FILE / GEMINI_COOKIE (inline cookie file body)
40
+ API_KEYS (comma-separated)
41
+ AUTH_USER / XSRF_TOKEN
42
+ GEMINI_BL / DEFAULT_MODEL
43
+ LOG_REQUESTS (1/0 true/false)
44
+ """
45
+ if os.environ.get("PORT"):
46
+ CONFIG["port"] = int(os.environ["PORT"])
47
+ if os.environ.get("HOST"):
48
+ CONFIG["host"] = os.environ["HOST"]
49
+ if os.environ.get("PROXY"):
50
+ CONFIG["proxy"] = os.environ["PROXY"] or None
51
+
52
+ cookie_file = os.environ.get("GEMINI_COOKIE_FILE") or os.environ.get("COOKIE_FILE")
53
+ if cookie_file:
54
+ CONFIG["cookie_file"] = cookie_file
55
+ elif os.environ.get("GEMINI_COOKIE"):
56
+ # Write secret body to a temp path (Spaces has no durable volume on free tier)
57
+ path = os.path.join(tempfile.gettempdir(), "gemini_web2api_cookies.txt")
58
+ with open(path, "w", encoding="utf-8") as f:
59
+ f.write(os.environ["GEMINI_COOKIE"])
60
+ CONFIG["cookie_file"] = path
61
+
62
+ if os.environ.get("API_KEYS") is not None:
63
+ raw = os.environ["API_KEYS"].strip()
64
+ CONFIG["api_keys"] = [k.strip() for k in raw.split(",") if k.strip()] if raw else []
65
+
66
+ if "AUTH_USER" in os.environ:
67
+ v = os.environ["AUTH_USER"].strip()
68
+ CONFIG["auth_user"] = int(v) if v.isdigit() else (v or None)
69
+ if "XSRF_TOKEN" in os.environ:
70
+ CONFIG["xsrf_token"] = os.environ["XSRF_TOKEN"] or None
71
+ if os.environ.get("GEMINI_BL"):
72
+ CONFIG["gemini_bl"] = os.environ["GEMINI_BL"]
73
+ if os.environ.get("DEFAULT_MODEL"):
74
+ CONFIG["default_model"] = os.environ["DEFAULT_MODEL"]
75
+ if os.environ.get("LOG_REQUESTS") is not None:
76
+ CONFIG["log_requests"] = os.environ["LOG_REQUESTS"].strip().lower() in (
77
+ "1", "true", "yes", "on",
78
+ )
79
+
80
+ return CONFIG
81
+
82
+
83
+ def find_config():
84
+ """Search for config file in standard locations."""
85
+ for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
86
+ if os.path.exists(p):
87
+ return p
88
+ return None
gemini_web2api/gemini.py CHANGED
@@ -1,242 +1,257 @@
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 _build_headers() -> dict:
81
- headers = {
82
- "Content-Type": "application/x-www-form-urlencoded",
83
- "Origin": "https://gemini.google.com",
84
- "Referer": "https://gemini.google.com/app",
85
- "X-Same-Domain": "1",
86
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
87
- }
88
- cookie_str, sapisid = load_cookie()
89
- if cookie_str:
90
- headers["Cookie"] = cookie_str
91
- if sapisid:
92
- headers["Authorization"] = make_sapisidhash(sapisid)
93
- return headers
94
-
95
-
96
- def _build_payload(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
97
- inner = [None] * 102
98
- if file_refs:
99
- refs = [[None, None, ref] for ref in file_refs]
100
- inner[0] = [prompt, 0, None, refs, None, None, 0]
101
- else:
102
- inner[0] = [prompt, 0, None, None, None, None, 0]
103
- inner[1] = ["en"]
104
- inner[2] = ["", "", "", None, None, None, None, None, None, ""]
105
- inner[6] = [0]
106
- inner[7] = 1
107
- inner[10] = 1
108
- inner[11] = 0
109
- inner[17] = [[think_mode]]
110
- inner[18] = 0
111
- inner[27] = 1
112
- inner[30] = [4]
113
- inner[41] = [2]
114
- inner[53] = 0
115
- inner[59] = str(uuid.uuid4())
116
- inner[61] = []
117
- inner[68] = 1
118
- inner[79] = model_id
119
- if extra_fields:
120
- for k, v in extra_fields.items():
121
- inner[k] = v
122
- outer = [None, json.dumps(inner)]
123
- return urllib.parse.urlencode({"f.req": json.dumps(outer)})
124
-
125
-
126
- def _get_url() -> str:
127
- reqid = int(time.time()) % 1000000
128
- return (
129
- "https://gemini.google.com/_/BardChatUi/data/"
130
- "assistant.lamda.BardFrontendService/StreamGenerate"
131
- f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
132
- )
133
-
134
-
135
- def clean_text(text: str) -> str:
136
- text = re.sub(
137
- r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
138
- '', text, flags=re.DOTALL
139
- )
140
- text = re.sub(r'http://googleusercontent\.com/card_content/\d+\n?', '', text)
141
- return text.strip()
142
-
143
-
144
- def _extract_texts_from_line(line: str) -> list:
145
- """Parse a single wrb.fr line and return list of text strings found."""
146
- if '"wrb.fr"' not in line or len(line) < 200:
147
- return []
148
- try:
149
- arr = json.loads(line)
150
- inner_str = arr[0][2]
151
- if not inner_str or len(inner_str) < 50:
152
- return []
153
- inner = json.loads(inner_str)
154
- if not (isinstance(inner, list) and len(inner) > 4 and inner[4]):
155
- return []
156
- texts = []
157
- for part in inner[4]:
158
- if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
159
- for t in part[1]:
160
- if isinstance(t, str) and t:
161
- texts.append(t)
162
- return texts
163
- except (json.JSONDecodeError, IndexError, TypeError):
164
- return []
165
-
166
-
167
- def extract_response_text(raw: str) -> str:
168
- """Parse full response to get final text."""
169
- last_text = ""
170
- for line in raw.split("\n"):
171
- for t in _extract_texts_from_line(line):
172
- if len(t) > len(last_text):
173
- last_text = t
174
- return clean_text(last_text)
175
-
176
-
177
- def generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
178
- """Non-streaming generation with retry."""
179
- body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields).encode()
180
- url = _get_url()
181
- headers = _build_headers()
182
- ctx = _get_ssl_ctx()
183
- proxy = CONFIG.get("proxy")
184
-
185
- last_err = None
186
- for attempt in range(CONFIG["retry_attempts"]):
187
- try:
188
- req = urllib.request.Request(url, data=body, headers=headers, method="POST")
189
- if proxy:
190
- opener = urllib.request.build_opener(
191
- urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
192
- urllib.request.HTTPSHandler(context=ctx)
193
- )
194
- resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
195
- else:
196
- resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
197
- raw = resp.read().decode("utf-8", errors="replace")
198
- return extract_response_text(raw)
199
- except Exception as e:
200
- last_err = e
201
- if attempt < CONFIG["retry_attempts"] - 1:
202
- log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
203
- time.sleep(CONFIG["retry_delay_sec"])
204
- raise last_err
205
-
206
-
207
- def generate_stream(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None):
208
- """Streaming generation via httpx with retry on connection failure."""
209
- if not HAS_HTTPX:
210
- text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
211
- if text:
212
- yield text
213
- return
214
-
215
- body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields)
216
- url = _get_url()
217
- headers = _build_headers()
218
- client = _get_httpx_client()
219
-
220
- last_err = None
221
- for attempt in range(CONFIG["retry_attempts"]):
222
- try:
223
- prev_text = ""
224
- with client.stream("POST", url, content=body, headers=headers) as resp:
225
- buf = ""
226
- for chunk in resp.iter_text():
227
- buf += chunk
228
- while "\n" in buf:
229
- line, buf = buf.split("\n", 1)
230
- for t in _extract_texts_from_line(line):
231
- if len(t) > len(prev_text):
232
- delta = clean_text(t[len(prev_text):])
233
- if delta:
234
- yield delta
235
- prev_text = t
236
- return
237
- except Exception as e:
238
- last_err = e
239
- if attempt < CONFIG["retry_attempts"] - 1:
240
- log(f"Stream retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
241
- time.sleep(CONFIG["retry_delay_sec"])
242
- 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 _build_payload(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
108
+ inner = [None] * 102
109
+ if file_refs:
110
+ refs = [[None, None, ref] for ref in file_refs]
111
+ inner[0] = [prompt, 0, None, refs, None, None, 0]
112
+ else:
113
+ inner[0] = [prompt, 0, None, None, None, None, 0]
114
+ inner[1] = ["en"]
115
+ inner[2] = ["", "", "", None, None, None, None, None, None, ""]
116
+ inner[6] = [0]
117
+ inner[7] = 1
118
+ inner[10] = 1
119
+ inner[11] = 0
120
+ inner[17] = [[think_mode]]
121
+ inner[18] = 0
122
+ inner[27] = 1
123
+ inner[30] = [4]
124
+ inner[41] = [2]
125
+ inner[53] = 0
126
+ inner[59] = str(uuid.uuid4())
127
+ inner[61] = []
128
+ inner[68] = 1
129
+ inner[79] = model_id
130
+ if extra_fields:
131
+ for k, v in extra_fields.items():
132
+ inner[k] = v
133
+ outer = [None, json.dumps(inner)]
134
+ params = {"f.req": json.dumps(outer)}
135
+ if CONFIG.get("xsrf_token"):
136
+ params["at"] = CONFIG["xsrf_token"]
137
+ return urllib.parse.urlencode(params)
138
+
139
+
140
+ def _get_url() -> str:
141
+ reqid = int(time.time()) % 1000000
142
+ account_prefix = _account_prefix()
143
+ return (
144
+ f"https://gemini.google.com{account_prefix}/_/BardChatUi/data/"
145
+ "assistant.lamda.BardFrontendService/StreamGenerate"
146
+ f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
147
+ )
148
+
149
+
150
+ def clean_text(text: str) -> str:
151
+ text = re.sub(
152
+ r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
153
+ '', text, flags=re.DOTALL
154
+ )
155
+ text = re.sub(r'http://googleusercontent\.com/card_content/\d+\n?', '', text)
156
+ return text.strip()
157
+
158
+
159
+ def _extract_texts_from_line(line: str) -> list:
160
+ """Parse a single wrb.fr line and return list of text strings found."""
161
+ if '"wrb.fr"' not in line or len(line) < 200:
162
+ return []
163
+ try:
164
+ arr = json.loads(line)
165
+ inner_str = arr[0][2]
166
+ if not inner_str or len(inner_str) < 50:
167
+ return []
168
+ inner = json.loads(inner_str)
169
+ if not (isinstance(inner, list) and len(inner) > 4 and inner[4]):
170
+ return []
171
+ texts = []
172
+ for part in inner[4]:
173
+ if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
174
+ for t in part[1]:
175
+ if isinstance(t, str) and t:
176
+ texts.append(t)
177
+ return texts
178
+ except (json.JSONDecodeError, IndexError, TypeError):
179
+ return []
180
+
181
+
182
+ def extract_response_text(raw: str) -> str:
183
+ """Parse full response to get final text."""
184
+ last_text = ""
185
+ for line in raw.split("\n"):
186
+ for t in _extract_texts_from_line(line):
187
+ if len(t) > len(last_text):
188
+ last_text = t
189
+ return clean_text(last_text)
190
+
191
+
192
+ def generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None) -> str:
193
+ """Non-streaming generation with retry."""
194
+ body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields).encode()
195
+ url = _get_url()
196
+ headers = _build_headers()
197
+ ctx = _get_ssl_ctx()
198
+ proxy = CONFIG.get("proxy")
199
+
200
+ last_err = None
201
+ for attempt in range(CONFIG["retry_attempts"]):
202
+ try:
203
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
204
+ if proxy:
205
+ opener = urllib.request.build_opener(
206
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
207
+ urllib.request.HTTPSHandler(context=ctx)
208
+ )
209
+ resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
210
+ else:
211
+ resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
212
+ raw = resp.read().decode("utf-8", errors="replace")
213
+ return extract_response_text(raw)
214
+ except Exception as e:
215
+ last_err = e
216
+ if attempt < CONFIG["retry_attempts"] - 1:
217
+ log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
218
+ time.sleep(CONFIG["retry_delay_sec"])
219
+ raise last_err
220
+
221
+
222
+ def generate_stream(prompt: str, model_id: int, think_mode: int, file_refs: list = None, extra_fields: dict = None):
223
+ """Streaming generation via httpx with retry on connection failure."""
224
+ if not HAS_HTTPX:
225
+ text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
226
+ if text:
227
+ yield text
228
+ return
229
+
230
+ body = _build_payload(prompt, model_id, think_mode, file_refs, extra_fields)
231
+ url = _get_url()
232
+ headers = _build_headers()
233
+ client = _get_httpx_client()
234
+
235
+ last_err = None
236
+ for attempt in range(CONFIG["retry_attempts"]):
237
+ try:
238
+ prev_text = ""
239
+ with client.stream("POST", url, content=body, headers=headers) as resp:
240
+ buf = ""
241
+ for chunk in resp.iter_text():
242
+ buf += chunk
243
+ while "\n" in buf:
244
+ line, buf = buf.split("\n", 1)
245
+ for t in _extract_texts_from_line(line):
246
+ if len(t) > len(prev_text):
247
+ delta = clean_text(t[len(prev_text):])
248
+ if delta:
249
+ yield delta
250
+ prev_text = t
251
+ return
252
+ except Exception as e:
253
+ last_err = e
254
+ if attempt < CONFIG["retry_attempts"] - 1:
255
+ log(f"Stream retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
256
+ time.sleep(CONFIG["retry_delay_sec"])
257
+ raise last_err
gemini_web2api/models.py CHANGED
@@ -1,60 +1,64 @@
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.5-flash": {
8
- "mode": 1, "think": 4,
9
- "desc": "Fast general-purpose model",
10
- },
11
- "gemini-3.5-flash-thinking": {
12
- "mode": 2, "think": 0,
13
- "desc": "Deep thinking mode, longest output (~20k chars)",
14
- },
15
- "gemini-3.1-pro": {
16
- "mode": 3, "think": 4,
17
- "desc": "Pro model (requires cookie for real routing)",
18
- },
19
- "gemini-3.1-pro-enhanced": {
20
- "mode": 3, "think": 4, "extra": {31: 2, 80: 3},
21
- "desc": "Pro with enhanced output (experimental)",
22
- },
23
- "gemini-auto": {
24
- "mode": 4, "think": 4,
25
- "desc": "Auto model selection",
26
- },
27
- "gemini-3.5-flash-thinking-lite": {
28
- "mode": 5, "think": 0,
29
- "desc": "Dynamic thinking with adaptive depth",
30
- },
31
- "gemini-flash-lite": {
32
- "mode": 6, "think": 4,
33
- "desc": "Lightweight fast model",
34
- },
35
- }
36
-
37
-
38
- def resolve_model(model_name: str, default: str = "gemini-3.5-flash"):
39
- """Resolve model name to (name, mode_id, think_mode, error, extra_fields).
40
-
41
- Unknown model names fall back to default rather than erroring,
42
- since upstream clients may request arbitrary model identifiers.
43
- """
44
- think_override = None
45
- if "@think=" in model_name:
46
- model_name, think_str = model_name.rsplit("@think=", 1)
47
- try:
48
- think_override = int(think_str)
49
- except ValueError:
50
- return None, None, None, f"Invalid think level: {think_str}", None
51
- cfg = MODELS.get(model_name)
52
- if not cfg:
53
- from .gemini import log
54
- log(f"Unknown model '{model_name}', falling back to '{default}'")
55
- model_name = default
56
- cfg = MODELS[default]
57
- mode_id = cfg["mode"]
58
- think_mode = think_override if think_override is not None else cfg["think"]
59
- extra = cfg.get("extra")
60
- 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.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
gemini_web2api/multimodal.py CHANGED
@@ -1,127 +1,127 @@
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
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("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 = "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(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
+
10
+ from .config import CONFIG
11
+ from .gemini import load_cookie, make_sapisidhash, _get_ssl_ctx, log
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("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 = "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(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""
gemini_web2api/server.py CHANGED
@@ -1,413 +1,424 @@
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
- auth = self.headers.get("Authorization", "")
74
- key = auth[7:] if auth.startswith("Bearer ") else self.headers.get("x-api-key", "")
75
- return key in keys
76
-
77
- def do_OPTIONS(self):
78
- self.send_response(204)
79
- self.send_header("Access-Control-Allow-Origin", "*")
80
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
81
- self.send_header("Access-Control-Allow-Headers", "*")
82
- self.end_headers()
83
-
84
- def do_GET(self):
85
- try:
86
- if self.path.startswith("/v1/") and not self._authorized():
87
- self.send_json({"error": {"message": "invalid api key"}}, 401)
88
- return
89
- if self.path == "/v1/models":
90
- self.send_json({"object": "list", "data": [
91
- {"id": n, "object": "model", "created": 1700000000,
92
- "owned_by": "google", "description": c["desc"]}
93
- for n, c in MODELS.items()
94
- ]})
95
- elif self.path.startswith("/v1beta/models"):
96
- self.send_json({"models": [
97
- {"name": f"models/{n}", "displayName": n, "description": c["desc"],
98
- "supportedGenerationMethods": ["generateContent", "streamGenerateContent"]}
99
- for n, c in MODELS.items()
100
- ]})
101
- elif self.path == "/":
102
- self.send_json({"status": "ok", "version": __version__, "models": list(MODELS.keys())})
103
- else:
104
- self.send_json({"error": "not found"}, 404)
105
- except (BrokenPipeError, ConnectionResetError):
106
- pass
107
-
108
- def do_POST(self):
109
- try:
110
- if self.path.startswith("/v1/") and not self._authorized():
111
- self.send_json({"error": {"message": "invalid api key"}}, 401)
112
- return
113
- length = int(self.headers.get("Content-Length", 0))
114
- body = self.rfile.read(length) if length else b""
115
- if self.path == "/v1/chat/completions":
116
- self._handle_chat(body)
117
- elif self.path == "/v1/responses":
118
- self._handle_responses(body)
119
- elif ":generateContent" in self.path:
120
- self._handle_google_generate(body, stream=False)
121
- elif ":streamGenerateContent" in self.path:
122
- self._handle_google_generate(body, stream=True)
123
- else:
124
- self.send_json({"error": "not found"}, 404)
125
- except (BrokenPipeError, ConnectionResetError):
126
- pass
127
- except Exception as e:
128
- log(f"POST error: {e}")
129
- try:
130
- self.send_json({"error": {"message": str(e)}}, 500)
131
- except:
132
- pass
133
-
134
- # ─── /v1/chat/completions ─────────────────────────────────────────────────
135
-
136
- def _handle_chat(self, body: bytes):
137
- req = self._parse_body(body)
138
- if req is None:
139
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
140
- return
141
- model_name, model_id, think_mode, err, extra_fields = resolve_model(
142
- req.get("model", CONFIG["default_model"]))
143
- if err:
144
- self.send_json({"error": {"message": err}}, 400)
145
- return
146
-
147
- tools = req.get("tools")
148
- tool_choice = req.get("tool_choice", "auto")
149
- prompt, images = messages_to_prompt(req.get("messages", []), tools, tool_choice)
150
- if not prompt.strip():
151
- self.send_json({"error": {"message": "empty prompt"}}, 400)
152
- return
153
-
154
- stream = req.get("stream", False)
155
- cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
156
-
157
- if stream and (not tools or tool_choice == "none"):
158
- try:
159
- self._start_sse()
160
- for delta in generate_stream(prompt, model_id, think_mode, _upload_images(images), extra_fields):
161
- chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
162
- "model": model_name, "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}]}
163
- self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
164
- self.wfile.flush()
165
- end = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
166
- "model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
167
- self.wfile.write(f"data: {json.dumps(end)}\n\n".encode())
168
- self.wfile.write(b"data: [DONE]\n\n")
169
- self.wfile.flush()
170
- except (BrokenPipeError, ConnectionResetError):
171
- pass
172
- return
173
-
174
- try:
175
- text = generate(prompt, model_id, think_mode, _upload_images(images), extra_fields)
176
- except Exception as e:
177
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
178
- return
179
-
180
- tool_calls = None
181
- if tools and text and tool_choice != "none":
182
- text, tool_calls = parse_tool_calls(text)
183
- msg = {"role": "assistant", "content": text or None}
184
- if tool_calls:
185
- msg["tool_calls"] = tool_calls
186
- finish = "tool_calls" if tool_calls else "stop"
187
-
188
- if stream:
189
- self._start_sse()
190
- chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
191
- "model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
192
- self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
193
- self.wfile.write(b"data: [DONE]\n\n")
194
- self.wfile.flush()
195
- else:
196
- self.send_json({
197
- "id": cid, "object": "chat.completion", "created": int(time.time()),
198
- "model": model_name,
199
- "choices": [{"index": 0, "message": msg, "finish_reason": finish}],
200
- "usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text or "")//4,
201
- "total_tokens": (len(prompt)+len(text or ""))//4},
202
- })
203
-
204
- # ─── /v1/responses (Codex CLI) ───────────────────────────────────────────
205
-
206
- def _handle_responses(self, body: bytes):
207
- req = self._parse_body(body)
208
- if req is None:
209
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
210
- return
211
- model_name, model_id, think_mode, err, extra_fields = resolve_model(
212
- req.get("model", CONFIG["default_model"]))
213
- if err:
214
- self.send_json({"error": {"message": err}}, 400)
215
- return
216
-
217
- input_items = req.get("input", [])
218
- tools = req.get("tools")
219
- messages = []
220
- if req.get("instructions"):
221
- messages.append({"role": "system", "content": req["instructions"]})
222
- if isinstance(input_items, str):
223
- messages.append({"role": "user", "content": input_items})
224
- elif isinstance(input_items, list):
225
- for item in input_items:
226
- if isinstance(item, str):
227
- messages.append({"role": "user", "content": item})
228
- elif isinstance(item, dict):
229
- if item.get("type") == "function_call_output":
230
- messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
231
- "name": item.get("name", ""), "content": item.get("output", "")})
232
- elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
233
- cp = item.get("content", [])
234
- text_acc, tc_list = "", []
235
- if isinstance(cp, list):
236
- for c in cp:
237
- if isinstance(c, dict):
238
- if c.get("type") == "output_text": text_acc += c.get("text", "")
239
- elif c.get("type") == "function_call": tc_list.append(c)
240
- elif isinstance(cp, str):
241
- text_acc = cp
242
- m = {"role": "assistant", "content": text_acc or None}
243
- if tc_list:
244
- m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
245
- "function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
246
- for i, tc in enumerate(tc_list)]
247
- messages.append(m)
248
- else:
249
- role = item.get("role", "user")
250
- content = item.get("content", "")
251
- if isinstance(content, list):
252
- content = " ".join(c.get("text", "") for c in content if c.get("type") in ("text", "input_text"))
253
- messages.append({"role": role, "content": content})
254
-
255
- if tools:
256
- tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
257
- if t.get("type") == "function" and "function" not in t else t for t in tools]
258
-
259
- tool_choice = req.get("tool_choice", "auto")
260
- prompt, images = messages_to_prompt(messages, tools, tool_choice)
261
- if not prompt.strip():
262
- self.send_json({"error": {"message": "empty input"}}, 400)
263
- return
264
-
265
- try:
266
- text = generate(prompt, model_id, think_mode, _upload_images(images), extra_fields)
267
- except Exception as e:
268
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
269
- return
270
-
271
- tool_calls = None
272
- if tools and text and tool_choice != "none":
273
- text, tool_calls = parse_tool_calls(text)
274
-
275
- rid = f"resp_{uuid.uuid4().hex[:16]}"
276
- mid = f"msg_{uuid.uuid4().hex[:12]}"
277
- output = []
278
- if tool_calls:
279
- for tc in tool_calls:
280
- output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
281
- "name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
282
- if text or not tool_calls:
283
- output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
284
- "content": [{"type": "output_text", "text": text or "", "annotations": []}]})
285
-
286
- if req.get("stream"):
287
- self.send_response(200)
288
- self.send_header("Content-Type", "text/event-stream")
289
- self.send_header("Cache-Control", "no-cache")
290
- self.send_header("Access-Control-Allow-Origin", "*")
291
- self.end_headers()
292
- ev = {"type": "response.created", "response": {"id": rid, "object": "response", "status": "in_progress", "model": model_name, "output": []}}
293
- self.wfile.write(f"event: response.created\ndata: {json.dumps(ev)}\n\n".encode())
294
- for item in output:
295
- if item["type"] == "function_call":
296
- ev = {"type": "response.function_call_arguments.done", "item_id": item["id"], "call_id": item["call_id"], "name": item["name"], "arguments": item["arguments"]}
297
- self.wfile.write(f"event: response.function_call_arguments.done\ndata: {json.dumps(ev)}\n\n".encode())
298
- elif item["type"] == "message":
299
- for ci, cp in enumerate(item["content"]):
300
- ev = {"type": "response.output_text.done", "item_id": item["id"], "content_index": ci, "text": cp["text"]}
301
- self.wfile.write(f"event: response.output_text.done\ndata: {json.dumps(ev)}\n\n".encode())
302
- resp_obj = {"id": rid, "object": "response", "status": "completed", "model": model_name, "output": output,
303
- "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text or "")//4, "total_tokens": (len(prompt)+len(text or ""))//4}}
304
- self.wfile.write(f"event: response.completed\ndata: {json.dumps({'type': 'response.completed', 'response': resp_obj})}\n\n".encode())
305
- self.wfile.flush()
306
- else:
307
- self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
308
- "model": model_name, "output": output,
309
- "usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text or "")//4, "total_tokens": (len(prompt)+len(text or ""))//4}})
310
-
311
- # ─── /v1beta/models (Google Gemini CLI) ──────────────────────────────────
312
-
313
- def _handle_google_generate(self, body: bytes, stream: bool):
314
- req = self._parse_body(body)
315
- if req is None:
316
- self.send_json({"error": {"message": "invalid JSON"}}, 400)
317
- return
318
- m = re.match(r'/v1beta/models/([^:?]+)', self.path)
319
- model_name = m.group(1) if m else CONFIG["default_model"]
320
- model_name, model_id, think_mode, err, extra_fields = resolve_model(model_name)
321
- if err:
322
- self.send_json({"error": {"message": err}}, 400)
323
- return
324
-
325
- tool_config = req.get("toolConfig", {})
326
- fc_mode = tool_config.get("functionCallingConfig", {}).get("mode", "AUTO")
327
- has_tools = bool(req.get("tools")) and fc_mode != "NONE"
328
- prompt, images = google_contents_to_prompt(req)
329
- if not prompt.strip():
330
- self.send_json({"error": {"message": "empty content"}}, 400)
331
- return
332
-
333
- file_refs = _upload_images(images)
334
- log(f"Google API: model={model_name} stream={stream} tools={has_tools} prompt_len={len(prompt)}")
335
-
336
- if stream and not has_tools:
337
- try:
338
- self._start_sse()
339
- full_text = ""
340
- for delta in generate_stream(prompt, model_id, think_mode, file_refs, extra_fields):
341
- if not delta:
342
- continue
343
- full_text += delta
344
- chunk_obj = {
345
- "candidates": [{"content": {"parts": [{"text": delta}], "role": "model"}, "index": 0}],
346
- "modelVersion": model_name,
347
- }
348
- self.wfile.write(f"data: {json.dumps(chunk_obj, ensure_ascii=False)}\n\n".encode())
349
- self.wfile.flush()
350
- final_chunk = {
351
- "candidates": [{"finishReason": "STOP", "index": 0}],
352
- "usageMetadata": {
353
- "promptTokenCount": len(prompt) // 4,
354
- "candidatesTokenCount": len(full_text) // 4,
355
- "totalTokenCount": (len(prompt) + len(full_text)) // 4,
356
- },
357
- "modelVersion": model_name,
358
- }
359
- self.wfile.write(f"data: {json.dumps(final_chunk, ensure_ascii=False)}\n\n".encode())
360
- self.wfile.flush()
361
- except (BrokenPipeError, ConnectionResetError):
362
- pass
363
- return
364
-
365
- try:
366
- text = generate(prompt, model_id, think_mode, file_refs, extra_fields)
367
- except Exception as e:
368
- self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
369
- return
370
-
371
- if not text:
372
- log("Warning: empty response from Gemini")
373
-
374
- response_parts = []
375
- if has_tools and text:
376
- clean_text, function_calls = parse_google_function_calls(text)
377
- if function_calls:
378
- if clean_text:
379
- response_parts.append({"text": clean_text})
380
- for fc in function_calls:
381
- response_parts.append({"functionCall": {"name": fc["name"], "args": fc["args"]}})
382
- else:
383
- response_parts.append({"text": text})
384
- else:
385
- response_parts.append({"text": text or "I apologize, but I was unable to generate a response. Please try again."})
386
-
387
- candidate = {
388
- "content": {"parts": response_parts, "role": "model"},
389
- "finishReason": "STOP",
390
- "index": 0,
391
- }
392
- usage = {
393
- "promptTokenCount": len(prompt) // 4,
394
- "candidatesTokenCount": len(text or "") // 4,
395
- "totalTokenCount": (len(prompt) + len(text or "")) // 4,
396
- }
397
- response_obj = {
398
- "candidates": [candidate],
399
- "usageMetadata": usage,
400
- "modelVersion": model_name,
401
- }
402
-
403
- if stream:
404
- self._start_sse()
405
- self.wfile.write(f"data: {json.dumps(response_obj, ensure_ascii=False)}\n\n".encode())
406
- self.wfile.flush()
407
- else:
408
- self.send_json(response_obj)
409
-
410
-
411
- class ThreadedServer(ThreadingMixIn, HTTPServer):
412
- daemon_threads = True
413
- 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 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
gemini_web2api/tools.py CHANGED
@@ -1,287 +1,287 @@
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 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
pyproject.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "gemini-web2api"
3
+ version = "1.1.0"
4
+ description = "Convert Google Gemini web into OpenAI-compatible API"
5
+ readme = "README.md"
6
+ license = {text = "MIT"}
7
+ requires-python = ">=3.8"
8
+ dependencies = []
9
+
10
+ [project.optional-dependencies]
11
+ streaming = ["httpx>=0.25"]
12
+
13
+ [project.scripts]
14
+ gemini-web2api = "gemini_web2api.__main__:main"
15
+
16
+ [build-system]
17
+ requires = ["setuptools>=68"]
18
+ build-backend = "setuptools.build_meta"
requirements.txt CHANGED
@@ -1 +1 @@
1
- httpx>=0.25
 
1
+ httpx>=0.25