@arhan-w/ibex 0.0.0-stage → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +295 -2
- package/npm-package/LICENSE +21 -0
- package/npm-package/README.md +176 -0
- package/npm-package/bin/goat.js +3 -0
- package/npm-package/bin/ibex.js +77 -0
- package/npm-package/package.json +58 -0
- package/npm-package/scripts/install-binary.js +168 -0
- package/package.json +69 -6
- package/src/agent.ts +695 -0
- package/src/agents/loader.ts +110 -0
- package/src/ambient.d.ts +2 -0
- package/src/code/extract.ts +292 -0
- package/src/code/find.ts +244 -0
- package/src/code/grammars.ts +88 -0
- package/src/code/indexer.ts +242 -0
- package/src/code/semantic.ts +253 -0
- package/src/code/slash.ts +88 -0
- package/src/code/tool.ts +40 -0
- package/src/collab/client.ts +141 -0
- package/src/collab/handlers.ts +141 -0
- package/src/collab/invite.ts +39 -0
- package/src/collab/relay.ts +106 -0
- package/src/collab/sync.ts +131 -0
- package/src/commands.tsx +943 -0
- package/src/computer.ts +629 -0
- package/src/config.ts +318 -0
- package/src/constants.ts +18 -0
- package/src/context.ts +73 -0
- package/src/data/providers.json +2342 -0
- package/src/diff.ts +50 -0
- package/src/doctor.ts +443 -0
- package/src/errors.ts +139 -0
- package/src/gflash.ts +170 -0
- package/src/hooks.ts +133 -0
- package/src/ide/assets.gen.ts +3 -0
- package/src/ide/index.html +844 -0
- package/src/ide/server.ts +506 -0
- package/src/ide/vendor/marked.umd.js +80 -0
- package/src/ide/vendor/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
- package/src/ide/vendor/vs/base/worker/workerMain.js +31 -0
- package/src/ide/vendor/vs/basic-languages/abap/abap.js +10 -0
- package/src/ide/vendor/vs/basic-languages/apex/apex.js +10 -0
- package/src/ide/vendor/vs/basic-languages/azcli/azcli.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bat/bat.js +10 -0
- package/src/ide/vendor/vs/basic-languages/bicep/bicep.js +11 -0
- package/src/ide/vendor/vs/basic-languages/cameligo/cameligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/clojure/clojure.js +10 -0
- package/src/ide/vendor/vs/basic-languages/coffee/coffee.js +10 -0
- package/src/ide/vendor/vs/basic-languages/cpp/cpp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csharp/csharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/csp/csp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/css/css.js +12 -0
- package/src/ide/vendor/vs/basic-languages/cypher/cypher.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dart/dart.js +10 -0
- package/src/ide/vendor/vs/basic-languages/dockerfile/dockerfile.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ecl/ecl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/elixir/elixir.js +10 -0
- package/src/ide/vendor/vs/basic-languages/flow9/flow9.js +10 -0
- package/src/ide/vendor/vs/basic-languages/freemarker2/freemarker2.js +12 -0
- package/src/ide/vendor/vs/basic-languages/fsharp/fsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/go/go.js +10 -0
- package/src/ide/vendor/vs/basic-languages/graphql/graphql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/handlebars/handlebars.js +10 -0
- package/src/ide/vendor/vs/basic-languages/hcl/hcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/html/html.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ini/ini.js +10 -0
- package/src/ide/vendor/vs/basic-languages/java/java.js +10 -0
- package/src/ide/vendor/vs/basic-languages/javascript/javascript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/julia/julia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/kotlin/kotlin.js +10 -0
- package/src/ide/vendor/vs/basic-languages/less/less.js +11 -0
- package/src/ide/vendor/vs/basic-languages/lexon/lexon.js +10 -0
- package/src/ide/vendor/vs/basic-languages/liquid/liquid.js +10 -0
- package/src/ide/vendor/vs/basic-languages/lua/lua.js +10 -0
- package/src/ide/vendor/vs/basic-languages/m3/m3.js +10 -0
- package/src/ide/vendor/vs/basic-languages/markdown/markdown.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mdx/mdx.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mips/mips.js +10 -0
- package/src/ide/vendor/vs/basic-languages/msdax/msdax.js +10 -0
- package/src/ide/vendor/vs/basic-languages/mysql/mysql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/objective-c/objective-c.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascal/pascal.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pascaligo/pascaligo.js +10 -0
- package/src/ide/vendor/vs/basic-languages/perl/perl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pgsql/pgsql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/php/php.js +10 -0
- package/src/ide/vendor/vs/basic-languages/pla/pla.js +10 -0
- package/src/ide/vendor/vs/basic-languages/postiats/postiats.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powerquery/powerquery.js +10 -0
- package/src/ide/vendor/vs/basic-languages/powershell/powershell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/protobuf/protobuf.js +11 -0
- package/src/ide/vendor/vs/basic-languages/pug/pug.js +10 -0
- package/src/ide/vendor/vs/basic-languages/python/python.js +10 -0
- package/src/ide/vendor/vs/basic-languages/qsharp/qsharp.js +10 -0
- package/src/ide/vendor/vs/basic-languages/r/r.js +10 -0
- package/src/ide/vendor/vs/basic-languages/razor/razor.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redis/redis.js +10 -0
- package/src/ide/vendor/vs/basic-languages/redshift/redshift.js +10 -0
- package/src/ide/vendor/vs/basic-languages/restructuredtext/restructuredtext.js +10 -0
- package/src/ide/vendor/vs/basic-languages/ruby/ruby.js +10 -0
- package/src/ide/vendor/vs/basic-languages/rust/rust.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sb/sb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scala/scala.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scheme/scheme.js +10 -0
- package/src/ide/vendor/vs/basic-languages/scss/scss.js +12 -0
- package/src/ide/vendor/vs/basic-languages/shell/shell.js +10 -0
- package/src/ide/vendor/vs/basic-languages/solidity/solidity.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sophia/sophia.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sparql/sparql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/sql/sql.js +10 -0
- package/src/ide/vendor/vs/basic-languages/st/st.js +10 -0
- package/src/ide/vendor/vs/basic-languages/swift/swift.js +13 -0
- package/src/ide/vendor/vs/basic-languages/systemverilog/systemverilog.js +10 -0
- package/src/ide/vendor/vs/basic-languages/tcl/tcl.js +10 -0
- package/src/ide/vendor/vs/basic-languages/twig/twig.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typescript/typescript.js +10 -0
- package/src/ide/vendor/vs/basic-languages/typespec/typespec.js +10 -0
- package/src/ide/vendor/vs/basic-languages/vb/vb.js +10 -0
- package/src/ide/vendor/vs/basic-languages/wgsl/wgsl.js +307 -0
- package/src/ide/vendor/vs/basic-languages/xml/xml.js +10 -0
- package/src/ide/vendor/vs/basic-languages/yaml/yaml.js +10 -0
- package/src/ide/vendor/vs/editor/editor.main.css +8 -0
- package/src/ide/vendor/vs/editor/editor.main.js +798 -0
- package/src/ide/vendor/vs/language/css/cssMode.js +13 -0
- package/src/ide/vendor/vs/language/css/cssWorker.js +77 -0
- package/src/ide/vendor/vs/language/html/htmlMode.js +13 -0
- package/src/ide/vendor/vs/language/html/htmlWorker.js +454 -0
- package/src/ide/vendor/vs/language/json/jsonMode.js +19 -0
- package/src/ide/vendor/vs/language/json/jsonWorker.js +42 -0
- package/src/ide/vendor/vs/language/typescript/tsMode.js +20 -0
- package/src/ide/vendor/vs/language/typescript/tsWorker.js +51328 -0
- package/src/ide/vendor/vs/loader.js +11 -0
- package/src/index-shared.ts +117 -0
- package/src/index.ts +586 -0
- package/src/llm.ts +721 -0
- package/src/logger.ts +39 -0
- package/src/mcp/client.ts +121 -0
- package/src/mcp/types.ts +27 -0
- package/src/oauth.ts +205 -0
- package/src/onboarding.ts +140 -0
- package/src/palette.tsx +199 -0
- package/src/permissions.ts +123 -0
- package/src/plugins/loader.ts +120 -0
- package/src/plugins/marketplace.ts +252 -0
- package/src/plugins/sandbox.ts +303 -0
- package/src/plugins/tar.ts +241 -0
- package/src/pricing.ts +78 -0
- package/src/protocol/client.ts +102 -0
- package/src/protocol/rpc.ts +43 -0
- package/src/protocol/serve.ts +136 -0
- package/src/providers.ts +402 -0
- package/src/rate-limiter.ts +101 -0
- package/src/refs.ts +97 -0
- package/src/runtime.ts +144 -0
- package/src/session.ts +401 -0
- package/src/skills/loader.ts +136 -0
- package/src/statusline.ts +70 -0
- package/src/system-prompt.ts +28 -0
- package/src/tools.ts +1280 -0
- package/src/tui.tsx +1355 -0
- package/src/update.ts +236 -0
- package/src/vendor/flashServer.ts +2 -0
- package/src/vendor/gemini-web2api/gemini_web2api.py +1136 -0
- package/src/virtual-list.tsx +125 -0
- package/src/window.ts +31 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,1136 @@
|
|
|
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
|
+
import binascii
|
|
36
|
+
from typing import Optional
|
|
37
|
+
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
38
|
+
from socketserver import ThreadingMixIn
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
import httpx
|
|
42
|
+
HAS_HTTPX = True
|
|
43
|
+
except ImportError:
|
|
44
|
+
HAS_HTTPX = False
|
|
45
|
+
|
|
46
|
+
__version__ = "1.1.0"
|
|
47
|
+
|
|
48
|
+
# ─── Configuration ───────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
DEFAULT_CONFIG = {
|
|
51
|
+
"port": 8081,
|
|
52
|
+
# Goated fork: bind loopback only — the server is embedded in GoatCode
|
|
53
|
+
# and must never be reachable from the LAN.
|
|
54
|
+
"host": "127.0.0.1",
|
|
55
|
+
"retry_attempts": 3,
|
|
56
|
+
"retry_delay_sec": 2,
|
|
57
|
+
"request_timeout_sec": 180,
|
|
58
|
+
"gemini_bl": "boq_assistant-bard-web-server_20260716.08_p0",
|
|
59
|
+
"auth_user": None,
|
|
60
|
+
"xsrf_token": None,
|
|
61
|
+
"default_model": "goated-flash",
|
|
62
|
+
"log_requests": True,
|
|
63
|
+
"cookie_file": None,
|
|
64
|
+
"proxy": None,
|
|
65
|
+
"api_keys": [],
|
|
66
|
+
"temporary_chats": False,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
CONFIG = dict(DEFAULT_CONFIG)
|
|
70
|
+
|
|
71
|
+
# ─── Models ──────────────────────────────────────────────────────────────────
|
|
72
|
+
# Mapping from JS source: MODE_CATEGORY enum (028-6eb337387583.js)
|
|
73
|
+
# 1=FAST, 2=THINKING, 3=PRO, 4=AUTO, 5=FAST_DYNAMIC_THINKING, 6=FLASH_LITE
|
|
74
|
+
|
|
75
|
+
MODELS = {
|
|
76
|
+
"gemini-3.7-flash": {
|
|
77
|
+
"mode": 1, "think": 4,
|
|
78
|
+
"desc": "Latest all-around model (Gemini 3.7 Flash)",
|
|
79
|
+
},
|
|
80
|
+
"gemini-3.6-flash": {
|
|
81
|
+
"mode": 1, "think": 4,
|
|
82
|
+
"desc": "All-around model (Gemini 3.6 Flash)",
|
|
83
|
+
},
|
|
84
|
+
"gemini-3.5-flash": {
|
|
85
|
+
"mode": 1, "think": 4,
|
|
86
|
+
"desc": "Alias for gemini-3.6-flash (backend upgraded)",
|
|
87
|
+
},
|
|
88
|
+
"gemini-3.5-flash-thinking": {
|
|
89
|
+
"mode": 2, "think": 0,
|
|
90
|
+
"desc": "Deep thinking mode, longest output (~20k chars)",
|
|
91
|
+
},
|
|
92
|
+
"gemini-3.1-pro": {
|
|
93
|
+
"mode": 3, "think": 4,
|
|
94
|
+
"desc": "Pro model (requires cookie for real routing)",
|
|
95
|
+
},
|
|
96
|
+
"gemini-auto": {
|
|
97
|
+
"mode": 4, "think": 4,
|
|
98
|
+
"desc": "Auto model selection",
|
|
99
|
+
},
|
|
100
|
+
"gemini-3.5-flash-thinking-lite": {
|
|
101
|
+
"mode": 5, "think": 0,
|
|
102
|
+
"desc": "Dynamic thinking with adaptive depth",
|
|
103
|
+
},
|
|
104
|
+
"gemini-flash-lite": {
|
|
105
|
+
"mode": 6, "think": 4,
|
|
106
|
+
"desc": "Lightweight fast model",
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
# ─── Goated aliases (brand-neutral names for the Goated-Flash-Free tier)
|
|
111
|
+
for _ga, _gb in {
|
|
112
|
+
"goated-flash": "gemini-3.5-flash",
|
|
113
|
+
"goated-1-flash": "gemini-3.5-flash",
|
|
114
|
+
"goated-2-flash": "gemini-3.6-flash",
|
|
115
|
+
"goated-3-flash": "gemini-3.7-flash",
|
|
116
|
+
"goated-1-flash-thinking": "gemini-3.5-flash-thinking",
|
|
117
|
+
"goated-flash-lite": "gemini-flash-lite",
|
|
118
|
+
"goated-pro": "gemini-3.1-pro",
|
|
119
|
+
"goated-auto": "gemini-auto",
|
|
120
|
+
}.items():
|
|
121
|
+
if _gb in MODELS:
|
|
122
|
+
_c = dict(MODELS[_gb])
|
|
123
|
+
_c["desc"] = _c.get("desc", "").replace("Gemini", "Goated").replace("gemini-", "goated-")
|
|
124
|
+
MODELS[_ga] = _c
|
|
125
|
+
for _gb in [k for k in MODELS if k.startswith("gemini-")]:
|
|
126
|
+
del MODELS[_gb]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ─── Utilities ───────────────────────────────────────────────────────────────
|
|
130
|
+
|
|
131
|
+
def log(msg: str):
|
|
132
|
+
if CONFIG["log_requests"]:
|
|
133
|
+
sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
|
|
134
|
+
sys.stderr.flush()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def load_cookie() -> tuple:
|
|
138
|
+
"""Load cookie from file. Returns (cookie_str, sapisid)."""
|
|
139
|
+
cookie_file = CONFIG.get("cookie_file")
|
|
140
|
+
if not cookie_file:
|
|
141
|
+
return "", None
|
|
142
|
+
if not os.path.exists(cookie_file):
|
|
143
|
+
return "", None
|
|
144
|
+
try:
|
|
145
|
+
with open(cookie_file, "r") as f:
|
|
146
|
+
content = f.read().strip()
|
|
147
|
+
if content.startswith("{"):
|
|
148
|
+
data = json.loads(content)
|
|
149
|
+
cookie_str = data.get("cookie", "")
|
|
150
|
+
sapisid = data.get("sapisid", "")
|
|
151
|
+
else:
|
|
152
|
+
cookie_str = content
|
|
153
|
+
pairs = dict(p.split("=", 1) for p in cookie_str.split("; ") if "=" in p)
|
|
154
|
+
sapisid = pairs.get("SAPISID", "")
|
|
155
|
+
return cookie_str, sapisid if sapisid else None
|
|
156
|
+
except Exception as e:
|
|
157
|
+
log(f"Cookie load error: {e}")
|
|
158
|
+
return "", None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def make_sapisidhash(sapisid: str) -> str:
|
|
162
|
+
ts = int(time.time())
|
|
163
|
+
h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
|
|
164
|
+
return f"SAPISIDHASH {ts}_{h}"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def account_prefix() -> str:
|
|
168
|
+
"""Return the Gemini account path prefix for non-default Google accounts."""
|
|
169
|
+
auth_user = CONFIG.get("auth_user")
|
|
170
|
+
if auth_user is None or auth_user == "":
|
|
171
|
+
return ""
|
|
172
|
+
return f"/u/{auth_user}"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def apply_chat_persistence_flags(inner: list) -> None:
|
|
176
|
+
"""Apply Gemini Web persistence flags to an outgoing request payload."""
|
|
177
|
+
if CONFIG.get("temporary_chats", False):
|
|
178
|
+
inner[41] = [1]
|
|
179
|
+
inner[45] = 1
|
|
180
|
+
else:
|
|
181
|
+
inner[41] = [2]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def fetch_latest_bl() -> Optional[str]:
|
|
185
|
+
"""Fetch the latest gemini_bl from gemini.google.com page."""
|
|
186
|
+
try:
|
|
187
|
+
req = urllib.request.Request(
|
|
188
|
+
"https://gemini.google.com/app",
|
|
189
|
+
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
|
|
190
|
+
ctx = ssl.create_default_context()
|
|
191
|
+
proxy = CONFIG.get("proxy")
|
|
192
|
+
if proxy:
|
|
193
|
+
opener = urllib.request.build_opener(
|
|
194
|
+
urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
|
|
195
|
+
urllib.request.HTTPSHandler(context=ctx))
|
|
196
|
+
resp = opener.open(req, timeout=15)
|
|
197
|
+
else:
|
|
198
|
+
resp = urllib.request.urlopen(req, context=ctx, timeout=15)
|
|
199
|
+
html = resp.read().decode("utf-8", errors="replace")
|
|
200
|
+
m = re.search(r'(boq_assistant-bard-web-server_\d+\.\d+_p\d+)', html)
|
|
201
|
+
if m:
|
|
202
|
+
return m.group(1)
|
|
203
|
+
except Exception as e:
|
|
204
|
+
log(f"BL auto-update fetch failed: {e}")
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def update_bl_if_needed() -> bool:
|
|
209
|
+
"""Attempt to fetch and update gemini_bl. Returns True if updated."""
|
|
210
|
+
new_bl = fetch_latest_bl()
|
|
211
|
+
if new_bl and new_bl != CONFIG["gemini_bl"]:
|
|
212
|
+
log(f"BL auto-updated: {CONFIG['gemini_bl']} -> {new_bl}")
|
|
213
|
+
CONFIG["gemini_bl"] = new_bl
|
|
214
|
+
return True
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def upload_images(images: list) -> list:
|
|
219
|
+
"""Upload parsed OpenAI image parts and return Gemini file references."""
|
|
220
|
+
if not images:
|
|
221
|
+
return None
|
|
222
|
+
from gemini_web2api.multimodal import detect_image_mime, fetch_image_bytes, upload_image
|
|
223
|
+
|
|
224
|
+
file_refs = []
|
|
225
|
+
for item in images:
|
|
226
|
+
if not (isinstance(item, tuple) and len(item) == 2):
|
|
227
|
+
continue
|
|
228
|
+
data, mime = item
|
|
229
|
+
if isinstance(data, str):
|
|
230
|
+
data = fetch_image_bytes(data)
|
|
231
|
+
mime = mime or "image/png"
|
|
232
|
+
if not data:
|
|
233
|
+
raise RuntimeError("image fetch failed")
|
|
234
|
+
mime = detect_image_mime(data, mime or "image/png")
|
|
235
|
+
try:
|
|
236
|
+
file_refs.append(upload_image(data, "image.png", mime or "image/png"))
|
|
237
|
+
except Exception as e:
|
|
238
|
+
raise RuntimeError(f"image upload failed: {e}") from e
|
|
239
|
+
return file_refs if file_refs else None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# ─── Gemini Protocol ─────────────────────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
def gemini_stream_generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None) -> str:
|
|
245
|
+
"""Send prompt to Gemini StreamGenerate with retry."""
|
|
246
|
+
inner = [None] * 80
|
|
247
|
+
if file_refs:
|
|
248
|
+
refs = [[None, None, ref] for ref in file_refs]
|
|
249
|
+
inner[0] = [prompt, 0, None, refs, None, None, 0]
|
|
250
|
+
else:
|
|
251
|
+
inner[0] = [prompt, 0, None, None, None, None, 0]
|
|
252
|
+
inner[1] = ["en"]
|
|
253
|
+
inner[2] = ["", "", "", None, None, None, None, None, None, ""]
|
|
254
|
+
inner[6] = [0]
|
|
255
|
+
inner[7] = 1
|
|
256
|
+
inner[10] = 1
|
|
257
|
+
inner[11] = 0
|
|
258
|
+
inner[17] = [[think_mode]]
|
|
259
|
+
inner[18] = 0
|
|
260
|
+
inner[27] = 1
|
|
261
|
+
inner[30] = [4]
|
|
262
|
+
apply_chat_persistence_flags(inner)
|
|
263
|
+
inner[53] = 0
|
|
264
|
+
inner[59] = str(uuid.uuid4())
|
|
265
|
+
inner[61] = []
|
|
266
|
+
inner[68] = 1
|
|
267
|
+
inner[79] = model_id
|
|
268
|
+
|
|
269
|
+
outer = [None, json.dumps(inner)]
|
|
270
|
+
params = {"f.req": json.dumps(outer)}
|
|
271
|
+
if CONFIG.get("xsrf_token"):
|
|
272
|
+
params["at"] = CONFIG["xsrf_token"]
|
|
273
|
+
body = urllib.parse.urlencode(params).encode()
|
|
274
|
+
reqid = int(time.time()) % 1000000
|
|
275
|
+
prefix = account_prefix()
|
|
276
|
+
url = (
|
|
277
|
+
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
|
|
278
|
+
"assistant.lamda.BardFrontendService/StreamGenerate"
|
|
279
|
+
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
|
|
280
|
+
)
|
|
281
|
+
headers = {
|
|
282
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
283
|
+
"Origin": "https://gemini.google.com",
|
|
284
|
+
"Referer": f"https://gemini.google.com{prefix}/app",
|
|
285
|
+
"X-Same-Domain": "1",
|
|
286
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
287
|
+
}
|
|
288
|
+
if prefix:
|
|
289
|
+
headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
|
|
290
|
+
|
|
291
|
+
cookie_str, sapisid = load_cookie()
|
|
292
|
+
if cookie_str:
|
|
293
|
+
headers["Cookie"] = cookie_str
|
|
294
|
+
if sapisid:
|
|
295
|
+
headers["Authorization"] = make_sapisidhash(sapisid)
|
|
296
|
+
|
|
297
|
+
last_err = None
|
|
298
|
+
for attempt in range(CONFIG["retry_attempts"]):
|
|
299
|
+
try:
|
|
300
|
+
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
|
|
301
|
+
ctx = ssl.create_default_context()
|
|
302
|
+
proxy = CONFIG.get("proxy")
|
|
303
|
+
if proxy:
|
|
304
|
+
opener = urllib.request.build_opener(
|
|
305
|
+
urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
|
|
306
|
+
urllib.request.HTTPSHandler(context=ctx)
|
|
307
|
+
)
|
|
308
|
+
resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
|
|
309
|
+
else:
|
|
310
|
+
resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
|
|
311
|
+
return resp.read().decode("utf-8", errors="replace")
|
|
312
|
+
except urllib.error.HTTPError as e:
|
|
313
|
+
if e.code == 405 and update_bl_if_needed():
|
|
314
|
+
reqid = int(time.time()) % 1000000
|
|
315
|
+
url = (
|
|
316
|
+
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
|
|
317
|
+
"assistant.lamda.BardFrontendService/StreamGenerate"
|
|
318
|
+
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
|
|
319
|
+
)
|
|
320
|
+
log("Retrying with updated BL...")
|
|
321
|
+
last_err = e
|
|
322
|
+
continue
|
|
323
|
+
last_err = e
|
|
324
|
+
if attempt < CONFIG["retry_attempts"] - 1:
|
|
325
|
+
log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
|
|
326
|
+
time.sleep(CONFIG["retry_delay_sec"])
|
|
327
|
+
except Exception as e:
|
|
328
|
+
last_err = e
|
|
329
|
+
if attempt < CONFIG["retry_attempts"] - 1:
|
|
330
|
+
log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
|
|
331
|
+
time.sleep(CONFIG["retry_delay_sec"])
|
|
332
|
+
raise last_err
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def gemini_stream_generate_iter(prompt: str, model_id: int, think_mode: int, file_refs: list = None):
|
|
336
|
+
"""Send prompt and yield incremental text deltas using httpx streaming."""
|
|
337
|
+
inner = [None] * 80
|
|
338
|
+
if file_refs:
|
|
339
|
+
refs = [[None, None, ref] for ref in file_refs]
|
|
340
|
+
inner[0] = [prompt, 0, None, refs, None, None, 0]
|
|
341
|
+
else:
|
|
342
|
+
inner[0] = [prompt, 0, None, None, None, None, 0]
|
|
343
|
+
inner[1] = ["en"]
|
|
344
|
+
inner[2] = ["", "", "", None, None, None, None, None, None, ""]
|
|
345
|
+
inner[6] = [0]
|
|
346
|
+
inner[7] = 1
|
|
347
|
+
inner[10] = 1
|
|
348
|
+
inner[11] = 0
|
|
349
|
+
inner[17] = [[think_mode]]
|
|
350
|
+
inner[18] = 0
|
|
351
|
+
inner[27] = 1
|
|
352
|
+
inner[30] = [4]
|
|
353
|
+
apply_chat_persistence_flags(inner)
|
|
354
|
+
inner[53] = 0
|
|
355
|
+
inner[59] = str(uuid.uuid4())
|
|
356
|
+
inner[61] = []
|
|
357
|
+
inner[68] = 1
|
|
358
|
+
inner[79] = model_id
|
|
359
|
+
|
|
360
|
+
outer = [None, json.dumps(inner)]
|
|
361
|
+
params = {"f.req": json.dumps(outer)}
|
|
362
|
+
if CONFIG.get("xsrf_token"):
|
|
363
|
+
params["at"] = CONFIG["xsrf_token"]
|
|
364
|
+
body = urllib.parse.urlencode(params)
|
|
365
|
+
reqid = int(time.time()) % 1000000
|
|
366
|
+
prefix = account_prefix()
|
|
367
|
+
url = (
|
|
368
|
+
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
|
|
369
|
+
"assistant.lamda.BardFrontendService/StreamGenerate"
|
|
370
|
+
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
|
|
371
|
+
)
|
|
372
|
+
headers = {
|
|
373
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
374
|
+
"Origin": "https://gemini.google.com",
|
|
375
|
+
"Referer": f"https://gemini.google.com{prefix}/app",
|
|
376
|
+
"X-Same-Domain": "1",
|
|
377
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
|
378
|
+
}
|
|
379
|
+
if prefix:
|
|
380
|
+
headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
|
|
381
|
+
cookie_str, sapisid = load_cookie()
|
|
382
|
+
if cookie_str:
|
|
383
|
+
headers["Cookie"] = cookie_str
|
|
384
|
+
if sapisid:
|
|
385
|
+
headers["Authorization"] = make_sapisidhash(sapisid)
|
|
386
|
+
|
|
387
|
+
proxy = CONFIG.get("proxy")
|
|
388
|
+
|
|
389
|
+
if not HAS_HTTPX:
|
|
390
|
+
# Fallback: non-streaming with urllib
|
|
391
|
+
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
|
|
392
|
+
text = extract_response_text(raw)
|
|
393
|
+
if text:
|
|
394
|
+
yield text
|
|
395
|
+
return
|
|
396
|
+
|
|
397
|
+
prev_text = ""
|
|
398
|
+
transport = httpx.HTTPTransport(proxy=proxy) if proxy else None
|
|
399
|
+
with httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True) as client:
|
|
400
|
+
try:
|
|
401
|
+
with client.stream("POST", url, content=body, headers=headers) as resp:
|
|
402
|
+
resp.raise_for_status()
|
|
403
|
+
buf = ""
|
|
404
|
+
for chunk in resp.iter_text():
|
|
405
|
+
buf += chunk
|
|
406
|
+
if "BardErrorInfo" in buf:
|
|
407
|
+
import re as _re
|
|
408
|
+
m = _re.search(r'BardErrorInfo\s*\[(\d+)\]', buf)
|
|
409
|
+
if m:
|
|
410
|
+
raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{m.group(1)}]")
|
|
411
|
+
while "\n" in buf:
|
|
412
|
+
line, buf = buf.split("\n", 1)
|
|
413
|
+
if '"wrb.fr"' not in line or len(line) < 200:
|
|
414
|
+
continue
|
|
415
|
+
try:
|
|
416
|
+
arr = json.loads(line)
|
|
417
|
+
inner_str = arr[0][2]
|
|
418
|
+
if not inner_str or len(inner_str) < 50:
|
|
419
|
+
continue
|
|
420
|
+
inner2 = json.loads(inner_str)
|
|
421
|
+
if isinstance(inner2, list) and len(inner2) > 4 and inner2[4]:
|
|
422
|
+
for part in inner2[4]:
|
|
423
|
+
if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
|
|
424
|
+
for t in part[1]:
|
|
425
|
+
if isinstance(t, str) and len(t) > len(prev_text):
|
|
426
|
+
delta = t[len(prev_text):]
|
|
427
|
+
delta = clean_gemini_text(delta, strip=False)
|
|
428
|
+
if delta:
|
|
429
|
+
yield delta
|
|
430
|
+
prev_text = t
|
|
431
|
+
except (json.JSONDecodeError, IndexError, TypeError):
|
|
432
|
+
pass
|
|
433
|
+
except Exception as e:
|
|
434
|
+
if HAS_HTTPX and hasattr(e, 'response') and getattr(e.response, 'status_code', 0) == 405:
|
|
435
|
+
if update_bl_if_needed():
|
|
436
|
+
log("BL updated, falling back to non-streaming for this request")
|
|
437
|
+
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
|
|
438
|
+
text = extract_response_text(raw)
|
|
439
|
+
if text:
|
|
440
|
+
yield text
|
|
441
|
+
return
|
|
442
|
+
raise
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def clean_gemini_text(text: str, strip: bool = True) -> str:
|
|
446
|
+
"""Remove internal code execution artifacts."""
|
|
447
|
+
text = re.sub(
|
|
448
|
+
r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
|
|
449
|
+
'', text, flags=re.DOTALL
|
|
450
|
+
)
|
|
451
|
+
return text.strip() if strip else text
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def extract_response_text(raw: str) -> str:
|
|
455
|
+
"""Parse StreamGenerate response to extract final text."""
|
|
456
|
+
import re as _re
|
|
457
|
+
bard_err = _re.search(r'BardErrorInfo\s*\[(\d+)\]', raw)
|
|
458
|
+
if bard_err:
|
|
459
|
+
raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{bard_err.group(1)}]")
|
|
460
|
+
texts = []
|
|
461
|
+
for line in raw.split("\n"):
|
|
462
|
+
if '"wrb.fr"' not in line or len(line) < 200:
|
|
463
|
+
continue
|
|
464
|
+
try:
|
|
465
|
+
arr = json.loads(line)
|
|
466
|
+
inner_str = arr[0][2]
|
|
467
|
+
if not inner_str or len(inner_str) < 50:
|
|
468
|
+
continue
|
|
469
|
+
inner = json.loads(inner_str)
|
|
470
|
+
if isinstance(inner, list) and len(inner) > 4 and inner[4]:
|
|
471
|
+
for part in inner[4]:
|
|
472
|
+
if isinstance(part, list) and len(part) > 1 and part[1]:
|
|
473
|
+
if isinstance(part[1], list):
|
|
474
|
+
for t in part[1]:
|
|
475
|
+
if isinstance(t, str) and len(t) > 0:
|
|
476
|
+
texts.append(t)
|
|
477
|
+
except (json.JSONDecodeError, IndexError, TypeError):
|
|
478
|
+
pass
|
|
479
|
+
text = ""
|
|
480
|
+
for t in reversed(texts):
|
|
481
|
+
if t.strip():
|
|
482
|
+
text = t
|
|
483
|
+
break
|
|
484
|
+
return clean_gemini_text(text)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
# ─── OpenAI Format Helpers ───────────────────────────────────────────────────
|
|
488
|
+
|
|
489
|
+
PROMPT_MAX_BYTES = 60000
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def decode_data_url(url: str):
|
|
493
|
+
match = re.match(r"^data:([^;,]+)?(;base64)?,(.*)$", url, re.DOTALL)
|
|
494
|
+
if not match:
|
|
495
|
+
return None
|
|
496
|
+
mime = match.group(1) or "image/png"
|
|
497
|
+
is_base64 = bool(match.group(2))
|
|
498
|
+
data = match.group(3)
|
|
499
|
+
try:
|
|
500
|
+
if is_base64:
|
|
501
|
+
return base64.b64decode(data, validate=True), mime
|
|
502
|
+
return urllib.parse.unquote_to_bytes(data), mime
|
|
503
|
+
except (ValueError, TypeError, binascii.Error):
|
|
504
|
+
return None
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def image_from_url(url: str, mime: str = None):
|
|
508
|
+
if not isinstance(url, str) or not url:
|
|
509
|
+
return None
|
|
510
|
+
if url.startswith("data:"):
|
|
511
|
+
return decode_data_url(url)
|
|
512
|
+
return url, mime or "image/png"
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def image_from_part(part: dict):
|
|
516
|
+
part_type = part.get("type")
|
|
517
|
+
if part_type == "image_url":
|
|
518
|
+
image_url = part.get("image_url", {})
|
|
519
|
+
if isinstance(image_url, dict):
|
|
520
|
+
return image_from_url(image_url.get("url"), image_url.get("mime_type"))
|
|
521
|
+
return image_from_url(image_url)
|
|
522
|
+
if part_type in ("input_image", "image"):
|
|
523
|
+
image_url = part.get("image_url") or part.get("url")
|
|
524
|
+
if isinstance(image_url, dict):
|
|
525
|
+
return image_from_url(image_url.get("url"), image_url.get("mime_type"))
|
|
526
|
+
if image_url:
|
|
527
|
+
return image_from_url(image_url, part.get("mime_type"))
|
|
528
|
+
image_data = part.get("data") or part.get("base64")
|
|
529
|
+
if isinstance(image_data, str):
|
|
530
|
+
mime = part.get("mime_type") or part.get("media_type") or "image/png"
|
|
531
|
+
if image_data.startswith("data:"):
|
|
532
|
+
return decode_data_url(image_data)
|
|
533
|
+
try:
|
|
534
|
+
return base64.b64decode(image_data, validate=True), mime
|
|
535
|
+
except (ValueError, TypeError, binascii.Error):
|
|
536
|
+
return None
|
|
537
|
+
return None
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def messages_to_prompt(messages: list, tools: list = None) -> tuple:
|
|
541
|
+
"""Convert OpenAI messages to (prompt_str, images_list)."""
|
|
542
|
+
parts = []
|
|
543
|
+
images = []
|
|
544
|
+
if tools:
|
|
545
|
+
tool_defs = []
|
|
546
|
+
for tool in tools:
|
|
547
|
+
fn = tool.get("function", tool) if tool.get("type") == "function" else tool
|
|
548
|
+
tool_defs.append({
|
|
549
|
+
"name": fn.get("name", tool.get("name", "")),
|
|
550
|
+
"description": fn.get("description", tool.get("description", "")),
|
|
551
|
+
"parameters": fn.get("parameters", tool.get("parameters", {})),
|
|
552
|
+
})
|
|
553
|
+
if tool_defs:
|
|
554
|
+
tools_json = json.dumps(tool_defs, indent=2)
|
|
555
|
+
if len(tools_json) > PROMPT_MAX_BYTES // 2:
|
|
556
|
+
slim_defs = [{"name": t["name"], "description": t["description"]} for t in tool_defs]
|
|
557
|
+
tools_json = json.dumps(slim_defs, indent=2)
|
|
558
|
+
log(f"Tools block too large ({len(tool_defs)} tools), stripped parameters")
|
|
559
|
+
parts.append(
|
|
560
|
+
"[System instruction]: You have access to tools. "
|
|
561
|
+
"To call a tool, respond with:\n"
|
|
562
|
+
'```tool_call\n{"name": "func_name", "arguments": {...}}\n```\n'
|
|
563
|
+
"Only use tool_call blocks when needed.\n\n"
|
|
564
|
+
f"Available tools:\n{tools_json}"
|
|
565
|
+
)
|
|
566
|
+
for msg in messages:
|
|
567
|
+
role = msg.get("role", "user")
|
|
568
|
+
content = msg.get("content", "")
|
|
569
|
+
if isinstance(content, list):
|
|
570
|
+
text_parts = []
|
|
571
|
+
for c in content:
|
|
572
|
+
if c.get("type") in ("text", "input_text", "output_text"):
|
|
573
|
+
text_parts.append(c.get("text", ""))
|
|
574
|
+
else:
|
|
575
|
+
image = image_from_part(c)
|
|
576
|
+
if image:
|
|
577
|
+
images.append(image)
|
|
578
|
+
text_parts.append("[Image attached]")
|
|
579
|
+
content = " ".join(text_parts)
|
|
580
|
+
if role == "system":
|
|
581
|
+
parts.append(f"[System instruction]: {content}")
|
|
582
|
+
elif role == "assistant":
|
|
583
|
+
if msg.get("tool_calls"):
|
|
584
|
+
tc_strs = []
|
|
585
|
+
for tc in msg["tool_calls"]:
|
|
586
|
+
fn = tc.get("function", {})
|
|
587
|
+
tc_strs.append(
|
|
588
|
+
f'```tool_call\n{{"name": "{fn.get("name")}", '
|
|
589
|
+
f'"arguments": {fn.get("arguments", "{}")}}}\n```'
|
|
590
|
+
)
|
|
591
|
+
parts.append(f"[Assistant]: {content or ''}\n" + "\n".join(tc_strs))
|
|
592
|
+
else:
|
|
593
|
+
parts.append(f"[Assistant]: {content}")
|
|
594
|
+
elif role == "tool":
|
|
595
|
+
parts.append(f"[Tool result for {msg.get('name', '')}]: {content}")
|
|
596
|
+
else:
|
|
597
|
+
parts.append(content if content else "")
|
|
598
|
+
return "\n\n".join(p for p in parts if p), images
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def google_contents_to_prompt(req: dict) -> tuple:
|
|
602
|
+
"""Convert Google API contents to (prompt_str, images_list)."""
|
|
603
|
+
parts = []
|
|
604
|
+
images = []
|
|
605
|
+
|
|
606
|
+
sys_inst = req.get("systemInstruction")
|
|
607
|
+
if sys_inst:
|
|
608
|
+
sys_text = " ".join(
|
|
609
|
+
part.get("text", "") for part in sys_inst.get("parts", []) if part.get("text")
|
|
610
|
+
)
|
|
611
|
+
if sys_text:
|
|
612
|
+
parts.append(f"[System instruction]: {sys_text}")
|
|
613
|
+
|
|
614
|
+
for content in req.get("contents", []):
|
|
615
|
+
role = content.get("role", "user")
|
|
616
|
+
text_parts = []
|
|
617
|
+
for part in content.get("parts", []):
|
|
618
|
+
if part.get("text"):
|
|
619
|
+
text_parts.append(part["text"])
|
|
620
|
+
elif part.get("inlineData"):
|
|
621
|
+
data = part["inlineData"]
|
|
622
|
+
try:
|
|
623
|
+
images.append((
|
|
624
|
+
base64.b64decode(data["data"], validate=True),
|
|
625
|
+
data.get("mimeType", "image/png"),
|
|
626
|
+
))
|
|
627
|
+
text_parts.append("[Image attached]")
|
|
628
|
+
except (KeyError, ValueError, TypeError, binascii.Error):
|
|
629
|
+
pass
|
|
630
|
+
text = " ".join(text_parts)
|
|
631
|
+
if role == "model":
|
|
632
|
+
parts.append(f"[Assistant]: {text}")
|
|
633
|
+
else:
|
|
634
|
+
parts.append(text)
|
|
635
|
+
|
|
636
|
+
return "\n\n".join(part for part in parts if part), images
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def parse_tool_calls(text: str) -> tuple:
|
|
640
|
+
"""Extract tool_call blocks. Returns (clean_text, tool_calls_list)."""
|
|
641
|
+
tool_calls = []
|
|
642
|
+
pattern = r'```tool_call\s*\n(.*?)\n```'
|
|
643
|
+
for match in re.findall(pattern, text, re.DOTALL):
|
|
644
|
+
try:
|
|
645
|
+
data = json.loads(match.strip())
|
|
646
|
+
tool_calls.append({
|
|
647
|
+
"id": f"call_{uuid.uuid4().hex[:8]}",
|
|
648
|
+
"type": "function",
|
|
649
|
+
"function": {
|
|
650
|
+
"name": data["name"],
|
|
651
|
+
"arguments": json.dumps(data.get("arguments", {}), ensure_ascii=False),
|
|
652
|
+
},
|
|
653
|
+
})
|
|
654
|
+
except (json.JSONDecodeError, KeyError):
|
|
655
|
+
pass
|
|
656
|
+
clean = re.sub(pattern, '', text, flags=re.DOTALL).strip()
|
|
657
|
+
return clean, tool_calls
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
# ─── HTTP Handler ────────────────────────────────────────────────────────────
|
|
661
|
+
|
|
662
|
+
class GeminiHandler(BaseHTTPRequestHandler):
|
|
663
|
+
def log_message(self, fmt, *args):
|
|
664
|
+
client_ip = self.client_address[0] if self.client_address else "-"
|
|
665
|
+
log(f"{client_ip} {fmt % args}")
|
|
666
|
+
|
|
667
|
+
def send_json(self, data, status=200):
|
|
668
|
+
body = json.dumps(data, ensure_ascii=False).encode()
|
|
669
|
+
self.send_response(status)
|
|
670
|
+
self.send_header("Content-Type", "application/json")
|
|
671
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
672
|
+
self.send_header("Content-Length", str(len(body)))
|
|
673
|
+
self.end_headers()
|
|
674
|
+
self.wfile.write(body)
|
|
675
|
+
|
|
676
|
+
def _authorized(self):
|
|
677
|
+
keys = CONFIG.get("api_keys") or []
|
|
678
|
+
if not keys:
|
|
679
|
+
return True
|
|
680
|
+
# Authorization: Bearer <key>
|
|
681
|
+
auth = self.headers.get("Authorization", "")
|
|
682
|
+
if auth.startswith("Bearer ") and auth[7:] in keys:
|
|
683
|
+
return True
|
|
684
|
+
# header keys (OpenAI x-api-key / Google x-goog-api-key)
|
|
685
|
+
for h in ("x-api-key", "x-goog-api-key"):
|
|
686
|
+
if self.headers.get(h, "") in keys:
|
|
687
|
+
return True
|
|
688
|
+
# query param ?key= (Gemini CLI native style)
|
|
689
|
+
if "?" in self.path:
|
|
690
|
+
for pair in self.path.split("?", 1)[1].split("&"):
|
|
691
|
+
if pair.startswith("key=") and pair[4:] in keys:
|
|
692
|
+
return True
|
|
693
|
+
return False
|
|
694
|
+
|
|
695
|
+
def do_OPTIONS(self):
|
|
696
|
+
self.send_response(204)
|
|
697
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
698
|
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
|
699
|
+
self.send_header("Access-Control-Allow-Headers", "*")
|
|
700
|
+
self.end_headers()
|
|
701
|
+
|
|
702
|
+
def do_GET(self):
|
|
703
|
+
try:
|
|
704
|
+
if self.path.startswith("/v1") and not self._authorized():
|
|
705
|
+
self.send_json({"error": {"message": "invalid api key"}}, 401)
|
|
706
|
+
return
|
|
707
|
+
if self.path == "/v1/models":
|
|
708
|
+
self.send_json({"object": "list", "data": [
|
|
709
|
+
{"id": n, "object": "model", "created": 1700000000,
|
|
710
|
+
"owned_by": "google", "description": c["desc"]}
|
|
711
|
+
for n, c in MODELS.items()
|
|
712
|
+
]})
|
|
713
|
+
elif self.path.startswith("/v1beta/models"):
|
|
714
|
+
self._handle_google_models_list()
|
|
715
|
+
elif self.path == "/":
|
|
716
|
+
self.send_json({"status": "ok", "version": __version__,
|
|
717
|
+
"models": list(MODELS.keys())})
|
|
718
|
+
else:
|
|
719
|
+
self.send_json({"error": "not found"}, 404)
|
|
720
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
721
|
+
pass
|
|
722
|
+
except Exception as e:
|
|
723
|
+
log(f"GET error: {e}")
|
|
724
|
+
|
|
725
|
+
def do_POST(self):
|
|
726
|
+
try:
|
|
727
|
+
if self.path.startswith("/v1") and not self._authorized():
|
|
728
|
+
self.send_json({"error": {"message": "invalid api key"}}, 401)
|
|
729
|
+
return
|
|
730
|
+
body = self._read_request_body()
|
|
731
|
+
if self.path == "/v1/chat/completions":
|
|
732
|
+
self.handle_chat(body)
|
|
733
|
+
elif self.path == "/v1/responses":
|
|
734
|
+
self.handle_responses(body)
|
|
735
|
+
elif ":streamGenerateContent" in self.path:
|
|
736
|
+
self._handle_google_generate(body, stream=True)
|
|
737
|
+
elif ":generateContent" in self.path:
|
|
738
|
+
self._handle_google_generate(body, stream=False)
|
|
739
|
+
else:
|
|
740
|
+
self.send_json({"error": "not found"}, 404)
|
|
741
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
742
|
+
pass
|
|
743
|
+
except Exception as e:
|
|
744
|
+
log(f"POST error: {e}")
|
|
745
|
+
try:
|
|
746
|
+
self.send_json({"error": {"message": str(e)}}, 500)
|
|
747
|
+
except:
|
|
748
|
+
pass
|
|
749
|
+
|
|
750
|
+
def _read_request_body(self) -> bytes:
|
|
751
|
+
transfer_encoding = self.headers.get("Transfer-Encoding", "")
|
|
752
|
+
if "chunked" in transfer_encoding.lower():
|
|
753
|
+
chunks = []
|
|
754
|
+
while True:
|
|
755
|
+
size_line = self.rfile.readline()
|
|
756
|
+
if not size_line:
|
|
757
|
+
break
|
|
758
|
+
size_text = size_line.split(b";", 1)[0].strip()
|
|
759
|
+
try:
|
|
760
|
+
size = int(size_text, 16)
|
|
761
|
+
except ValueError:
|
|
762
|
+
raise ValueError("invalid chunked request body")
|
|
763
|
+
if size == 0:
|
|
764
|
+
while True:
|
|
765
|
+
trailer = self.rfile.readline()
|
|
766
|
+
if trailer in (b"\r\n", b"\n", b""):
|
|
767
|
+
break
|
|
768
|
+
break
|
|
769
|
+
chunks.append(self.rfile.read(size))
|
|
770
|
+
self.rfile.read(2)
|
|
771
|
+
return b"".join(chunks)
|
|
772
|
+
|
|
773
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
774
|
+
return self.rfile.read(length) if length else b""
|
|
775
|
+
|
|
776
|
+
def _resolve_model(self, model_name):
|
|
777
|
+
think_override = None
|
|
778
|
+
if "@think=" in model_name:
|
|
779
|
+
model_name, think_str = model_name.rsplit("@think=", 1)
|
|
780
|
+
think_override = int(think_str)
|
|
781
|
+
cfg = MODELS.get(model_name)
|
|
782
|
+
if not cfg:
|
|
783
|
+
return None, None, None, f"Unknown model: {model_name}"
|
|
784
|
+
return model_name, cfg["mode"], (think_override if think_override is not None else cfg["think"]), None
|
|
785
|
+
|
|
786
|
+
def _call_gemini(self, prompt, model_id, think_mode, tools, file_refs=None):
|
|
787
|
+
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
|
|
788
|
+
text = extract_response_text(raw)
|
|
789
|
+
tool_calls = None
|
|
790
|
+
if tools and text:
|
|
791
|
+
text, tool_calls = parse_tool_calls(text)
|
|
792
|
+
return text or "", tool_calls
|
|
793
|
+
|
|
794
|
+
def handle_chat(self, body: bytes):
|
|
795
|
+
req = json.loads(body)
|
|
796
|
+
model_name, model_id, think_mode, err = self._resolve_model(
|
|
797
|
+
req.get("model", CONFIG["default_model"]))
|
|
798
|
+
if err:
|
|
799
|
+
self.send_json({"error": {"message": err}}, 400)
|
|
800
|
+
return
|
|
801
|
+
|
|
802
|
+
tools = req.get("tools")
|
|
803
|
+
prompt, images = messages_to_prompt(req.get("messages", []), tools)
|
|
804
|
+
if not prompt.strip():
|
|
805
|
+
self.send_json({"error": {"message": "empty prompt"}}, 400)
|
|
806
|
+
return
|
|
807
|
+
|
|
808
|
+
stream = req.get("stream", False)
|
|
809
|
+
cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
|
|
810
|
+
try:
|
|
811
|
+
file_refs = upload_images(images)
|
|
812
|
+
except RuntimeError as e:
|
|
813
|
+
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
|
|
814
|
+
return
|
|
815
|
+
|
|
816
|
+
if stream and not tools:
|
|
817
|
+
# True streaming: forward chunks as they arrive
|
|
818
|
+
try:
|
|
819
|
+
self.send_response(200)
|
|
820
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
821
|
+
self.send_header("Cache-Control", "no-cache")
|
|
822
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
823
|
+
self.end_headers()
|
|
824
|
+
first_chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
|
|
825
|
+
"model": model_name, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]}
|
|
826
|
+
self.wfile.write(f"data: {json.dumps(first_chunk)}\n\n".encode())
|
|
827
|
+
for delta_text in gemini_stream_generate_iter(prompt, model_id, think_mode, file_refs):
|
|
828
|
+
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
|
|
829
|
+
"model": model_name, "choices": [{"index": 0, "delta": {"content": delta_text}, "finish_reason": None}]}
|
|
830
|
+
self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
|
|
831
|
+
self.wfile.flush()
|
|
832
|
+
# Final chunk
|
|
833
|
+
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
|
|
834
|
+
"model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
|
|
835
|
+
self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
|
|
836
|
+
self.wfile.write(b"data: [DONE]\n\n")
|
|
837
|
+
self.wfile.flush()
|
|
838
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
839
|
+
pass
|
|
840
|
+
except Exception as e:
|
|
841
|
+
log(f"Stream error: {e}")
|
|
842
|
+
return
|
|
843
|
+
|
|
844
|
+
# Non-streaming (or tool calling which needs full response)
|
|
845
|
+
try:
|
|
846
|
+
text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools, file_refs)
|
|
847
|
+
except Exception as e:
|
|
848
|
+
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
|
|
849
|
+
return
|
|
850
|
+
|
|
851
|
+
msg = {"role": "assistant", "content": text or None}
|
|
852
|
+
if tool_calls:
|
|
853
|
+
msg["tool_calls"] = tool_calls
|
|
854
|
+
finish = "tool_calls" if tool_calls else "stop"
|
|
855
|
+
|
|
856
|
+
if stream:
|
|
857
|
+
# Stream mode with tools: send as single chunk (need full parse for tool_calls)
|
|
858
|
+
self.send_response(200)
|
|
859
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
860
|
+
self.send_header("Cache-Control", "no-cache")
|
|
861
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
862
|
+
self.end_headers()
|
|
863
|
+
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
|
|
864
|
+
"model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
|
|
865
|
+
self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
|
|
866
|
+
self.wfile.write(b"data: [DONE]\n\n")
|
|
867
|
+
self.wfile.flush()
|
|
868
|
+
else:
|
|
869
|
+
self.send_json({
|
|
870
|
+
"id": cid, "object": "chat.completion", "created": int(time.time()),
|
|
871
|
+
"model": model_name,
|
|
872
|
+
"choices": [{"index": 0, "message": msg, "finish_reason": finish}],
|
|
873
|
+
"usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text)//4,
|
|
874
|
+
"total_tokens": (len(prompt)+len(text))//4},
|
|
875
|
+
})
|
|
876
|
+
|
|
877
|
+
def handle_responses(self, body: bytes):
|
|
878
|
+
"""OpenAI Responses API for Codex CLI compatibility."""
|
|
879
|
+
req = json.loads(body)
|
|
880
|
+
model_name, model_id, think_mode, err = self._resolve_model(
|
|
881
|
+
req.get("model", CONFIG["default_model"]))
|
|
882
|
+
if err:
|
|
883
|
+
self.send_json({"error": {"message": err}}, 400)
|
|
884
|
+
return
|
|
885
|
+
|
|
886
|
+
input_items = req.get("input", [])
|
|
887
|
+
tools = req.get("tools")
|
|
888
|
+
|
|
889
|
+
messages = []
|
|
890
|
+
if req.get("instructions"):
|
|
891
|
+
messages.append({"role": "system", "content": req["instructions"]})
|
|
892
|
+
if isinstance(input_items, str):
|
|
893
|
+
messages.append({"role": "user", "content": input_items})
|
|
894
|
+
elif isinstance(input_items, list):
|
|
895
|
+
for item in input_items:
|
|
896
|
+
if isinstance(item, str):
|
|
897
|
+
messages.append({"role": "user", "content": item})
|
|
898
|
+
elif isinstance(item, dict):
|
|
899
|
+
if item.get("type") == "function_call_output":
|
|
900
|
+
messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
|
|
901
|
+
"name": item.get("name", ""), "content": item.get("output", "")})
|
|
902
|
+
elif item.get("type") in ("input_text", "input_image", "image"):
|
|
903
|
+
messages.append({"role": "user", "content": [item]})
|
|
904
|
+
elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
|
|
905
|
+
cp = item.get("content", [])
|
|
906
|
+
text_acc, tc_list = "", []
|
|
907
|
+
if isinstance(cp, list):
|
|
908
|
+
for c in cp:
|
|
909
|
+
if isinstance(c, dict):
|
|
910
|
+
if c.get("type") == "output_text": text_acc += c.get("text", "")
|
|
911
|
+
elif c.get("type") == "function_call": tc_list.append(c)
|
|
912
|
+
elif isinstance(cp, str):
|
|
913
|
+
text_acc = cp
|
|
914
|
+
m = {"role": "assistant", "content": text_acc or None}
|
|
915
|
+
if tc_list:
|
|
916
|
+
m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
|
|
917
|
+
"function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
|
|
918
|
+
for i, tc in enumerate(tc_list)]
|
|
919
|
+
messages.append(m)
|
|
920
|
+
else:
|
|
921
|
+
role = item.get("role", "user")
|
|
922
|
+
messages.append({"role": role, "content": item.get("content", "")})
|
|
923
|
+
|
|
924
|
+
if tools:
|
|
925
|
+
tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
|
|
926
|
+
if t.get("type") == "function" and "function" not in t else t for t in tools]
|
|
927
|
+
|
|
928
|
+
prompt, images = messages_to_prompt(messages, tools)
|
|
929
|
+
if not prompt.strip():
|
|
930
|
+
self.send_json({"error": {"message": "empty input"}}, 400)
|
|
931
|
+
return
|
|
932
|
+
|
|
933
|
+
try:
|
|
934
|
+
file_refs = upload_images(images)
|
|
935
|
+
text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools, file_refs)
|
|
936
|
+
except Exception as e:
|
|
937
|
+
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
|
|
938
|
+
return
|
|
939
|
+
|
|
940
|
+
rid = f"resp_{uuid.uuid4().hex[:16]}"
|
|
941
|
+
mid = f"msg_{uuid.uuid4().hex[:12]}"
|
|
942
|
+
output = []
|
|
943
|
+
if tool_calls:
|
|
944
|
+
for tc in tool_calls:
|
|
945
|
+
output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
|
|
946
|
+
"name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
|
|
947
|
+
if text or not tool_calls:
|
|
948
|
+
output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
|
|
949
|
+
"content": [{"type": "output_text", "text": text or "", "annotations": []}]})
|
|
950
|
+
|
|
951
|
+
if req.get("stream"):
|
|
952
|
+
self.send_response(200)
|
|
953
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
954
|
+
self.send_header("Cache-Control", "no-cache")
|
|
955
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
956
|
+
self.end_headers()
|
|
957
|
+
seq = [0]
|
|
958
|
+
|
|
959
|
+
def emit(ev_type, **fields):
|
|
960
|
+
seq[0] += 1
|
|
961
|
+
ev = {"type": ev_type, "sequence_number": seq[0], **fields}
|
|
962
|
+
self.wfile.write(f"event: {ev_type}\ndata: {json.dumps(ev)}\n\n".encode())
|
|
963
|
+
|
|
964
|
+
usage = {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}
|
|
965
|
+
base_resp = {"id": rid, "object": "response", "created_at": int(time.time()), "model": model_name}
|
|
966
|
+
emit("response.created", response={**base_resp, "status": "in_progress", "output": [], "usage": None})
|
|
967
|
+
emit("response.in_progress", response={**base_resp, "status": "in_progress", "output": [], "usage": None})
|
|
968
|
+
for oi, item in enumerate(output):
|
|
969
|
+
if item["type"] == "function_call":
|
|
970
|
+
pending = {"type": "function_call", "id": item["id"], "call_id": item["call_id"],
|
|
971
|
+
"name": item["name"], "arguments": "", "status": "in_progress"}
|
|
972
|
+
emit("response.output_item.added", output_index=oi, item=pending)
|
|
973
|
+
emit("response.function_call_arguments.delta", item_id=item["id"], output_index=oi, delta=item["arguments"])
|
|
974
|
+
emit("response.function_call_arguments.done", item_id=item["id"], output_index=oi, arguments=item["arguments"])
|
|
975
|
+
emit("response.output_item.done", output_index=oi, item=item)
|
|
976
|
+
elif item["type"] == "message":
|
|
977
|
+
pending = {"type": "message", "id": item["id"], "role": "assistant", "status": "in_progress", "content": []}
|
|
978
|
+
emit("response.output_item.added", output_index=oi, item=pending)
|
|
979
|
+
for ci, cp in enumerate(item["content"]):
|
|
980
|
+
emit("response.content_part.added", item_id=item["id"], output_index=oi, content_index=ci,
|
|
981
|
+
part={"type": "output_text", "text": "", "annotations": []})
|
|
982
|
+
emit("response.output_text.delta", item_id=item["id"], output_index=oi, content_index=ci, delta=cp["text"])
|
|
983
|
+
emit("response.output_text.done", item_id=item["id"], output_index=oi, content_index=ci, text=cp["text"])
|
|
984
|
+
emit("response.content_part.done", item_id=item["id"], output_index=oi, content_index=ci, part=cp)
|
|
985
|
+
emit("response.output_item.done", output_index=oi, item=item)
|
|
986
|
+
emit("response.completed", response={**base_resp, "status": "completed", "output": output, "usage": usage})
|
|
987
|
+
self.wfile.flush()
|
|
988
|
+
else:
|
|
989
|
+
self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
|
|
990
|
+
"model": model_name, "output": output,
|
|
991
|
+
"usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}})
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
# ─── Google Native API (Gemini CLI compatible) ────────────────────────────
|
|
995
|
+
|
|
996
|
+
def _parse_google_model_from_path(self):
|
|
997
|
+
"""Extract model name from /v1beta/models/{model}:method path."""
|
|
998
|
+
m = re.match(r'/v1beta/models/([^:?]+)', self.path)
|
|
999
|
+
if m:
|
|
1000
|
+
return m.group(1)
|
|
1001
|
+
return None
|
|
1002
|
+
|
|
1003
|
+
def _handle_google_models_list(self):
|
|
1004
|
+
"""GET /v1beta/models — Google AI format model list."""
|
|
1005
|
+
models = []
|
|
1006
|
+
for name, cfg in MODELS.items():
|
|
1007
|
+
models.append({
|
|
1008
|
+
"name": f"models/{name}",
|
|
1009
|
+
"displayName": name,
|
|
1010
|
+
"description": cfg["desc"],
|
|
1011
|
+
"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],
|
|
1012
|
+
})
|
|
1013
|
+
self.send_json({"models": models})
|
|
1014
|
+
|
|
1015
|
+
def _handle_google_generate(self, body: bytes, stream: bool):
|
|
1016
|
+
"""Handle Google native generateContent / streamGenerateContent."""
|
|
1017
|
+
req = json.loads(body)
|
|
1018
|
+
model_name = self._parse_google_model_from_path()
|
|
1019
|
+
if not model_name:
|
|
1020
|
+
self.send_json({"error": {"message": "model not specified in path"}}, 400)
|
|
1021
|
+
return
|
|
1022
|
+
|
|
1023
|
+
model_name, model_id, think_mode, err = self._resolve_model(model_name)
|
|
1024
|
+
if err:
|
|
1025
|
+
self.send_json({"error": {"message": err}}, 400)
|
|
1026
|
+
return
|
|
1027
|
+
|
|
1028
|
+
prompt, images = google_contents_to_prompt(req)
|
|
1029
|
+
if not prompt.strip():
|
|
1030
|
+
self.send_json({"error": {"message": "empty content"}}, 400)
|
|
1031
|
+
return
|
|
1032
|
+
|
|
1033
|
+
try:
|
|
1034
|
+
file_refs = upload_images(images)
|
|
1035
|
+
text, _ = self._call_gemini(prompt, model_id, think_mode, None, file_refs)
|
|
1036
|
+
except Exception as e:
|
|
1037
|
+
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
|
|
1038
|
+
return
|
|
1039
|
+
|
|
1040
|
+
candidate = {
|
|
1041
|
+
"content": {"parts": [{"text": text or ""}], "role": "model"},
|
|
1042
|
+
"finishReason": "STOP",
|
|
1043
|
+
"index": 0,
|
|
1044
|
+
}
|
|
1045
|
+
usage = {
|
|
1046
|
+
"promptTokenCount": len(prompt) // 4,
|
|
1047
|
+
"candidatesTokenCount": len(text) // 4,
|
|
1048
|
+
"totalTokenCount": (len(prompt) + len(text)) // 4,
|
|
1049
|
+
}
|
|
1050
|
+
response_obj = {
|
|
1051
|
+
"candidates": [candidate],
|
|
1052
|
+
"usageMetadata": usage,
|
|
1053
|
+
"modelVersion": model_name,
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
if stream:
|
|
1057
|
+
self.send_response(200)
|
|
1058
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
1059
|
+
self.send_header("Cache-Control", "no-cache")
|
|
1060
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
1061
|
+
self.end_headers()
|
|
1062
|
+
self.wfile.write(f"data: {json.dumps(response_obj)}\n\n".encode())
|
|
1063
|
+
self.wfile.flush()
|
|
1064
|
+
else:
|
|
1065
|
+
self.send_json(response_obj)
|
|
1066
|
+
|
|
1067
|
+
|
|
1068
|
+
# ─── Main ────────────────────────────────────────────────────────────────────
|
|
1069
|
+
|
|
1070
|
+
def load_config(path: str):
|
|
1071
|
+
if path and os.path.exists(path):
|
|
1072
|
+
with open(path) as f:
|
|
1073
|
+
CONFIG.update(json.load(f))
|
|
1074
|
+
log(f"Config loaded: {path}")
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def main():
|
|
1078
|
+
parser = argparse.ArgumentParser(description="Gemini Web to OpenAI API")
|
|
1079
|
+
parser.add_argument("--port", type=int, default=None)
|
|
1080
|
+
parser.add_argument("--config", type=str, default=None)
|
|
1081
|
+
parser.add_argument("--cookie-file", type=str, default=None, help="Path to cookie file")
|
|
1082
|
+
parser.add_argument("--proxy", type=str, default=None, help="HTTP proxy, e.g. http://127.0.0.1:7890")
|
|
1083
|
+
parser.add_argument("--version", action="version", version=f"gemini-web2api {__version__}")
|
|
1084
|
+
args = parser.parse_args()
|
|
1085
|
+
|
|
1086
|
+
config_path = args.config or os.environ.get("GEMINI_WEB2API_CONFIG")
|
|
1087
|
+
if not config_path:
|
|
1088
|
+
for p in ["./config.json", os.path.expanduser("~/.config/gemini-web2api/config.json")]:
|
|
1089
|
+
if os.path.exists(p):
|
|
1090
|
+
config_path = p
|
|
1091
|
+
break
|
|
1092
|
+
load_config(config_path)
|
|
1093
|
+
|
|
1094
|
+
if args.port:
|
|
1095
|
+
CONFIG["port"] = args.port
|
|
1096
|
+
if args.cookie_file:
|
|
1097
|
+
CONFIG["cookie_file"] = args.cookie_file
|
|
1098
|
+
if args.proxy:
|
|
1099
|
+
CONFIG["proxy"] = args.proxy
|
|
1100
|
+
|
|
1101
|
+
# Goated fork: bind the socket FIRST so the launcher's health poll passes
|
|
1102
|
+
# instantly; refresh gemini_bl in the background (its fetch can stall on
|
|
1103
|
+
# some networks, and a stale-but-valid default bl serves anonymous chat).
|
|
1104
|
+
def _bl_refresh():
|
|
1105
|
+
new_bl = fetch_latest_bl()
|
|
1106
|
+
if new_bl:
|
|
1107
|
+
CONFIG["gemini_bl"] = new_bl
|
|
1108
|
+
|
|
1109
|
+
import threading
|
|
1110
|
+
threading.Thread(target=_bl_refresh, daemon=True).start()
|
|
1111
|
+
|
|
1112
|
+
class ThreadedServer(ThreadingMixIn, HTTPServer):
|
|
1113
|
+
daemon_threads = True
|
|
1114
|
+
allow_reuse_address = True
|
|
1115
|
+
|
|
1116
|
+
port = CONFIG["port"]
|
|
1117
|
+
server = ThreadedServer((CONFIG["host"], port), GeminiHandler)
|
|
1118
|
+
print(f"gemini-web2api v{__version__}")
|
|
1119
|
+
print(f" Listening: http://0.0.0.0:{port}")
|
|
1120
|
+
print(f" Base URL: http://localhost:{port}/v1")
|
|
1121
|
+
print(f" Models: {', '.join(MODELS.keys())}")
|
|
1122
|
+
print(f" Cookie: {'yes (' + CONFIG['cookie_file'] + ')' if CONFIG.get('cookie_file') else 'none (anonymous)'}")
|
|
1123
|
+
print(f" Proxy: {CONFIG.get('proxy') or 'none (uses system env HTTP_PROXY/HTTPS_PROXY)'}")
|
|
1124
|
+
print(f" Retry: {CONFIG['retry_attempts']}x / {CONFIG['retry_delay_sec']}s")
|
|
1125
|
+
print(f" BL: {CONFIG['gemini_bl']}")
|
|
1126
|
+
print(f" Temporary: {'yes' if CONFIG.get('temporary_chats', False) else 'no'}")
|
|
1127
|
+
print()
|
|
1128
|
+
try:
|
|
1129
|
+
server.serve_forever()
|
|
1130
|
+
except KeyboardInterrupt:
|
|
1131
|
+
print("\nStopped.")
|
|
1132
|
+
server.shutdown()
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
if __name__ == "__main__":
|
|
1136
|
+
main()
|