-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
795 lines (677 loc) · 28.2 KB
/
Copy pathapp.py
File metadata and controls
795 lines (677 loc) · 28.2 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
from __future__ import annotations
import json
import logging
import os
import re
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, AsyncIterator, Callable
import httpx
import yaml
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from pydantic_settings import BaseSettings
from pydantic import Field
# ============================================================
# Settings (pydantic-settings: 支援 .env / env var / 預設值)
# ============================================================
class Settings(BaseSettings):
openrouter_api_key: str | None = Field(default=None, alias="OPENROUTER_API_KEY")
openrouter_base_url: str = Field(
default="https://openrouter.ai/api/v1", alias="OPENROUTER_BASE_URL"
)
router_config_path: str = Field(default="./config.yaml", alias="ROUTER_CONFIG_PATH")
router_auth_token: str | None = Field(default=None, alias="ROUTER_AUTH_TOKEN")
router_host: str = Field(default="0.0.0.0", alias="ROUTER_HOST")
router_port: int = Field(default=8000, alias="ROUTER_PORT")
http_referer: str | None = Field(default=None, alias="OPENROUTER_HTTP_REFERER")
x_title: str | None = Field(default="API Router", alias="OPENROUTER_X_TITLE")
upstream_auth_mode: str = Field(default="service", alias="UPSTREAM_AUTH_MODE")
log_input: bool = Field(default=False, alias="LOG_INPUT")
log_output: bool = Field(default=False, alias="LOG_OUTPUT")
log_stream_headers: bool = Field(default=False, alias="LOG_STREAM_HEADERS")
model_config = {"env_file": ".env", "extra": "ignore", "populate_by_name": True}
settings = Settings()
# ============================================================
# Config loading (支援 ${ENV_VAR} 替換)
# ============================================================
def load_config(path: str) -> dict[str, Any]:
p = Path(path)
if not p.exists():
raise RuntimeError(f"Config file not found: {p}")
raw = p.read_text(encoding="utf-8")
def _replace_env(match: re.Match) -> str:
return os.environ.get(match.group(1), "")
raw = re.sub(r"\$\{(\w+)\}", _replace_env, raw)
return yaml.safe_load(raw) or {}
# ============================================================
# Helpers
# ============================================================
def _clone(value: Any) -> Any:
return json.loads(json.dumps(value))
def deep_merge(target: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
for key, value in patch.items():
if key in target and isinstance(target[key], dict) and isinstance(value, dict):
deep_merge(target[key], value)
else:
target[key] = _clone(value)
return target
def set_by_path(payload: dict[str, Any], path: str, value: Any) -> None:
parts = path.split(".")
cur: Any = payload
for part in parts[:-1]:
if part not in cur or not isinstance(cur[part], dict):
cur[part] = {}
cur = cur[part]
cur[parts[-1]] = _clone(value)
def append_by_path(payload: dict[str, Any], path: str, value: Any) -> None:
parts = path.split(".")
cur: Any = payload
for part in parts[:-1]:
if part not in cur or not isinstance(cur[part], dict):
cur[part] = {}
cur = cur[part]
key = parts[-1]
if not isinstance(cur.get(key), list):
cur[key] = []
cur[key].append(_clone(value))
def _parse_optional_int(value: Any) -> int | None:
if value is None:
return None
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, str):
s = value.strip()
if not s:
return None
try:
return int(s)
except ValueError:
return None
return None
# ============================================================
# Logging
# ============================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
logger = logging.getLogger("api-router")
def _sanitize_headers(headers_obj: Any) -> dict[str, str]:
sensitive = {"authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key"}
out: dict[str, str] = {}
try:
items = headers_obj.items()
except Exception:
return out
for k, v in items:
key = str(k)
if key.lower() in sensitive:
continue
out[key] = str(v)
return out
def _log_stream_headers(upstream_headers: Any, downstream_headers: Any, upstream_status: int | None = None) -> None:
if not settings.log_stream_headers:
return
payload = {
"upstream_status": upstream_status,
"upstream": _sanitize_headers(upstream_headers),
"downstream": _sanitize_headers(downstream_headers),
}
text = json.dumps(payload, ensure_ascii=False)
if len(text) > 4000:
text = text[:4000] + "...(truncated)"
logger.info(f"[STREAM HEADERS] {text}")
def _pretty_log_input(body: dict[str, Any]) -> None:
logger.info("=" * 60)
logger.info("[INPUT] Request Body:")
logger.info(json.dumps(body, ensure_ascii=False, indent=2))
def _pretty_log_output(body: dict[str, Any]) -> None:
logger.info("=" * 60)
logger.info("[OUTPUT] Response Body:")
logger.info(json.dumps(body, ensure_ascii=False, indent=2))
logger.info("=" * 60)
# ============================================================
# Reasoning content cache(多輪對話的思考鏈補全)
# ============================================================
REASONING_CACHE: deque[dict[str, str]] = deque(maxlen=200)
def cache_reasoning_content(reasoning: str, content: str | None = None) -> None:
REASONING_CACHE.append({"content": content or "", "reasoning": reasoning})
logger.info(
f"Cached reasoning_content ({len(reasoning)} chars) [{len(REASONING_CACHE)} in queue]"
)
def restore_reasoning_content(body: dict[str, Any]) -> dict[str, Any]:
messages: list[dict[str, Any]] = body.get("messages", [])
matched_count = 0
fifo_count = 0
placeholder_count = 0
for msg in messages:
if msg.get("role") != "assistant":
continue
rc = msg.get("reasoning_content")
if rc is not None and rc != "":
continue
cached = None
content = msg.get("content")
if isinstance(content, str) and content:
for item in REASONING_CACHE:
if item.get("content") == content:
cached = item
break
if cached is not None:
REASONING_CACHE.remove(cached)
msg["reasoning_content"] = cached.get("reasoning") or " "
matched_count += 1
elif REASONING_CACHE:
item = REASONING_CACHE.popleft()
msg["reasoning_content"] = item.get("reasoning") or " "
fifo_count += 1
else:
msg["reasoning_content"] = " "
placeholder_count += 1
if matched_count or fifo_count or placeholder_count:
parts = []
if matched_count:
parts.append(f"{matched_count} matched")
if fifo_count:
parts.append(f"{fifo_count} FIFO")
if placeholder_count:
parts.append(f"{placeholder_count} placeholder")
logger.info(f"Restored reasoning_content: {', '.join(parts)}")
return body
# ============================================================
# Transformer system (composable middleware)
# ============================================================
@dataclass(frozen=True)
class Context:
original_model: str
headers: dict[str, str]
class Transformer:
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
return payload
class SetModel(Transformer):
def __init__(self, model: str) -> None:
self.model = model
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
payload["model"] = self.model
return payload
class Merge(Transformer):
def __init__(self, payload: dict[str, Any] | None = None) -> None:
self.patch = payload or {}
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
deep_merge(payload, self.patch)
return payload
class Strip(Transformer):
def __init__(self, keys: list[str] | None = None) -> None:
self.keys = keys or []
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
for k in self.keys:
payload.pop(k, None)
return payload
class SetPath(Transformer):
def __init__(self, path: str, value: Any = None) -> None:
self.path = path
self.value = value
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
set_by_path(payload, self.path, self.value)
return payload
class AppendPath(Transformer):
def __init__(self, path: str, value: Any = None) -> None:
self.path = path
self.value = value
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
append_by_path(payload, self.path, self.value)
return payload
class Reasoning(Transformer):
"""
注入 / 合併思考模式參數。支援三種 provider schema:
- provider=openai (預設): 寫入 {"reasoning": {"effort": "high"}}
可選 effort | max_tokens | enabled | exclude
- provider=deepseek: 寫入 {"thinking": {"type": "enabled"}} + "reasoning_effort"
支援 effort
- provider=anthropic: 寫入 {"thinking": {"type": "enabled", "budget_tokens": N}}
支援 max_tokens (映射為 budget_tokens)
skip_if_present=True: 若請求已自帶 reasoning/thinking 則完全保留呼叫方設定
override=True: 強制覆蓋已存在的同名字段
"""
def __init__(
self,
provider: str = "openai",
enabled: bool | None = None,
effort: str | None = None,
max_tokens: int | None = None,
exclude: bool | None = None,
override: bool = False,
skip_if_present: bool = False,
) -> None:
self.provider = provider
self.effort = effort
self.max_tokens = max_tokens
self.enabled = enabled
self.exclude = exclude
self.override = override
self.skip_if_present = skip_if_present
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
if self.provider == "openai":
return self._apply_openai(payload)
elif self.provider == "deepseek":
return self._apply_deepseek(payload)
elif self.provider == "anthropic":
return self._apply_anthropic(payload)
return payload
def _apply_openai(self, payload: dict[str, Any]) -> dict[str, Any]:
existing = payload.get("reasoning")
if existing is not None and not isinstance(existing, dict):
existing = {}
if existing and self.skip_if_present:
return payload
reasoning: dict[str, Any] = dict(existing or {})
fields: dict[str, Any] = {}
if self.effort is not None:
fields["effort"] = self.effort
if self.max_tokens is not None:
fields["max_tokens"] = self.max_tokens
if self.enabled is not None:
fields["enabled"] = self.enabled
if self.exclude is not None:
fields["exclude"] = self.exclude
for key, value in fields.items():
if self.override or key not in reasoning:
reasoning[key] = value
if reasoning:
payload["reasoning"] = reasoning
return payload
def _apply_deepseek(self, payload: dict[str, Any]) -> dict[str, Any]:
existing = payload.get("thinking")
if existing and self.skip_if_present:
return payload
payload["thinking"] = {"type": "enabled"}
if self.effort and ("reasoning_effort" not in payload or self.override):
payload["reasoning_effort"] = self.effort
return payload
def _apply_anthropic(self, payload: dict[str, Any]) -> dict[str, Any]:
existing = payload.get("thinking")
if existing and self.skip_if_present:
return payload
thinking: dict[str, Any] = {"type": "enabled"}
if self.max_tokens is not None:
thinking["budget_tokens"] = self.max_tokens
payload["thinking"] = thinking
return payload
class Fusion(Transformer):
"""
Fusion 融合模式(beta,格式可能變更)。支援三種入口:
- mode=plugin: model → "openrouter/fusion" + plugins:[{id:fusion, ...}]
- mode=alias: 僅 set model → "openrouter/fusion"(使用官方預設 Quality preset)
- mode=tool: tools:[{type:"openrouter:fusion", parameters:{...}}]
judge: 裁判模型
analysis_models: 專家面板模型列表
preset: 官方預設名稱
"""
def __init__(
self,
mode: str = "plugin",
judge: str | None = None,
analysis_models: list[str] | None = None,
preset: str | None = None,
force: bool = False,
extra: dict[str, Any] | None = None,
) -> None:
self.mode = mode
self.judge = judge
self.analysis_models = analysis_models
self.preset = preset
self.force = force
self.extra = extra or {}
def apply(self, payload: dict[str, Any], ctx: Context) -> dict[str, Any]:
if self.mode != "tool":
payload["model"] = "openrouter/fusion"
params: dict[str, Any] = {}
if self.judge:
params["model"] = self.judge
if self.analysis_models:
params["analysis_models"] = self.analysis_models
if self.preset:
params["preset"] = self.preset
if self.mode == "alias":
return payload
if self.mode == "tool":
tool: dict[str, Any] = {"type": "openrouter:fusion"}
if params:
tool["parameters"] = params
deep_merge(tool, self.extra)
payload.setdefault("tools", []).append(tool)
if self.force:
payload["tool_choice"] = "required"
return payload
plugin: dict[str, Any] = {"id": "fusion", **params}
deep_merge(plugin, self.extra)
payload.setdefault("plugins", []).append(plugin)
return payload
Builder = Callable[[dict[str, Any]], Transformer]
TRANSFORMER_BUILDERS: dict[str, Builder] = {
"set_model": lambda c: SetModel(c["model"]),
"merge": lambda c: Merge(c.get("payload", {})),
"strip": lambda c: Strip(c.get("keys", [])),
"set_path": lambda c: SetPath(c["path"], c.get("value")),
"append_path": lambda c: AppendPath(c["path"], c.get("value")),
"reasoning": lambda c: Reasoning(
provider=c.get("provider", "openai"),
enabled=c.get("enabled"),
effort=c.get("effort"),
max_tokens=c.get("max_tokens"),
exclude=c.get("exclude"),
override=c.get("override", False),
skip_if_present=c.get("skip_if_present", False),
),
"fusion": lambda c: Fusion(
mode=c.get("mode", "plugin"),
judge=c.get("judge"),
analysis_models=c.get("analysis_models"),
preset=c.get("preset"),
force=c.get("force", False),
extra=c.get("extra"),
),
}
# ============================================================
# ModelRegistry — 配置驅動路由核心(零 if/else)
# ============================================================
class ModelRegistry:
def __init__(self, config: dict[str, Any]) -> None:
self.defaults: dict[str, Any] = config.get("defaults", {})
self.passthrough: dict[str, Any] = config.get("passthrough", {})
self._models: dict[str, dict[str, Any]] = config.get("models") or {}
self._compiled: dict[str, tuple[dict[str, Any], list[Transformer]]] = {}
self._compile_all()
def _compile_all(self) -> None:
for model_id, cfg in self._models.items():
pipeline: list[Transformer] = []
for step in cfg.get("transformers", []):
t_use = step.get("use") or step.get("type")
builder = TRANSFORMER_BUILDERS.get(t_use)
if builder is None:
raise RuntimeError(
f"Unknown transformer '{t_use}' in model '{model_id}'. "
f"Available: {list(TRANSFORMER_BUILDERS.keys())}"
)
pipeline.append(builder(step))
self._compiled[model_id] = (cfg, pipeline)
def allow_unknown(self) -> bool:
return bool(self.passthrough.get("allow_unknown_models", True))
def list_models(self) -> list[dict[str, Any]]:
default_upstream = self.defaults.get("default_model_upstream")
return [
{
"id": mid,
"object": "model",
"created": 0,
"owned_by": "api-router",
"description": cfg.get("description", ""),
}
for mid, (cfg, _) in self._compiled.items()
]
def rewrite(self, payload: dict[str, Any], headers: dict[str, str]) -> dict[str, Any]:
original: str | None = payload.get("model")
if not original:
raise HTTPException(status_code=400, detail="Missing required field: model")
entry = self._compiled.get(original)
if entry is None:
if self.allow_unknown():
return payload
raise HTTPException(
status_code=404,
detail=f"Unknown model: '{original}'. Available: {list(self._compiled.keys())}",
)
cfg, pipeline = entry
ctx = Context(original_model=original, headers=headers)
out = _clone(payload)
if cfg.get("upstream"):
out["model"] = cfg["upstream"]
for t in pipeline:
out = t.apply(out, ctx)
out.pop("__extra_headers__", None)
return out
# ============================================================
# Upstream proxy(httpx async: 支援 streaming / non-streaming)
# ============================================================
class UpstreamProxy:
def __init__(self, base_url: str, api_key: str | None, registry: ModelRegistry) -> None:
base = base_url.rstrip("/")
self.base_url = base
self.api_key = api_key
self.registry = registry
self.client: httpx.AsyncClient | None = None
async def start(self) -> None:
self.client = httpx.AsyncClient(timeout=httpx.Timeout(None, connect=10.0))
async def close(self) -> None:
if self.client is not None:
await self.client.aclose()
self.client = None
def _upstream_headers(self, incoming_auth: str | None) -> dict[str, str]:
headers: dict[str, str] = {
"Content-Type": "application/json",
"Accept": "application/json",
}
if settings.upstream_auth_mode == "passthrough":
if not incoming_auth:
raise HTTPException(status_code=401, detail="Missing Authorization header")
headers["Authorization"] = incoming_auth
else:
if not self.api_key:
raise HTTPException(status_code=500, detail="OPENROUTER_API_KEY not configured")
headers["Authorization"] = f"Bearer {self.api_key}"
if settings.http_referer:
headers["HTTP-Referer"] = settings.http_referer
if settings.x_title:
headers["X-Title"] = settings.x_title
for k, v in self.registry.defaults.get("upstream_headers", {}).items():
headers[k] = str(v)
return headers
async def handle(
self,
payload: dict[str, Any],
incoming_headers: dict[str, str],
incoming_auth: str | None,
) -> Response:
assert self.client is not None
rewritten = self.registry.rewrite(payload, incoming_headers)
url = f"{self.base_url}/chat/completions"
upstream_headers = self._upstream_headers(incoming_auth)
if rewritten.get("stream") is True:
return StreamingResponse(
self._stream(url, upstream_headers, rewritten),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
resp = await self.client.post(url, headers=upstream_headers, json=rewritten)
self._cache_from_json_response(resp)
return Response(
content=resp.content,
status_code=resp.status_code,
headers={
k: v
for k, v in resp.headers.items()
if k.lower() not in {"content-encoding", "content-length", "transfer-encoding", "connection"}
},
media_type=resp.headers.get("content-type", "application/json"),
)
def _cache_from_json_response(self, resp: httpx.Response) -> None:
try:
data = resp.json()
msg = data.get("choices", [{}])[0].get("message", {})
rc = msg.get("reasoning_content")
if rc:
cache_reasoning_content(rc, msg.get("content"))
if settings.log_output:
_pretty_log_output(data)
except Exception:
if settings.log_output:
logger.info(f"[OUTPUT] Non-JSON response ({len(resp.content)} bytes)")
async def _stream(
self, url: str, headers: dict[str, str], payload: dict[str, Any]
) -> AsyncIterator[bytes]:
assert self.client is not None
acc_content: list[str] = []
acc_reasoning: list[str] = []
try:
async with self.client.stream("POST", url, headers=headers, json=payload) as resp:
if resp.status_code >= 400:
body = await resp.aread()
yield body
return
_log_stream_headers(resp.headers, {}, resp.status_code)
async for chunk in resp.aiter_bytes():
if chunk:
self._attempt_cache_from_chunk(chunk, acc_content, acc_reasoning)
yield chunk
except Exception as e:
logger.error(f"Stream error: {e}")
yield f'data: {{"error": "{e}"}}\n\n'.encode()
finally:
full_content = "".join(acc_content).strip()
full_reasoning = "".join(acc_reasoning).strip()
if full_reasoning:
cache_reasoning_content(full_reasoning, full_content)
if settings.log_output:
if full_reasoning:
logger.info("-" * 40)
logger.info(f"[STREAM OUTPUT] reasoning_content ({len(full_reasoning)} chars):")
logger.info(full_reasoning[:2000])
if full_content:
logger.info("-" * 40)
logger.info(f"[STREAM OUTPUT] content ({len(full_content)} chars):")
logger.info(full_content[:2000])
logger.info("=" * 60)
def _attempt_cache_from_chunk(
self, chunk: bytes, acc_content: list[str], acc_reasoning: list[str]
) -> None:
try:
text = chunk.decode(errors="ignore")
for line in text.split("\n"):
line = line.strip()
if not line.startswith("data:"):
continue
data_str = line[5:].strip()
if data_str == "[DONE]" or not data_str:
continue
try:
data = json.loads(data_str)
except json.JSONDecodeError:
continue
delta = data.get("choices", [{}])[0].get("delta", {})
c = delta.get("content")
if c is not None:
acc_content.append(str(c))
rc = delta.get("reasoning_content")
if rc is not None:
acc_reasoning.append(str(rc))
except Exception:
pass
# ============================================================
# FastAPI surface
# ============================================================
router_config = load_config(settings.router_config_path)
model_registry = ModelRegistry(router_config)
upstream_proxy = UpstreamProxy(
base_url=settings.openrouter_base_url,
api_key=settings.openrouter_api_key,
registry=model_registry,
)
app = FastAPI(title="Config-Driven API Router", version="2.0.0")
def _verify_auth(authorization: str | None) -> None:
if settings.router_auth_token and authorization != f"Bearer {settings.router_auth_token}":
raise HTTPException(status_code=401, detail="Unauthorized")
def _normalize_path(path: str) -> str:
chat_completions = "/v1/chat/completions"
full_url_match = re.match(r"https?://[^/]+(/.*)?", path)
if full_url_match:
extracted = full_url_match.group(1) or "/"
logger.info(f"Path stripped domain: {path} -> {extracted}")
path = extracted
normalized = path.strip("/")
if normalized in ("v1", ""):
logger.info(f"Path rewritten: {path} -> {chat_completions}")
return chat_completions
if not normalized.startswith("/"):
normalized = "/" + normalized
return normalized
@app.on_event("startup")
async def _startup() -> None:
await upstream_proxy.start()
logger.info("=" * 50)
logger.info(f"API Router starting at http://{settings.router_host}:{settings.router_port}")
logger.info(f"Upstream: {settings.openrouter_base_url}")
logger.info(f"Registered models: {list(model_registry._compiled.keys())}")
logger.info(f"Passthrough unknown models: {model_registry.allow_unknown()}")
logger.info(f"Log input: {'ON' if settings.log_input else 'OFF'}")
logger.info(f"Log output: {'ON' if settings.log_output else 'OFF'}")
logger.info("=" * 50)
@app.on_event("shutdown")
async def _shutdown() -> None:
await upstream_proxy.close()
@app.get("/health")
async def health() -> dict[str, str]:
return {"status": "ok"}
@app.get("/v1/models")
async def list_models() -> JSONResponse:
return JSONResponse(content={"object": "list", "data": model_registry.list_models()})
@app.post("/v1/chat/completions")
async def chat_completions(
request: Request,
authorization: str | None = Header(default=None),
) -> Response:
_verify_auth(authorization)
try:
payload: dict[str, Any] = await request.json()
except Exception:
raise HTTPException(status_code=400, detail="Invalid JSON body")
if settings.log_input:
_pretty_log_input(payload)
payload = restore_reasoning_content(payload)
incoming_headers: dict[str, str] = {k.lower(): v for k, v in request.headers.items()}
return await upstream_proxy.handle(payload, incoming_headers, authorization)
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
async def catch_all(
path: str,
request: Request,
authorization: str | None = Header(default=None),
) -> Response:
_verify_auth(authorization)
normalized = _normalize_path(path)
url = f"{settings.openrouter_base_url.rstrip('/')}{normalized}"
assert upstream_proxy.client is not None
headers = upstream_proxy._upstream_headers(authorization)
body_raw = await request.body()
logger.info(f"[PASSTHROUGH] {request.method} {url}")
if request.method in ("POST", "PUT", "PATCH") and body_raw:
resp = await upstream_proxy.client.request(
method=request.method, url=url, headers=headers, content=body_raw
)
else:
resp = await upstream_proxy.client.request(
method=request.method, url=url, headers=headers, params=dict(request.query_params)
)
return Response(
content=resp.content,
status_code=resp.status_code,
headers={
k: v
for k, v in resp.headers.items()
if k.lower() not in {"content-encoding", "content-length", "transfer-encoding", "connection"}
},
media_type=resp.headers.get("content-type", "application/json"),
)
# ============================================================
# Main
# ============================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app:app",
host=settings.router_host,
port=settings.router_port,
log_level="info",
)