-
Notifications
You must be signed in to change notification settings - Fork 608
Expand file tree
/
Copy pathgemini_web2api.py
More file actions
1108 lines (995 loc) · 45.9 KB
/
Copy pathgemini_web2api.py
File metadata and controls
1108 lines (995 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
gemini-web2api - Gemini Web to OpenAI API proxy.
Converts Google Gemini's web interface into an OpenAI-compatible API server.
Zero authentication required. Works on any platform (Windows/macOS/Linux).
Usage:
pip install httpx
python gemini_web2api.py [--port 8081] [--config config.json]
Client configuration (Cherry Studio, ChatBox, etc.):
Base URL: http://localhost:8081/v1
API Key: (anything or empty)
How it works:
Sends requests directly to Gemini's public StreamGenerate endpoint.
The backend does not verify authentication for basic text generation.
Model selection via MODE_CATEGORY field [79] in the request payload.
This is NOT a user-tier spoofing attack - the endpoint simply doesn't
require auth for anonymous access.
"""
import json
import urllib.request
import urllib.parse
import time
import ssl
import sys
import uuid
import re
import os
import hashlib
import argparse
import base64
import binascii
from typing import Optional
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
try:
import httpx
HAS_HTTPX = True
except ImportError:
HAS_HTTPX = False
__version__ = "1.1.0"
# ─── Configuration ───────────────────────────────────────────────────────────
DEFAULT_CONFIG = {
"port": 8081,
"host": "0.0.0.0",
"retry_attempts": 3,
"retry_delay_sec": 2,
"request_timeout_sec": 180,
"gemini_bl": "boq_assistant-bard-web-server_20260716.08_p0",
"auth_user": None,
"xsrf_token": None,
"default_model": "gemini-3.6-flash",
"log_requests": True,
"cookie_file": None,
"proxy": None,
"api_keys": [],
"temporary_chats": False,
}
CONFIG = dict(DEFAULT_CONFIG)
# ─── Models ──────────────────────────────────────────────────────────────────
# Mapping from JS source: MODE_CATEGORY enum (028-6eb337387583.js)
# 1=FAST, 2=THINKING, 3=PRO, 4=AUTO, 5=FAST_DYNAMIC_THINKING, 6=FLASH_LITE
MODELS = {
"gemini-3.7-flash": {
"mode": 1, "think": 4,
"desc": "Latest all-around model (Gemini 3.7 Flash)",
},
"gemini-3.6-flash": {
"mode": 1, "think": 4,
"desc": "All-around model (Gemini 3.6 Flash)",
},
"gemini-3.5-flash": {
"mode": 1, "think": 4,
"desc": "Alias for gemini-3.6-flash (backend upgraded)",
},
"gemini-3.5-flash-thinking": {
"mode": 2, "think": 0,
"desc": "Deep thinking mode, longest output (~20k chars)",
},
"gemini-3.1-pro": {
"mode": 3, "think": 4,
"desc": "Pro model (requires cookie for real routing)",
},
"gemini-auto": {
"mode": 4, "think": 4,
"desc": "Auto model selection",
},
"gemini-3.5-flash-thinking-lite": {
"mode": 5, "think": 0,
"desc": "Dynamic thinking with adaptive depth",
},
"gemini-flash-lite": {
"mode": 6, "think": 4,
"desc": "Lightweight fast model",
},
}
# ─── Utilities ───────────────────────────────────────────────────────────────
def log(msg: str):
if CONFIG["log_requests"]:
sys.stderr.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")
sys.stderr.flush()
def load_cookie() -> tuple:
"""Load cookie from file. Returns (cookie_str, sapisid)."""
cookie_file = CONFIG.get("cookie_file")
if not cookie_file:
return "", None
if not os.path.exists(cookie_file):
return "", None
try:
with open(cookie_file, "r") as f:
content = f.read().strip()
if content.startswith("{"):
data = json.loads(content)
cookie_str = data.get("cookie", "")
sapisid = data.get("sapisid", "")
else:
cookie_str = content
pairs = dict(p.split("=", 1) for p in cookie_str.split("; ") if "=" in p)
sapisid = pairs.get("SAPISID", "")
return cookie_str, sapisid if sapisid else None
except Exception as e:
log(f"Cookie load error: {e}")
return "", None
def make_sapisidhash(sapisid: str) -> str:
ts = int(time.time())
h = hashlib.sha1(f"{ts} {sapisid} https://gemini.google.com".encode()).hexdigest()
return f"SAPISIDHASH {ts}_{h}"
def account_prefix() -> str:
"""Return the Gemini account path prefix for non-default Google accounts."""
auth_user = CONFIG.get("auth_user")
if auth_user is None or auth_user == "":
return ""
return f"/u/{auth_user}"
def apply_chat_persistence_flags(inner: list) -> None:
"""Apply Gemini Web persistence flags to an outgoing request payload."""
if CONFIG.get("temporary_chats", False):
inner[41] = [1]
inner[45] = 1
else:
inner[41] = [2]
def fetch_latest_bl() -> Optional[str]:
"""Fetch the latest gemini_bl from gemini.google.com page."""
try:
req = urllib.request.Request(
"https://gemini.google.com/app",
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"})
ctx = ssl.create_default_context()
proxy = CONFIG.get("proxy")
if proxy:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
urllib.request.HTTPSHandler(context=ctx))
resp = opener.open(req, timeout=15)
else:
resp = urllib.request.urlopen(req, context=ctx, timeout=15)
html = resp.read().decode("utf-8", errors="replace")
m = re.search(r'(boq_assistant-bard-web-server_\d+\.\d+_p\d+)', html)
if m:
return m.group(1)
except Exception as e:
log(f"BL auto-update fetch failed: {e}")
return None
def update_bl_if_needed() -> bool:
"""Attempt to fetch and update gemini_bl. Returns True if updated."""
new_bl = fetch_latest_bl()
if new_bl and new_bl != CONFIG["gemini_bl"]:
log(f"BL auto-updated: {CONFIG['gemini_bl']} -> {new_bl}")
CONFIG["gemini_bl"] = new_bl
return True
return False
def upload_images(images: list) -> list:
"""Upload parsed OpenAI image parts and return Gemini file references."""
if not images:
return None
from gemini_web2api.multimodal import detect_image_mime, fetch_image_bytes, upload_image
file_refs = []
for item in images:
if not (isinstance(item, tuple) and len(item) == 2):
continue
data, mime = item
if isinstance(data, str):
data = fetch_image_bytes(data)
mime = mime or "image/png"
if not data:
raise RuntimeError("image fetch failed")
mime = detect_image_mime(data, mime or "image/png")
try:
file_refs.append(upload_image(data, "image.png", mime or "image/png"))
except Exception as e:
raise RuntimeError(f"image upload failed: {e}") from e
return file_refs if file_refs else None
# ─── Gemini Protocol ─────────────────────────────────────────────────────────
def gemini_stream_generate(prompt: str, model_id: int, think_mode: int, file_refs: list = None) -> str:
"""Send prompt to Gemini StreamGenerate with retry."""
inner = [None] * 80
if file_refs:
refs = [[None, None, ref] for ref in file_refs]
inner[0] = [prompt, 0, None, refs, None, None, 0]
else:
inner[0] = [prompt, 0, None, None, None, None, 0]
inner[1] = ["en"]
inner[2] = ["", "", "", None, None, None, None, None, None, ""]
inner[6] = [0]
inner[7] = 1
inner[10] = 1
inner[11] = 0
inner[17] = [[think_mode]]
inner[18] = 0
inner[27] = 1
inner[30] = [4]
apply_chat_persistence_flags(inner)
inner[53] = 0
inner[59] = str(uuid.uuid4())
inner[61] = []
inner[68] = 1
inner[79] = model_id
outer = [None, json.dumps(inner)]
params = {"f.req": json.dumps(outer)}
if CONFIG.get("xsrf_token"):
params["at"] = CONFIG["xsrf_token"]
body = urllib.parse.urlencode(params).encode()
reqid = int(time.time()) % 1000000
prefix = account_prefix()
url = (
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
"assistant.lamda.BardFrontendService/StreamGenerate"
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://gemini.google.com",
"Referer": f"https://gemini.google.com{prefix}/app",
"X-Same-Domain": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
}
if prefix:
headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
cookie_str, sapisid = load_cookie()
if cookie_str:
headers["Cookie"] = cookie_str
if sapisid:
headers["Authorization"] = make_sapisidhash(sapisid)
last_err = None
for attempt in range(CONFIG["retry_attempts"]):
try:
req = urllib.request.Request(url, data=body, headers=headers, method="POST")
ctx = ssl.create_default_context()
proxy = CONFIG.get("proxy")
if proxy:
opener = urllib.request.build_opener(
urllib.request.ProxyHandler({"http": proxy, "https": proxy}),
urllib.request.HTTPSHandler(context=ctx)
)
resp = opener.open(req, timeout=CONFIG["request_timeout_sec"])
else:
resp = urllib.request.urlopen(req, context=ctx, timeout=CONFIG["request_timeout_sec"])
return resp.read().decode("utf-8", errors="replace")
except urllib.error.HTTPError as e:
if e.code == 405 and update_bl_if_needed():
reqid = int(time.time()) % 1000000
url = (
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
"assistant.lamda.BardFrontendService/StreamGenerate"
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
)
log("Retrying with updated BL...")
last_err = e
continue
last_err = e
if attempt < CONFIG["retry_attempts"] - 1:
log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
time.sleep(CONFIG["retry_delay_sec"])
except Exception as e:
last_err = e
if attempt < CONFIG["retry_attempts"] - 1:
log(f"Retry {attempt+1}/{CONFIG['retry_attempts']}: {e}")
time.sleep(CONFIG["retry_delay_sec"])
raise last_err
def gemini_stream_generate_iter(prompt: str, model_id: int, think_mode: int, file_refs: list = None):
"""Send prompt and yield incremental text deltas using httpx streaming."""
inner = [None] * 80
if file_refs:
refs = [[None, None, ref] for ref in file_refs]
inner[0] = [prompt, 0, None, refs, None, None, 0]
else:
inner[0] = [prompt, 0, None, None, None, None, 0]
inner[1] = ["en"]
inner[2] = ["", "", "", None, None, None, None, None, None, ""]
inner[6] = [0]
inner[7] = 1
inner[10] = 1
inner[11] = 0
inner[17] = [[think_mode]]
inner[18] = 0
inner[27] = 1
inner[30] = [4]
apply_chat_persistence_flags(inner)
inner[53] = 0
inner[59] = str(uuid.uuid4())
inner[61] = []
inner[68] = 1
inner[79] = model_id
outer = [None, json.dumps(inner)]
params = {"f.req": json.dumps(outer)}
if CONFIG.get("xsrf_token"):
params["at"] = CONFIG["xsrf_token"]
body = urllib.parse.urlencode(params)
reqid = int(time.time()) % 1000000
prefix = account_prefix()
url = (
f"https://gemini.google.com{prefix}/_/BardChatUi/data/"
"assistant.lamda.BardFrontendService/StreamGenerate"
f"?bl={CONFIG['gemini_bl']}&hl=en&_reqid={reqid}&rt=c"
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://gemini.google.com",
"Referer": f"https://gemini.google.com{prefix}/app",
"X-Same-Domain": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
}
if prefix:
headers["X-Goog-AuthUser"] = str(CONFIG["auth_user"])
cookie_str, sapisid = load_cookie()
if cookie_str:
headers["Cookie"] = cookie_str
if sapisid:
headers["Authorization"] = make_sapisidhash(sapisid)
proxy = CONFIG.get("proxy")
if not HAS_HTTPX:
# Fallback: non-streaming with urllib
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
text = extract_response_text(raw)
if text:
yield text
return
prev_text = ""
transport = httpx.HTTPTransport(proxy=proxy) if proxy else None
with httpx.Client(transport=transport, timeout=CONFIG["request_timeout_sec"], verify=True) as client:
try:
with client.stream("POST", url, content=body, headers=headers) as resp:
resp.raise_for_status()
buf = ""
for chunk in resp.iter_text():
buf += chunk
if "BardErrorInfo" in buf:
import re as _re
m = _re.search(r'BardErrorInfo\s*\[(\d+)\]', buf)
if m:
raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{m.group(1)}]")
while "\n" in buf:
line, buf = buf.split("\n", 1)
if '"wrb.fr"' not in line or len(line) < 200:
continue
try:
arr = json.loads(line)
inner_str = arr[0][2]
if not inner_str or len(inner_str) < 50:
continue
inner2 = json.loads(inner_str)
if isinstance(inner2, list) and len(inner2) > 4 and inner2[4]:
for part in inner2[4]:
if isinstance(part, list) and len(part) > 1 and part[1] and isinstance(part[1], list):
for t in part[1]:
if isinstance(t, str) and len(t) > len(prev_text):
delta = t[len(prev_text):]
delta = clean_gemini_text(delta, strip=False)
if delta:
yield delta
prev_text = t
except (json.JSONDecodeError, IndexError, TypeError):
pass
except Exception as e:
if HAS_HTTPX and hasattr(e, 'response') and getattr(e.response, 'status_code', 0) == 405:
if update_bl_if_needed():
log("BL updated, falling back to non-streaming for this request")
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
text = extract_response_text(raw)
if text:
yield text
return
raise
def clean_gemini_text(text: str, strip: bool = True) -> str:
"""Remove internal code execution artifacts."""
text = re.sub(
r'```(?:python|javascript|text)\?code_(?:reference|stdout)&code_event_index=\d+\n.*?```\n?',
'', text, flags=re.DOTALL
)
return text.strip() if strip else text
def extract_response_text(raw: str) -> str:
"""Parse StreamGenerate response to extract final text."""
import re as _re
bard_err = _re.search(r'BardErrorInfo\s*\[(\d+)\]', raw)
if bard_err:
raise RuntimeError(f"Gemini upstream rejected request: BardErrorInfo [{bard_err.group(1)}]")
texts = []
for line in raw.split("\n"):
if '"wrb.fr"' not in line or len(line) < 200:
continue
try:
arr = json.loads(line)
inner_str = arr[0][2]
if not inner_str or len(inner_str) < 50:
continue
inner = json.loads(inner_str)
if isinstance(inner, list) and len(inner) > 4 and inner[4]:
for part in inner[4]:
if isinstance(part, list) and len(part) > 1 and part[1]:
if isinstance(part[1], list):
for t in part[1]:
if isinstance(t, str) and len(t) > 0:
texts.append(t)
except (json.JSONDecodeError, IndexError, TypeError):
pass
text = ""
for t in reversed(texts):
if t.strip():
text = t
break
return clean_gemini_text(text)
# ─── OpenAI Format Helpers ───────────────────────────────────────────────────
PROMPT_MAX_BYTES = 60000
def decode_data_url(url: str):
match = re.match(r"^data:([^;,]+)?(;base64)?,(.*)$", url, re.DOTALL)
if not match:
return None
mime = match.group(1) or "image/png"
is_base64 = bool(match.group(2))
data = match.group(3)
try:
if is_base64:
return base64.b64decode(data, validate=True), mime
return urllib.parse.unquote_to_bytes(data), mime
except (ValueError, TypeError, binascii.Error):
return None
def image_from_url(url: str, mime: str = None):
if not isinstance(url, str) or not url:
return None
if url.startswith("data:"):
return decode_data_url(url)
return url, mime or "image/png"
def image_from_part(part: dict):
part_type = part.get("type")
if part_type == "image_url":
image_url = part.get("image_url", {})
if isinstance(image_url, dict):
return image_from_url(image_url.get("url"), image_url.get("mime_type"))
return image_from_url(image_url)
if part_type in ("input_image", "image"):
image_url = part.get("image_url") or part.get("url")
if isinstance(image_url, dict):
return image_from_url(image_url.get("url"), image_url.get("mime_type"))
if image_url:
return image_from_url(image_url, part.get("mime_type"))
image_data = part.get("data") or part.get("base64")
if isinstance(image_data, str):
mime = part.get("mime_type") or part.get("media_type") or "image/png"
if image_data.startswith("data:"):
return decode_data_url(image_data)
try:
return base64.b64decode(image_data, validate=True), mime
except (ValueError, TypeError, binascii.Error):
return None
return None
def messages_to_prompt(messages: list, tools: list = None) -> tuple:
"""Convert OpenAI messages to (prompt_str, images_list)."""
parts = []
images = []
if tools:
tool_defs = []
for tool in tools:
fn = tool.get("function", tool) if tool.get("type") == "function" else tool
tool_defs.append({
"name": fn.get("name", tool.get("name", "")),
"description": fn.get("description", tool.get("description", "")),
"parameters": fn.get("parameters", tool.get("parameters", {})),
})
if tool_defs:
tools_json = json.dumps(tool_defs, indent=2)
if len(tools_json) > PROMPT_MAX_BYTES // 2:
slim_defs = [{"name": t["name"], "description": t["description"]} for t in tool_defs]
tools_json = json.dumps(slim_defs, indent=2)
log(f"Tools block too large ({len(tool_defs)} tools), stripped parameters")
parts.append(
"[System instruction]: You have access to tools. "
"To call a tool, respond with:\n"
'```tool_call\n{"name": "func_name", "arguments": {...}}\n```\n'
"Only use tool_call blocks when needed.\n\n"
f"Available tools:\n{tools_json}"
)
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
if isinstance(content, list):
text_parts = []
for c in content:
if c.get("type") in ("text", "input_text", "output_text"):
text_parts.append(c.get("text", ""))
else:
image = image_from_part(c)
if image:
images.append(image)
text_parts.append("[Image attached]")
content = " ".join(text_parts)
if role == "system":
parts.append(f"[System instruction]: {content}")
elif role == "assistant":
if msg.get("tool_calls"):
tc_strs = []
for tc in msg["tool_calls"]:
fn = tc.get("function", {})
tc_strs.append(
f'```tool_call\n{{"name": "{fn.get("name")}", '
f'"arguments": {fn.get("arguments", "{}")}}}\n```'
)
parts.append(f"[Assistant]: {content or ''}\n" + "\n".join(tc_strs))
else:
parts.append(f"[Assistant]: {content}")
elif role == "tool":
parts.append(f"[Tool result for {msg.get('name', '')}]: {content}")
else:
parts.append(content if content else "")
return "\n\n".join(p for p in parts if p), images
def google_contents_to_prompt(req: dict) -> tuple:
"""Convert Google API contents to (prompt_str, images_list)."""
parts = []
images = []
sys_inst = req.get("systemInstruction")
if sys_inst:
sys_text = " ".join(
part.get("text", "") for part in sys_inst.get("parts", []) if part.get("text")
)
if sys_text:
parts.append(f"[System instruction]: {sys_text}")
for content in req.get("contents", []):
role = content.get("role", "user")
text_parts = []
for part in content.get("parts", []):
if part.get("text"):
text_parts.append(part["text"])
elif part.get("inlineData"):
data = part["inlineData"]
try:
images.append((
base64.b64decode(data["data"], validate=True),
data.get("mimeType", "image/png"),
))
text_parts.append("[Image attached]")
except (KeyError, ValueError, TypeError, binascii.Error):
pass
text = " ".join(text_parts)
if role == "model":
parts.append(f"[Assistant]: {text}")
else:
parts.append(text)
return "\n\n".join(part for part in parts if part), images
def parse_tool_calls(text: str) -> tuple:
"""Extract tool_call blocks. Returns (clean_text, tool_calls_list)."""
tool_calls = []
pattern = r'```tool_call\s*\n(.*?)\n```'
for match in re.findall(pattern, text, re.DOTALL):
try:
data = json.loads(match.strip())
tool_calls.append({
"id": f"call_{uuid.uuid4().hex[:8]}",
"type": "function",
"function": {
"name": data["name"],
"arguments": json.dumps(data.get("arguments", {}), ensure_ascii=False),
},
})
except (json.JSONDecodeError, KeyError):
pass
clean = re.sub(pattern, '', text, flags=re.DOTALL).strip()
return clean, tool_calls
# ─── HTTP Handler ────────────────────────────────────────────────────────────
class GeminiHandler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
client_ip = self.client_address[0] if self.client_address else "-"
log(f"{client_ip} {fmt % args}")
def send_json(self, data, status=200):
body = json.dumps(data, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _authorized(self):
keys = CONFIG.get("api_keys") or []
if not keys:
return True
# Authorization: Bearer <key>
auth = self.headers.get("Authorization", "")
if auth.startswith("Bearer ") and auth[7:] in keys:
return True
# header keys (OpenAI x-api-key / Google x-goog-api-key)
for h in ("x-api-key", "x-goog-api-key"):
if self.headers.get(h, "") in keys:
return True
# query param ?key= (Gemini CLI native style)
if "?" in self.path:
for pair in self.path.split("?", 1)[1].split("&"):
if pair.startswith("key=") and pair[4:] in keys:
return True
return False
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "*")
self.end_headers()
def do_GET(self):
try:
if self.path.startswith("/v1") and not self._authorized():
self.send_json({"error": {"message": "invalid api key"}}, 401)
return
if self.path == "/v1/models":
self.send_json({"object": "list", "data": [
{"id": n, "object": "model", "created": 1700000000,
"owned_by": "google", "description": c["desc"]}
for n, c in MODELS.items()
]})
elif self.path.startswith("/v1beta/models"):
self._handle_google_models_list()
elif self.path == "/":
self.send_json({"status": "ok", "version": __version__,
"models": list(MODELS.keys())})
else:
self.send_json({"error": "not found"}, 404)
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as e:
log(f"GET error: {e}")
def do_POST(self):
try:
if self.path.startswith("/v1") and not self._authorized():
self.send_json({"error": {"message": "invalid api key"}}, 401)
return
body = self._read_request_body()
if self.path == "/v1/chat/completions":
self.handle_chat(body)
elif self.path == "/v1/responses":
self.handle_responses(body)
elif ":streamGenerateContent" in self.path:
self._handle_google_generate(body, stream=True)
elif ":generateContent" in self.path:
self._handle_google_generate(body, stream=False)
else:
self.send_json({"error": "not found"}, 404)
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as e:
log(f"POST error: {e}")
try:
self.send_json({"error": {"message": str(e)}}, 500)
except:
pass
def _read_request_body(self) -> bytes:
transfer_encoding = self.headers.get("Transfer-Encoding", "")
if "chunked" in transfer_encoding.lower():
chunks = []
while True:
size_line = self.rfile.readline()
if not size_line:
break
size_text = size_line.split(b";", 1)[0].strip()
try:
size = int(size_text, 16)
except ValueError:
raise ValueError("invalid chunked request body")
if size == 0:
while True:
trailer = self.rfile.readline()
if trailer in (b"\r\n", b"\n", b""):
break
break
chunks.append(self.rfile.read(size))
self.rfile.read(2)
return b"".join(chunks)
length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(length) if length else b""
def _resolve_model(self, model_name):
think_override = None
if "@think=" in model_name:
model_name, think_str = model_name.rsplit("@think=", 1)
think_override = int(think_str)
cfg = MODELS.get(model_name)
if not cfg:
return None, None, None, f"Unknown model: {model_name}"
return model_name, cfg["mode"], (think_override if think_override is not None else cfg["think"]), None
def _call_gemini(self, prompt, model_id, think_mode, tools, file_refs=None):
raw = gemini_stream_generate(prompt, model_id, think_mode, file_refs)
text = extract_response_text(raw)
tool_calls = None
if tools and text:
text, tool_calls = parse_tool_calls(text)
return text or "", tool_calls
def handle_chat(self, body: bytes):
req = json.loads(body)
model_name, model_id, think_mode, err = self._resolve_model(
req.get("model", CONFIG["default_model"]))
if err:
self.send_json({"error": {"message": err}}, 400)
return
tools = req.get("tools")
prompt, images = messages_to_prompt(req.get("messages", []), tools)
if not prompt.strip():
self.send_json({"error": {"message": "empty prompt"}}, 400)
return
stream = req.get("stream", False)
cid = f"chatcmpl-{uuid.uuid4().hex[:12]}"
try:
file_refs = upload_images(images)
except RuntimeError as e:
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
return
if stream and not tools:
# True streaming: forward chunks as they arrive
try:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
first_chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
"model": model_name, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]}
self.wfile.write(f"data: {json.dumps(first_chunk)}\n\n".encode())
for delta_text in gemini_stream_generate_iter(prompt, model_id, think_mode, file_refs):
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
"model": model_name, "choices": [{"index": 0, "delta": {"content": delta_text}, "finish_reason": None}]}
self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
self.wfile.flush()
# Final chunk
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
"model": model_name, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as e:
log(f"Stream error: {e}")
return
# Non-streaming (or tool calling which needs full response)
try:
text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools, file_refs)
except Exception as e:
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
return
msg = {"role": "assistant", "content": text or None}
if tool_calls:
msg["tool_calls"] = tool_calls
finish = "tool_calls" if tool_calls else "stop"
if stream:
# Stream mode with tools: send as single chunk (need full parse for tool_calls)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
chunk = {"id": cid, "object": "chat.completion.chunk", "created": int(time.time()),
"model": model_name, "choices": [{"index": 0, "delta": msg, "finish_reason": finish}]}
self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
else:
self.send_json({
"id": cid, "object": "chat.completion", "created": int(time.time()),
"model": model_name,
"choices": [{"index": 0, "message": msg, "finish_reason": finish}],
"usage": {"prompt_tokens": len(prompt)//4, "completion_tokens": len(text)//4,
"total_tokens": (len(prompt)+len(text))//4},
})
def handle_responses(self, body: bytes):
"""OpenAI Responses API for Codex CLI compatibility."""
req = json.loads(body)
model_name, model_id, think_mode, err = self._resolve_model(
req.get("model", CONFIG["default_model"]))
if err:
self.send_json({"error": {"message": err}}, 400)
return
input_items = req.get("input", [])
tools = req.get("tools")
messages = []
if req.get("instructions"):
messages.append({"role": "system", "content": req["instructions"]})
if isinstance(input_items, str):
messages.append({"role": "user", "content": input_items})
elif isinstance(input_items, list):
for item in input_items:
if isinstance(item, str):
messages.append({"role": "user", "content": item})
elif isinstance(item, dict):
if item.get("type") == "function_call_output":
messages.append({"role": "tool", "tool_call_id": item.get("call_id", ""),
"name": item.get("name", ""), "content": item.get("output", "")})
elif item.get("type") in ("input_text", "input_image", "image"):
messages.append({"role": "user", "content": [item]})
elif item.get("role") == "assistant" or (item.get("type") == "message" and item.get("role") == "assistant"):
cp = item.get("content", [])
text_acc, tc_list = "", []
if isinstance(cp, list):
for c in cp:
if isinstance(c, dict):
if c.get("type") == "output_text": text_acc += c.get("text", "")
elif c.get("type") == "function_call": tc_list.append(c)
elif isinstance(cp, str):
text_acc = cp
m = {"role": "assistant", "content": text_acc or None}
if tc_list:
m["tool_calls"] = [{"id": tc.get("call_id", f"call_{i}"), "type": "function",
"function": {"name": tc.get("name",""), "arguments": tc.get("arguments","{}")}}
for i, tc in enumerate(tc_list)]
messages.append(m)
else:
role = item.get("role", "user")
messages.append({"role": role, "content": item.get("content", "")})
if tools:
tools = [{"type": "function", "function": {"name": t["name"], "description": t.get("description", ""), "parameters": t.get("parameters", {})}}
if t.get("type") == "function" and "function" not in t else t for t in tools]
prompt, images = messages_to_prompt(messages, tools)
if not prompt.strip():
self.send_json({"error": {"message": "empty input"}}, 400)
return
try:
file_refs = upload_images(images)
text, tool_calls = self._call_gemini(prompt, model_id, think_mode, tools, file_refs)
except Exception as e:
self.send_json({"error": {"message": f"upstream error: {e}"}}, 502)
return
rid = f"resp_{uuid.uuid4().hex[:16]}"
mid = f"msg_{uuid.uuid4().hex[:12]}"
output = []
if tool_calls:
for tc in tool_calls:
output.append({"type": "function_call", "id": tc["id"], "call_id": tc["id"],
"name": tc["function"]["name"], "arguments": tc["function"]["arguments"], "status": "completed"})
if text or not tool_calls:
output.append({"type": "message", "id": mid, "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": text or "", "annotations": []}]})
if req.get("stream"):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
seq = [0]
def emit(ev_type, **fields):
seq[0] += 1
ev = {"type": ev_type, "sequence_number": seq[0], **fields}
self.wfile.write(f"event: {ev_type}\ndata: {json.dumps(ev)}\n\n".encode())
usage = {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}
base_resp = {"id": rid, "object": "response", "created_at": int(time.time()), "model": model_name}
emit("response.created", response={**base_resp, "status": "in_progress", "output": [], "usage": None})
emit("response.in_progress", response={**base_resp, "status": "in_progress", "output": [], "usage": None})
for oi, item in enumerate(output):
if item["type"] == "function_call":
pending = {"type": "function_call", "id": item["id"], "call_id": item["call_id"],
"name": item["name"], "arguments": "", "status": "in_progress"}
emit("response.output_item.added", output_index=oi, item=pending)
emit("response.function_call_arguments.delta", item_id=item["id"], output_index=oi, delta=item["arguments"])
emit("response.function_call_arguments.done", item_id=item["id"], output_index=oi, arguments=item["arguments"])
emit("response.output_item.done", output_index=oi, item=item)
elif item["type"] == "message":
pending = {"type": "message", "id": item["id"], "role": "assistant", "status": "in_progress", "content": []}
emit("response.output_item.added", output_index=oi, item=pending)
for ci, cp in enumerate(item["content"]):
emit("response.content_part.added", item_id=item["id"], output_index=oi, content_index=ci,
part={"type": "output_text", "text": "", "annotations": []})
emit("response.output_text.delta", item_id=item["id"], output_index=oi, content_index=ci, delta=cp["text"])
emit("response.output_text.done", item_id=item["id"], output_index=oi, content_index=ci, text=cp["text"])
emit("response.content_part.done", item_id=item["id"], output_index=oi, content_index=ci, part=cp)
emit("response.output_item.done", output_index=oi, item=item)
emit("response.completed", response={**base_resp, "status": "completed", "output": output, "usage": usage})
self.wfile.flush()
else:
self.send_json({"id": rid, "object": "response", "created_at": int(time.time()), "status": "completed",
"model": model_name, "output": output,
"usage": {"input_tokens": len(prompt)//4, "output_tokens": len(text)//4, "total_tokens": (len(prompt)+len(text))//4}})
# ─── Google Native API (Gemini CLI compatible) ────────────────────────────
def _parse_google_model_from_path(self):
"""Extract model name from /v1beta/models/{model}:method path."""
m = re.match(r'/v1beta/models/([^:?]+)', self.path)
if m:
return m.group(1)
return None
def _handle_google_models_list(self):
"""GET /v1beta/models — Google AI format model list."""
models = []
for name, cfg in MODELS.items():
models.append({
"name": f"models/{name}",
"displayName": name,
"description": cfg["desc"],
"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],
})
self.send_json({"models": models})
def _handle_google_generate(self, body: bytes, stream: bool):
"""Handle Google native generateContent / streamGenerateContent."""
req = json.loads(body)
model_name = self._parse_google_model_from_path()
if not model_name:
self.send_json({"error": {"message": "model not specified in path"}}, 400)
return