File size: 2,441 Bytes
59db361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43ec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59db361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""OpenRouter model catalog: tool-capable models only (design doc: 'any
OpenRouter model' is only true of tool-capable ones)."""
from __future__ import annotations

import httpx

# Verified live against https://openrouter.ai/api/v1/models on 2026-08-05:
# both ids exist, pricing shapes match (string USD-per-token), tool-capable.
PINNED_MODELS = [
    {"id": "anthropic/claude-sonnet-4.5", "name": "Claude Sonnet 4.5 (pinned)",
     "prompt_price": 0.0, "completion_price": 0.0},
    {"id": "openai/gpt-4.1-mini", "name": "GPT-4.1 mini (pinned)",
     "prompt_price": 0.0, "completion_price": 0.0},
]


def fetch_key_headroom(base_url: str, api_key: str,
                       transport: httpx.BaseTransport | None = None,
                       ) -> float | None:
    """Remaining credit on this OpenRouter key (GET /key), or None when
    unknowable — no key, endpoint error, or an uncapped key. None means
    "don't warn", never "zero left": the estimate must fail open."""
    if not api_key:
        return None
    try:
        with httpx.Client(base_url=base_url, timeout=10.0, transport=transport,
                          headers={"Authorization": f"Bearer {api_key}"}
                          ) as client:
            resp = client.get("/key")
            resp.raise_for_status()
            data = resp.json().get("data")
    except (httpx.HTTPError, ValueError):
        return None
    if not isinstance(data, dict):
        return None
    remaining = data.get("limit_remaining")
    if remaining is None and data.get("limit") is not None:
        remaining = float(data["limit"]) - float(data.get("usage") or 0.0)
    return float(remaining) if remaining is not None else None


def fetch_models(base_url: str,
                 transport: httpx.BaseTransport | None = None) -> list[dict]:
    with httpx.Client(base_url=base_url, timeout=30.0,
                      transport=transport) as client:
        resp = client.get("/models")
        resp.raise_for_status()
    out = []
    for m in resp.json().get("data", []):
        if "tools" not in (m.get("supported_parameters") or []):
            continue
        pricing = m.get("pricing") or {}
        out.append({"id": m["id"], "name": m.get("name", m["id"]),
                    "prompt_price": float(pricing.get("prompt", 0) or 0),
                    "completion_price": float(pricing.get("completion", 0) or 0)})
    return sorted(out, key=lambda m: m["id"])