-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_bridge.py
More file actions
9033 lines (8030 loc) · 331 KB
/
simple_bridge.py
File metadata and controls
9033 lines (8030 loc) · 331 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
"""
Universal LLM Gateway - OpenAI and Anthropic API compatible proxy
Features:
- Virtual model mapping to multiple backends (RunPod, DeepInfra, Ollama, etc.)
- OpenAI-compatible API (/v1/chat/completions, /v1/models, etc.)
- Anthropic-compatible API (/v1/messages) - works with Claude Code
- Admin UI for endpoint and model configuration
- Token usage tracking and cost calculation
- Tool call extraction from various model output formats
- Streaming support for both APIs
"""
from fastapi import FastAPI, Request
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.requests import Request as FastAPIRequest
import httpx
import os
import time
import time as time_module
import json
import asyncio
import base64
import re
import hashlib
import sqlite3
import urllib.parse
from pathlib import Path
from abc import ABC, abstractmethod
from typing import Any, Optional
from contextlib import contextmanager
# Flask for admin UI
from flask import (
Flask,
render_template,
request as flask_request,
jsonify as flask_jsonify,
redirect,
)
import secrets
# Flask app for admin routes
FLASK_PORT = int(os.getenv("FLASK_PORT", 5001))
flask_app = Flask(__name__, template_folder="templates", static_folder="static")
flask_app.secret_key = os.getenv("SECRET_KEY", secrets.token_hex(32))
AIMENU_URL = os.getenv("AIMENU_URL", "http://localhost:5000")
def is_auth_enabled():
"""Check if auth is enabled - reads from env at call time, not load time."""
return os.getenv("AUTH_ENABLED", "true").lower() == "true"
# Backwards compatibility
AUTH_ENABLED = is_auth_enabled()
# Database setup
DATABASE_PATH = os.getenv("DATABASE_PATH", "/data/proxy.db")
def get_db_connection():
"""Get database connection."""
os.makedirs(os.path.dirname(DATABASE_PATH), exist_ok=True)
conn = sqlite3.connect(DATABASE_PATH)
conn.row_factory = sqlite3.Row
return conn
@contextmanager
def get_db():
"""Context manager for database."""
conn = get_db_connection()
try:
yield conn
finally:
conn.close()
def get_setting(key, default=None):
"""Get a setting from the database, fallback to default."""
try:
with get_db() as conn:
cursor = conn.cursor()
cursor.execute("SELECT value FROM settings WHERE key = ?", (key,))
row = cursor.fetchone()
if row:
return row["value"]
except Exception as e:
print(f"Error getting setting {key}: {e}")
return default
def get_api_port():
"""Get API port from DB, fallback to env var or default."""
return int(get_setting("api_port", os.getenv("API_PORT", "8002")))
def get_flask_port():
"""Get Flask/Admin port from DB, fallback to env var or default."""
return int(get_setting("flask_port", os.getenv("FLASK_PORT", "5001")))
def is_debug_mode():
"""Check if debug mode is enabled. Returns 'off', 'basic', or 'full'."""
return get_setting("debug_mode", "off")
def is_payload_audit_enabled() -> bool:
"""Check if persisted payload audit snapshots are enabled."""
value = get_setting(
"payload_audit_enabled", os.getenv("PAYLOAD_AUDIT_ENABLED", "false")
)
return str(value).lower() in ("1", "true", "yes", "on")
def debug_log(level, msg):
"""Log message if debug mode is enabled. level: 'info', 'warn', 'error'."""
mode = is_debug_mode()
if mode == "off":
return
if level == "error" or level == "warn" or mode == "full":
print(f"[DEBUG:{level.upper()}] {msg}", flush=True)
def _ollama_options_from_openai(
temperature: float,
max_tokens: int,
top_p: float,
kwargs: dict,
) -> dict:
"""Map OpenAI-style sampling params into Ollama options."""
options = {}
if temperature is not None:
options["temperature"] = temperature
if max_tokens is not None:
options["num_predict"] = max_tokens
if top_p is not None:
options["top_p"] = top_p
if kwargs.get("stop") is not None:
options["stop"] = kwargs.get("stop")
if kwargs.get("presence_penalty") is not None:
options["presence_penalty"] = kwargs.get("presence_penalty")
if kwargs.get("frequency_penalty") is not None:
options["frequency_penalty"] = kwargs.get("frequency_penalty")
return options
def _openai_to_ollama_chat_payload(
model: str,
messages: list,
stream: bool,
temperature: float,
max_tokens: int,
top_p: float,
tools: Optional[list],
kwargs: dict,
) -> dict:
"""Build Ollama-native /api/chat payload from OpenAI-style request."""
payload = {
"model": model,
"messages": _normalize_ollama_messages(messages),
"stream": stream,
"options": _ollama_options_from_openai(temperature, max_tokens, top_p, kwargs),
}
if tools:
payload["tools"] = tools
# Do not forward OpenAI tool_choice object to Ollama; some versions reject it.
if kwargs.get("format") is not None:
payload["format"] = kwargs.get("format")
response_format = kwargs.get("response_format")
if response_format is not None and payload.get("format") is None:
if isinstance(response_format, str):
if response_format == "json":
payload["format"] = "json"
elif isinstance(response_format, dict):
rf_type = response_format.get("type")
if rf_type == "json_object":
payload["format"] = "json"
# Skip json_schema passthrough for Ollama compatibility.
if kwargs.get("keep_alive") is not None:
payload["keep_alive"] = kwargs.get("keep_alive")
return payload
def _normalize_ollama_messages(messages: list) -> list:
"""Ensure Ollama messages[].content is always a string."""
out = []
if not isinstance(messages, list):
return out
for msg in messages:
if not isinstance(msg, dict):
continue
item = dict(msg)
content = item.get("content", "")
if isinstance(content, list):
parts = []
for block in content:
if not isinstance(block, dict):
continue
btype = block.get("type")
if btype == "text":
parts.append(str(block.get("text") or ""))
elif btype == "image_url":
parts.append("[image]")
item["content"] = "\n".join([p for p in parts if p]).strip()
elif content is None:
item["content"] = ""
elif not isinstance(content, str):
item["content"] = str(content)
out.append(item)
return out
def _ollama_tool_calls_to_openai(ollama_tool_calls: list) -> list:
"""Convert Ollama tool_calls into OpenAI tool_calls format."""
out = []
if not isinstance(ollama_tool_calls, list):
return out
for idx, tc in enumerate(ollama_tool_calls):
if not isinstance(tc, dict):
continue
fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
name = fn.get("name") or tc.get("name") or "unknown"
arguments = fn.get("arguments") or tc.get("arguments") or {}
if not isinstance(arguments, str):
arguments = json.dumps(arguments)
out.append(
{
"id": tc.get("id") or f"call_{int(time.time() * 1000)}_{idx}",
"type": "function",
"function": {
"name": name,
"arguments": arguments,
},
}
)
return out
def _ollama_nonstream_to_openai(result: dict, model: str) -> dict:
"""Convert Ollama /api/chat non-stream response into OpenAI format."""
message = result.get("message", {}) if isinstance(result, dict) else {}
content = message.get("content") or ""
reasoning_content = message.get("thinking") or ""
tool_calls = _ollama_tool_calls_to_openai(message.get("tool_calls") or [])
done_reason = result.get("done_reason") if isinstance(result, dict) else None
finish_reason = (
"tool_calls" if tool_calls and not content else (done_reason or "stop")
)
if finish_reason == "tool_calls":
finish_reason = "tool_calls"
elif finish_reason in ("stop", "length"):
pass
else:
finish_reason = "stop"
prompt_tokens = (
result.get("prompt_eval_count", 0) if isinstance(result, dict) else 0
)
completion_tokens = result.get("eval_count", 0) if isinstance(result, dict) else 0
return {
"id": result.get("id", f"chat-{int(time.time())}"),
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": content,
"reasoning_content": reasoning_content,
"tool_calls": tool_calls if tool_calls else None,
},
"finish_reason": finish_reason,
}
],
"usage": {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": prompt_tokens + completion_tokens,
},
}
def _ollama_stream_to_openai_sse(stream_data: str, model: str) -> str:
"""Convert Ollama JSONL stream into OpenAI-style SSE stream."""
out_lines = []
created = int(time.time())
chunk_id = f"chat-{int(time.time() * 1000)}"
for line in (stream_data or "").splitlines():
raw = line.strip()
if not raw:
continue
try:
chunk = json.loads(raw)
except Exception:
continue
message = chunk.get("message", {}) if isinstance(chunk, dict) else {}
content = message.get("content") or ""
thinking = message.get("thinking") or ""
ollama_tc = message.get("tool_calls") or []
tool_calls = _ollama_tool_calls_to_openai(ollama_tc)
delta = {}
if content:
delta["content"] = content
if thinking:
delta["reasoning_content"] = thinking
if tool_calls:
delta["tool_calls"] = []
for idx, tc in enumerate(tool_calls):
delta["tool_calls"].append(
{
"index": idx,
"id": tc["id"],
"type": "function",
"function": {
"name": tc["function"]["name"],
"arguments": tc["function"]["arguments"],
},
}
)
finish_reason = None
if chunk.get("done"):
finish_reason = "tool_calls" if tool_calls and not content else "stop"
openai_chunk = {
"id": chunk_id,
"object": "chat.completion.chunk",
"created": created,
"model": model,
"choices": [
{
"index": 0,
"delta": delta,
"finish_reason": finish_reason,
}
],
}
if chunk.get("done"):
prompt_tokens = chunk.get("prompt_eval_count", 0)
completion_tokens = chunk.get("eval_count", 0)
openai_chunk["usage"] = {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": prompt_tokens + completion_tokens,
}
out_lines.append(f"data: {json.dumps(openai_chunk)}")
out_lines.append("")
out_lines.append("data: [DONE]")
out_lines.append("")
return "\n".join(out_lines)
def _openai_to_ollama_chat_response(result: dict, model: str) -> dict:
"""Convert OpenAI-style chat result into Ollama /api/chat response."""
choice = (result.get("choices") or [{}])[0]
message = choice.get("message") or {}
usage = result.get("usage") or {}
response = {
"model": model,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"message": {
"role": "assistant",
"content": message.get("content") or "",
},
"done": True,
"done_reason": choice.get("finish_reason") or "stop",
"prompt_eval_count": usage.get("prompt_tokens", 0),
"eval_count": usage.get("completion_tokens", 0),
}
if message.get("tool_calls"):
response["message"]["tool_calls"] = message.get("tool_calls")
return response
def _hash_text(value: str) -> str:
"""Return short stable hash for payload audit logs."""
if not isinstance(value, str):
value = str(value)
return hashlib.sha256(value.encode("utf-8", errors="ignore")).hexdigest()[:16]
def _detect_base64_image_mime(base64_data: str) -> str:
"""Best-effort MIME type detection from base64 image signature."""
if not isinstance(base64_data, str):
return "image/png"
sig = base64_data.strip()[:12]
if sig.startswith("iVBOR"):
return "image/png"
if sig.startswith("/9j/"):
return "image/jpeg"
if sig.startswith("R0lGOD"):
return "image/gif"
if sig.startswith("UklGR"):
return "image/webp"
if sig.startswith("Qk"):
return "image/bmp"
return "image/png"
def _extract_base64_from_data_url(value: str) -> str:
"""Normalize data payload for stable digesting."""
if not isinstance(value, str):
return ""
value = value.strip()
if value.startswith("data:") and "base64," in value:
return value.split("base64,", 1)[1].strip()
return value
PAYLOAD_AUDIT_DIR = os.getenv("PAYLOAD_AUDIT_DIR", "/data/payload_audit")
def _summarize_payload_for_storage(messages: Any) -> dict:
"""Build compact per-block summary for persisted inbound/outbound comparison."""
summary = {
"messages": len(messages) if isinstance(messages, list) else 0,
"blocks": [],
}
if not isinstance(messages, list):
return summary
marker_re = re.compile(r"Image\s*\(base64\):", re.IGNORECASE)
for msg_i, msg in enumerate(messages):
if not isinstance(msg, dict):
continue
role = msg.get("role", "")
content = msg.get("content", "")
if isinstance(content, list):
for block_i, block in enumerate(content):
if not isinstance(block, dict):
continue
btype = block.get("type")
if btype == "image_url":
image_url = block.get("image_url", {})
if isinstance(image_url, dict):
url = image_url.get("url", "")
else:
url = image_url if isinstance(image_url, str) else ""
b64 = _extract_base64_from_data_url(url)
summary["blocks"].append(
{
"message_index": msg_i,
"block_index": block_i,
"role": role,
"type": "image_url",
"base64_len": len(b64),
"digest": _hash_text(b64),
"prefix": b64[:32],
"suffix": b64[-32:] if len(b64) > 32 else b64,
}
)
elif btype == "text":
text = block.get("text", "")
if marker_re.search(text):
parts = marker_re.split(text, maxsplit=1)
b64 = _extract_base64_from_data_url(
parts[1].strip() if len(parts) > 1 else text
)
b64_clean = re.sub(r"[^A-Za-z0-9+/=]", "", b64)
summary["blocks"].append(
{
"message_index": msg_i,
"block_index": block_i,
"role": role,
"type": "text_base64",
"base64_len": len(b64_clean),
"digest": _hash_text(b64_clean),
"prefix": b64_clean[:32],
"suffix": (
b64_clean[-32:]
if len(b64_clean) > 32
else b64_clean
),
}
)
elif isinstance(content, str):
if marker_re.search(content):
parts = marker_re.split(content, maxsplit=1)
b64 = _extract_base64_from_data_url(
parts[1].strip() if len(parts) > 1 else content
)
b64_clean = re.sub(r"[^A-Za-z0-9+/=]", "", b64)
summary["blocks"].append(
{
"message_index": msg_i,
"block_index": 0,
"role": role,
"type": "text_base64",
"base64_len": len(b64_clean),
"digest": _hash_text(b64_clean),
"prefix": b64_clean[:32],
"suffix": b64_clean[-32:] if len(b64_clean) > 32 else b64_clean,
}
)
return summary
def _persist_payload_snapshot(
request_id: str,
stage: str,
model: str,
messages: Any,
audit_summary: Optional[dict] = None,
):
"""Persist payload comparison artifacts to disk for forensic debugging."""
if not is_payload_audit_enabled():
return
compact = _summarize_payload_for_storage(messages)
has_relevant = (
compact.get("blocks")
or (audit_summary and audit_summary.get("image_blocks", 0) > 0)
or (audit_summary and audit_summary.get("base64_text_blocks", 0) > 0)
)
if not has_relevant:
return
try:
out_dir = Path(PAYLOAD_AUDIT_DIR)
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{request_id}_{stage}.json"
payload = {
"request_id": request_id,
"stage": stage,
"model": model,
"ts": int(time.time()),
"audit": audit_summary or {},
"compact": compact,
}
with out_path.open("w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
print(
f"[PAYLOAD_STORE] request_id={request_id} stage={stage} path={out_path}",
flush=True,
)
except Exception as e:
debug_log(
"warn",
f"[PAYLOAD_STORE_ERR] request_id={request_id} stage={stage} error={e}",
)
def _normalize_inline_base64_messages(messages: Any) -> tuple[Any, int]:
"""Convert 'Image (base64): ...' payloads into image_url blocks."""
if not isinstance(messages, list):
return messages, 0
marker_re = re.compile(r"Image\s*\(base64\):", re.IGNORECASE)
def _normalize_text_content(content: str) -> tuple[Any, int]:
if not isinstance(content, str) or not marker_re.search(content):
return content, 0
blocks = []
last_end = 0
local_converted = 0
for match in marker_re.finditer(content):
prefix = content[last_end : match.start()]
if prefix.strip():
blocks.append({"type": "text", "text": prefix.strip()})
next_match = marker_re.search(content, match.end())
candidate = (
content[match.end() : next_match.start()]
if next_match
else content[match.end() :]
)
compact = re.sub(r"\s+", "", candidate)
if compact.startswith("data:image/"):
image_url = compact
else:
image_b64 = _extract_base64_from_data_url(compact)
image_b64 = re.sub(r"[^A-Za-z0-9+/=]", "", image_b64)
if len(image_b64) < 64:
blocks.append(
{
"type": "text",
"text": ("Image (base64):" + candidate).strip(),
}
)
last_end = next_match.start() if next_match else len(content)
continue
mime = _detect_base64_image_mime(image_b64)
image_url = f"data:{mime};base64,{image_b64}"
blocks.append({"type": "image_url", "image_url": {"url": image_url}})
local_converted += 1
last_end = next_match.start() if next_match else len(content)
suffix = content[last_end:]
if suffix.strip():
blocks.append({"type": "text", "text": suffix.strip()})
if local_converted > 0:
return blocks, local_converted
return content, 0
converted = 0
normalized_messages = []
for msg in messages:
if not isinstance(msg, dict):
normalized_messages.append(msg)
continue
if msg.get("role") != "user":
normalized_messages.append(msg)
continue
content = msg.get("content")
if isinstance(content, str):
normalized_content, local_converted = _normalize_text_content(content)
if local_converted > 0:
msg_copy = dict(msg)
msg_copy["content"] = normalized_content
normalized_messages.append(msg_copy)
converted += local_converted
else:
normalized_messages.append(msg)
continue
if isinstance(content, list):
new_blocks = []
local_converted = 0
for block in content:
if isinstance(block, dict) and block.get("type") == "text":
text_val = block.get("text", "")
normalized_content, block_converted = _normalize_text_content(
text_val
)
if block_converted > 0 and isinstance(normalized_content, list):
new_blocks.extend(normalized_content)
local_converted += block_converted
else:
new_blocks.append(block)
else:
new_blocks.append(block)
if local_converted > 0:
msg_copy = dict(msg)
msg_copy["content"] = new_blocks
normalized_messages.append(msg_copy)
converted += local_converted
else:
normalized_messages.append(msg)
continue
normalized_messages.append(msg)
return normalized_messages, converted
def _audit_message_payload(messages):
"""Collect payload audit info for image/base64 content."""
summary = {
"messages": len(messages) if isinstance(messages, list) else 0,
"image_blocks": 0,
"data_urls": 0,
"base64_text_blocks": 0,
"digests": [],
}
if not isinstance(messages, list):
return summary
marker_re = re.compile(r"Image\s*\(base64\):", re.IGNORECASE)
for msg in messages:
if not isinstance(msg, dict):
continue
content = msg.get("content", "")
if isinstance(content, list):
for block in content:
if not isinstance(block, dict):
continue
btype = block.get("type")
if btype == "image_url":
summary["image_blocks"] += 1
image_url = block.get("image_url", {})
if isinstance(image_url, dict):
url = image_url.get("url", "")
else:
url = image_url if isinstance(image_url, str) else ""
if isinstance(url, str) and url.startswith("data:"):
summary["data_urls"] += 1
summary["digests"].append(
_hash_text(_extract_base64_from_data_url(url))
)
elif btype == "text":
text = block.get("text", "")
if marker_re.search(text):
summary["base64_text_blocks"] += 1
parts = marker_re.split(text, maxsplit=1)
b64 = parts[1].strip() if len(parts) > 1 else text
summary["digests"].append(
_hash_text(_extract_base64_from_data_url(b64))
)
elif isinstance(content, str):
if marker_re.search(content):
summary["base64_text_blocks"] += 1
parts = marker_re.split(content, maxsplit=1)
b64 = parts[1].strip() if len(parts) > 1 else content
summary["digests"].append(
_hash_text(_extract_base64_from_data_url(b64))
)
return summary
def _log_payload_audit(stage: str, request_id: str, summary: dict):
"""Log concise in/out payload audit when image/base64 content is present."""
if not summary:
return
has_relevant = (
summary.get("image_blocks", 0) > 0
or summary.get("data_urls", 0) > 0
or summary.get("base64_text_blocks", 0) > 0
)
if not has_relevant:
return
digests_preview = summary.get("digests", [])[:4]
print(
f"[PAYLOAD_AUDIT] request_id={request_id} stage={stage} "
f"messages={summary.get('messages', 0)} image_blocks={summary.get('image_blocks', 0)} "
f"data_urls={summary.get('data_urls', 0)} base64_text={summary.get('base64_text_blocks', 0)} "
f"digests={digests_preview}",
flush=True,
)
def _looks_like_data_block(text: str) -> bool:
"""Detect large data/base64 blocks that should never be regex-normalized."""
if not isinstance(text, str):
return False
if "Image (base64):" in text:
return True
if "data:image/" in text and "base64," in text:
return True
if len(text) > 800 and re.search(r"[A-Za-z0-9+/]{600,}={0,2}", text):
return True
return False
def init_database():
"""Initialize database tables."""
with get_db() as conn:
cursor = conn.cursor()
# Endpoints table
cursor.execute("""
CREATE TABLE IF NOT EXISTS endpoints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
api_key TEXT,
endpoint_type TEXT DEFAULT 'ollama',
custom_headers TEXT,
priority INTEGER DEFAULT 0,
enabled INTEGER DEFAULT 1,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
updated_at INTEGER DEFAULT (strftime('%s', 'now'))
)
""")
# Virtual models table
cursor.execute("""
CREATE TABLE IF NOT EXISTS virtual_models (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
endpoint_id INTEGER NOT NULL,
actual_model TEXT NOT NULL,
description TEXT,
cost_per_1m_tokens_in REAL DEFAULT 0,
cost_per_1m_tokens_out REAL DEFAULT 0,
cost_per_1m_tokens_in_cached REAL DEFAULT 0,
cost_per_1m_tokens_out_cached REAL DEFAULT 0,
disable_streaming INTEGER DEFAULT 0,
force_non_streaming INTEGER DEFAULT 0,
custom_headers TEXT,
enabled INTEGER DEFAULT 1,
max_tokens INTEGER DEFAULT 0,
temperature REAL DEFAULT 0,
top_p REAL DEFAULT 1.0,
system_prompt TEXT,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
updated_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (endpoint_id) REFERENCES endpoints(id)
)
""")
# Request usage tracking table
cursor.execute("""
CREATE TABLE IF NOT EXISTS request_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
virtual_model TEXT NOT NULL,
endpoint_name TEXT,
endpoint_id INTEGER,
request_type TEXT DEFAULT 'chat',
prompt_tokens INTEGER DEFAULT 0,
completion_tokens INTEGER DEFAULT 0,
total_tokens INTEGER DEFAULT 0,
cached_input_tokens INTEGER DEFAULT 0,
cache_creation_tokens INTEGER DEFAULT 0,
cost_estimate REAL DEFAULT 0,
cost_in REAL DEFAULT 0,
cost_out REAL DEFAULT 0,
cached_cost_estimate REAL DEFAULT 0,
response_time_ms INTEGER DEFAULT 0,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (endpoint_id) REFERENCES endpoints(id)
)
""")
# Embedding usage tracking table
cursor.execute("""
CREATE TABLE IF NOT EXISTS embedding_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
virtual_model TEXT NOT NULL,
endpoint_name TEXT,
endpoint_id INTEGER,
input_tokens INTEGER DEFAULT 0,
output_tokens INTEGER DEFAULT 0,
total_tokens INTEGER DEFAULT 0,
cost_estimate REAL DEFAULT 0,
response_time_ms INTEGER DEFAULT 0,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
FOREIGN KEY (endpoint_id) REFERENCES endpoints(id)
)
""")
# Recent activity table (operational metadata only)
cursor.execute("""
CREATE TABLE IF NOT EXISTS recent_activity (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at INTEGER NOT NULL,
request_id TEXT,
method TEXT NOT NULL,
path TEXT NOT NULL,
request_type TEXT NOT NULL,
virtual_model TEXT,
actual_model TEXT,
endpoint_name TEXT,
endpoint_id INTEGER,
endpoint_type TEXT,
client_ip TEXT,
forwarded_for TEXT,
x_source TEXT,
user_agent TEXT,
stream INTEGER DEFAULT 0,
status_code INTEGER,
outcome TEXT,
response_time_ms INTEGER DEFAULT 0,
error_summary TEXT
)
""")
# Settings table
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at INTEGER DEFAULT (strftime('%s', 'now'))
)
""")
# Tool patterns table
cursor.execute("""
CREATE TABLE IF NOT EXISTS tool_patterns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
pattern_name TEXT NOT NULL UNIQUE,
pattern_type TEXT NOT NULL,
regex_pattern TEXT NOT NULL,
tool_name TEXT,
tool_name_group INTEGER,
tool_name_json_path TEXT,
tool_name_mapping TEXT,
parameter_mapping TEXT,
enabled INTEGER DEFAULT 1,
priority INTEGER DEFAULT 0,
created_at INTEGER DEFAULT (strftime('%s', 'now')),
updated_at INTEGER DEFAULT (strftime('%s', 'now'))
)
""")
# Auto-seed patterns if table is empty
cursor.execute("SELECT COUNT(*) FROM tool_patterns")
if cursor.fetchone()[0] == 0:
seed_patterns = [
(
"fence_json",
"fence",
r"```\s*(\w*)\s*\n?(.*?)```",
None,
None,
"name",
"{}",
"{}",
100,
),
(
"inline_json",
"inline",
r"\{.*?\"name\"\s*:\s*\"(\w+)\".*?\"arguments\"\s*:\s*(\{[^}]*\})",
None,
1,
None,
"{}",
"{}",
90,
),
(
"tool_use",
"xml",
r'<tool_use\s+code\s+name="(\w+)"\s*>(.*?)</tool_use>',
None,
1,
None,
"{}",
"{}",
80,
),
(
"tool_code",
"xml",
r"<tool_code>(.*?)</tool_code>",
None,
None,
"name",
"{}",
"{}",
80,
),
(
"tool_call",
"xml",
r"<tool_call>(.*?)</tool_call>",
None,
None,
"name",
"{}",
"{}",
80,
),
(
"tool_call_alt",
"bracket",
r"\[TOOL_CALL\]\s*(\{.*?\})\s*\[/TOOL_CALL\]",
None,
None,
"name",
"{}",
"{}",
85,
),
(
"tool_call_nested_xml",
"xml",
r"<tool_call>\s*<function=(\w+)>\s*<parameter=(\w+)>\s*(.*?)\s*</parameter>\s*</function>\s*</tool_call>",
None,
1,
None,
"{}",
'{"file_path":"filePath"}',
86,
),
(
"tool_call_bare_param",