rexlib-py 0.9.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rexlib/__init__.py +75 -0
- rexlib/cli/__init__.py +44 -0
- rexlib/cli/commands.py +99 -0
- rexlib/cli/console.py +83 -0
- rexlib/cli/options.py +47 -0
- rexlib/cli/permissions.py +174 -0
- rexlib/cli/render.py +78 -0
- rexlib/cli/repl.py +97 -0
- rexlib/cli/session.py +99 -0
- rexlib/container/__init__.py +33 -0
- rexlib/container/detect.py +151 -0
- rexlib/container/model.py +111 -0
- rexlib/container/probe.py +191 -0
- rexlib/container/resolve.py +151 -0
- rexlib/gateway/__init__.py +56 -0
- rexlib/gateway/attempts.py +51 -0
- rexlib/gateway/audit.py +173 -0
- rexlib/gateway/config.py +383 -0
- rexlib/gateway/costs.py +157 -0
- rexlib/gateway/keys.py +46 -0
- rexlib/gateway/presets.py +59 -0
- rexlib/gateway/prices.py +134 -0
- rexlib/gateway/router.py +391 -0
- rexlib/gateway/stream.py +224 -0
- rexlib/loop/__init__.py +63 -0
- rexlib/loop/calls.py +220 -0
- rexlib/loop/core.py +249 -0
- rexlib/loop/options.py +149 -0
- rexlib/loop/stream.py +88 -0
- rexlib/messages.py +221 -0
- rexlib/providers/__init__.py +11 -0
- rexlib/providers/anthropic.py +108 -0
- rexlib/providers/base.py +53 -0
- rexlib/providers/errors.py +191 -0
- rexlib/providers/http.py +124 -0
- rexlib/providers/openai.py +148 -0
- rexlib/providers/transport.py +163 -0
- rexlib/py.typed +0 -0
- rexlib/storage/__init__.py +30 -0
- rexlib/storage/base.py +144 -0
- rexlib/storage/contract.py +262 -0
- rexlib/storage/registry.py +49 -0
- rexlib/storage/sqlite.py +219 -0
- rexlib/testing.py +160 -0
- rexlib/tools/__init__.py +12 -0
- rexlib/tools/base.py +116 -0
- rexlib/tools/executor.py +105 -0
- rexlib/tools/function_tool.py +168 -0
- rexlib/tools/registry.py +66 -0
- rexlib/wire/__init__.py +6 -0
- rexlib/wire/anthropic_messages.py +300 -0
- rexlib/wire/openai_chat.py +134 -0
- rexlib/wire/sse.py +85 -0
- rexlib_py-0.9.0a1.dist-info/METADATA +251 -0
- rexlib_py-0.9.0a1.dist-info/RECORD +58 -0
- rexlib_py-0.9.0a1.dist-info/WHEEL +5 -0
- rexlib_py-0.9.0a1.dist-info/licenses/LICENSE +21 -0
- rexlib_py-0.9.0a1.dist-info/top_level.txt +1 -0
rexlib/gateway/prices.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
3
|
+
# AI models: claude-opus-5-5
|
|
4
|
+
# Licensed under MIT License
|
|
5
|
+
"""``ModelPrices``: the price table of the gateway, one entry per model id and one per class.
|
|
6
|
+
|
|
7
|
+
prices = ModelPrices.from_config(config) # the table the Gateway charges with (gateway.prices)
|
|
8
|
+
prices.price("sonnet") # Price(input=3.0, output=15.0, ...) or None (unpriced)
|
|
9
|
+
prices.price("large") # the highest member price, field by field
|
|
10
|
+
rexlib.run(gateway.provider("large"), messages,
|
|
11
|
+
options=RunOptions(limits=Limits(cost_cap_usd=0.5), prices=prices.for_target("large")))
|
|
12
|
+
|
|
13
|
+
A class's entry is the highest price of its members, field by field (input, output, cache read, cache write), so
|
|
14
|
+
a loop's cost limit can check a conservative bound before it knows which model of the class serves (rexlib design
|
|
15
|
+
2.1, "Costs"). A class with an unpriced member has no bound (``price`` returns None, ``for_target`` refuses it).
|
|
16
|
+
``from_config`` also knows each entry's upstream model name (the name an answer may carry); when several entries
|
|
17
|
+
share one, their highest price is used.
|
|
18
|
+
|
|
19
|
+
``ModelPrices`` and ``TargetPrice`` are price tables for ``RunOptions.prices`` (the ``rexlib.loop.PriceTable``
|
|
20
|
+
protocol: ``cost(usage, model) -> USD``). ``cost`` refuses an unknown or unpriced name with a ``ValueError``
|
|
21
|
+
rather than count 0 USD (a cost limit must not have a hole). The table is read-only.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from types import MappingProxyType
|
|
29
|
+
|
|
30
|
+
from rexlib.messages import Usage
|
|
31
|
+
|
|
32
|
+
from .config import GatewayConfig, Price
|
|
33
|
+
from .costs import cost_usd
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True, slots=True)
|
|
37
|
+
class TargetPrice:
|
|
38
|
+
"""The price of one target (a model id, or a class at its highest member price); ``cost`` ignores the model
|
|
39
|
+
name an answer carries and always charges this price (the conservative bound for a loop)."""
|
|
40
|
+
|
|
41
|
+
target: str
|
|
42
|
+
price: Price
|
|
43
|
+
|
|
44
|
+
def cost(self, usage: Usage, model: str | None = None) -> float:
|
|
45
|
+
"""USD of ``usage`` at this target's price."""
|
|
46
|
+
return cost_usd(self.price, usage)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ModelPrices:
|
|
50
|
+
"""Read-only price table: ``models`` (model id -> ``Price`` or None = unpriced), ``classes`` (class name ->
|
|
51
|
+
member model ids), ``aliases`` (another name, e.g. an upstream model name -> model ids)."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, models: Mapping[str, Price | None], classes: Mapping[str, Sequence[str]] | None = None, *,
|
|
54
|
+
aliases: Mapping[str, Sequence[str]] | None = None) -> None:
|
|
55
|
+
for model_id, price in models.items():
|
|
56
|
+
if not isinstance(model_id, str) or not (price is None or isinstance(price, Price)):
|
|
57
|
+
raise TypeError("ModelPrices models: model id (str) -> Price or None")
|
|
58
|
+
self._models: Mapping[str, Price | None] = MappingProxyType(dict(models))
|
|
59
|
+
self._classes = MappingProxyType(_members(classes or {}, self._models, "class"))
|
|
60
|
+
self._aliases = MappingProxyType(_members(aliases or {}, self._models, "alias"))
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def from_config(cls, config: GatewayConfig) -> ModelPrices:
|
|
64
|
+
"""The table of a ``GatewayConfig``: each model's ``price``, each class's members, upstream names."""
|
|
65
|
+
upstream: dict[str, list[str]] = {}
|
|
66
|
+
for model_id, model in config.models.items():
|
|
67
|
+
upstream.setdefault(model.model, []).append(model_id)
|
|
68
|
+
return cls({m: e.price for m, e in config.models.items()},
|
|
69
|
+
{n: c.models for n, c in config.classes.items()}, aliases=upstream)
|
|
70
|
+
|
|
71
|
+
def __repr__(self) -> str:
|
|
72
|
+
return f"ModelPrices(models={list(self._models)!r}, classes={list(self._classes)!r})"
|
|
73
|
+
|
|
74
|
+
def __contains__(self, name: object) -> bool:
|
|
75
|
+
return name in self._models or name in self._classes or name in self._aliases
|
|
76
|
+
|
|
77
|
+
def names(self) -> tuple[str, ...]:
|
|
78
|
+
"""The model ids, then the class names (the aliases are not listed)."""
|
|
79
|
+
return (*self._models, *self._classes)
|
|
80
|
+
|
|
81
|
+
def price(self, name: str) -> Price | None:
|
|
82
|
+
"""The ``Price`` of a model id, a class (its highest member price, field by field) or an alias; a name that
|
|
83
|
+
is several of these (a model id that is also another entry's upstream name) gets the highest price of all
|
|
84
|
+
the entries it names. None when any of them is unpriced; ``ValueError`` for an unknown name."""
|
|
85
|
+
members = {name} if name in self._models else set()
|
|
86
|
+
members.update(self._classes.get(name, ()), self._aliases.get(name, ()))
|
|
87
|
+
if not members:
|
|
88
|
+
raise ValueError(f"no price entry for {_show(name)}; known: {', '.join(self.names())}")
|
|
89
|
+
return highest(self._models[m] for m in sorted(members))
|
|
90
|
+
|
|
91
|
+
def cost(self, usage: Usage, model: str | None) -> float:
|
|
92
|
+
"""USD of ``usage`` at the price of ``model`` (a model id, class or alias); ``ValueError`` when the name is
|
|
93
|
+
missing, unknown or unpriced."""
|
|
94
|
+
if model is None:
|
|
95
|
+
raise ValueError("ModelPrices.cost needs a model name (set RunOptions.model, or use for_target)")
|
|
96
|
+
return cost_usd(self._priced(model), usage)
|
|
97
|
+
|
|
98
|
+
def for_target(self, target: str) -> TargetPrice:
|
|
99
|
+
"""The fixed price of ``target`` for ``RunOptions.prices``; ``ValueError`` when it is unknown or has no
|
|
100
|
+
price (an unpriced model, or a class with an unpriced member)."""
|
|
101
|
+
return TargetPrice(target, self._priced(target))
|
|
102
|
+
|
|
103
|
+
def _priced(self, name: str) -> Price:
|
|
104
|
+
price = self.price(name)
|
|
105
|
+
if price is None:
|
|
106
|
+
raise ValueError(f"{_show(name)} has no price (a model without a price, or a class with one)")
|
|
107
|
+
return price
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def highest(prices: Iterable[Price | None]) -> Price | None:
|
|
111
|
+
"""The highest of ``prices`` field by field; None when any of them is None (or there is none)."""
|
|
112
|
+
known = list(prices)
|
|
113
|
+
if not known or any(p is None for p in known):
|
|
114
|
+
return None
|
|
115
|
+
fields = [p for p in known if p is not None]
|
|
116
|
+
return Price(max(p.input for p in fields), max(p.output for p in fields),
|
|
117
|
+
max(p.cache_read for p in fields), max(p.cache_write for p in fields))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _members(table: Mapping[str, Sequence[str]], models: Mapping[str, Price | None],
|
|
121
|
+
what: str) -> dict[str, tuple[str, ...]]:
|
|
122
|
+
checked: dict[str, tuple[str, ...]] = {}
|
|
123
|
+
for name, members in table.items():
|
|
124
|
+
found = (members,) if isinstance(members, str) else tuple(members)
|
|
125
|
+
unknown = [m for m in found if m not in models]
|
|
126
|
+
if not isinstance(name, str) or not found or unknown:
|
|
127
|
+
raise ValueError(f"ModelPrices {what} {_show(name)} must list known model ids")
|
|
128
|
+
checked[name] = found
|
|
129
|
+
return checked
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _show(name: object) -> str:
|
|
133
|
+
text = str(name)
|
|
134
|
+
return repr(text if len(text) <= 40 else text[:40] + "...")
|
rexlib/gateway/router.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
3
|
+
# AI models: claude-opus-5-5
|
|
4
|
+
# Licensed under MIT License
|
|
5
|
+
"""``Gateway``: a class name (or a model id) -> the model that serves it, with fallback, cooldown and daily caps.
|
|
6
|
+
|
|
7
|
+
gateway = Gateway(config, GatewayOptions(storage=open_storage("sqlite:///~/.rex/rex.db")))
|
|
8
|
+
answer = gateway.complete("large", ChatRequest([ChatMessage.user("hi")]))
|
|
9
|
+
result = rexlib.run(gateway.provider("large"), messages) # any Provider consumer
|
|
10
|
+
gateway.spent_today("large") # USD since local midnight
|
|
11
|
+
|
|
12
|
+
Routing (rexlib design 2.1; LiteLLM Router model groups, fallbacks and cooldowns): a class is an ordered list of
|
|
13
|
+
model ids, primary first. A call tries the models of the class that are not cooling down, in order; when every
|
|
14
|
+
usable model is cooling down, all of them are tried in order. A model whose ``key_env`` variable is not set at
|
|
15
|
+
call time is skipped (no cooldown; set the variable and the next call uses it); when no model of the target has
|
|
16
|
+
its key, the call fails with a ``ProviderError`` of kind ``auth`` naming the models and the variables (never a
|
|
17
|
+
value). A target that is a model id uses that model alone: it is refused when ANY capped class listing it has
|
|
18
|
+
spent its cap, and charged to the first capped class listing it, else to the first class listing it.
|
|
19
|
+
|
|
20
|
+
Fallback on retryable errors only (``ProviderError.retryable``: connect errors, timeouts, 408, 429, 5xx including
|
|
21
|
+
Anthropic's 529): the model cools down for ``GatewayConfig.cooldown`` seconds (or the server's ``Retry-After``
|
|
22
|
+
when longer; a shorter later cooldown never cuts an earlier longer one) on the monotonic clock, and the next model
|
|
23
|
+
is tried, each model at most once per call. No fallback on 400, 401/403, TLS
|
|
24
|
+
failures or an unparsable answer: they surface at once. When every model failed, the ``ProviderError`` names each
|
|
25
|
+
model with its error kind and keeps the last error's kind, status and ``Retry-After``.
|
|
26
|
+
|
|
27
|
+
Costs: before each call the class's soft daily cap (``daily_cap_usd``) is checked against
|
|
28
|
+
``Storage.spent(class, since=local midnight)`` in the ``GatewayConfig.timezone`` zone (``CostCapExceeded``);
|
|
29
|
+
after a successful call ``Storage.record_cost`` gets ``{scope: class, usd, ts, model, target, input_tokens,
|
|
30
|
+
output_tokens, cache_read_tokens, cache_write_tokens, estimated, priced}``, the USD from the model's ``Price``
|
|
31
|
+
(USD per million tokens) and the answer's usage (estimated from the characters when the answer has none). A
|
|
32
|
+
model without a price is charged 0 USD (``priced: false``); a class with a daily cap must price all its models.
|
|
33
|
+
Without ``GatewayOptions.storage`` the gateway keeps an in-memory SQLite ledger of its own (gone at exit; closed
|
|
34
|
+
by ``close()``; ``notice`` warns when a capped class runs on it). Accounting fails closed: a ``StorageError``
|
|
35
|
+
while reading what was spent (before dispatch, nothing sent) or while recording the cost (after dispatch) becomes
|
|
36
|
+
a ``LedgerError`` (a ``ProviderError`` of kind ``storage``, not retryable, ``__cause__`` = the ``StorageError``);
|
|
37
|
+
after dispatch it carries the paid answer in ``completion``, so ``rexlib.run`` returns a partial result whose
|
|
38
|
+
``error.completion`` still holds it. ``spent_today`` raises ``StorageError`` as is. The prices come from
|
|
39
|
+
``Gateway.prices`` (a ``ModelPrices`` built from the configuration: the same table a loop's cost limit reads
|
|
40
|
+
through ``prices.for_target(target)``); the ledger is ``Gateway.meter`` (a ``CostMeter`` on the storage).
|
|
41
|
+
|
|
42
|
+
Audit (step G3): one ``AuditEvent`` per attempt (each model tried) to ``GatewayOptions.audit``, by default to the
|
|
43
|
+
storage's ``append_audit`` when a storage is given: target, class, model id, provider, outcome, tokens, USD,
|
|
44
|
+
duration, error kind and status; never a prompt, an answer or a key (``GatewayOptions.audit_extra`` is the app's
|
|
45
|
+
explicit way to add fields). A failing sink never fails the call (``notice`` is told; a warning is logged when
|
|
46
|
+
there is no ``notice`` or it raises too). A cost-cap refusal leaves one ``refused`` event (class, spent, cap; no
|
|
47
|
+
model, tokens or USD); a model skipped for a missing key is not an attempt and leaves no event.
|
|
48
|
+
|
|
49
|
+
Requests: ``model`` becomes the entry's upstream name; ``max_tokens`` is clamped to ``max_output`` (and set to it
|
|
50
|
+
when the request gives none). Streaming (step ST2): ``Gateway.stream(target, request)`` and
|
|
51
|
+
``Gateway.provider(target).stream`` follow the same routing, caps and costs, with fallback only before the first
|
|
52
|
+
chunk (``rexlib.gateway.stream``). Test with
|
|
53
|
+
``GatewayOptions(providers={id: FakeProvider(...)}, env={...}, clock=FakeClock(), monotonic=FakeClock())``: no
|
|
54
|
+
network, no waiting.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
from __future__ import annotations
|
|
58
|
+
|
|
59
|
+
import logging
|
|
60
|
+
import threading
|
|
61
|
+
import time
|
|
62
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
63
|
+
from dataclasses import dataclass, field
|
|
64
|
+
from typing import Any
|
|
65
|
+
|
|
66
|
+
from rexlib.messages import ChatCompletion, ChatCompletionChunk, Usage
|
|
67
|
+
from rexlib.providers.anthropic import AnthropicMessages
|
|
68
|
+
from rexlib.providers.base import ChatRequest, Provider
|
|
69
|
+
from rexlib.providers.errors import ProviderError
|
|
70
|
+
from rexlib.providers.openai import OpenAIChat
|
|
71
|
+
from rexlib.storage import SqliteStorage, Storage, StorageError
|
|
72
|
+
|
|
73
|
+
from .attempts import Attempt, exhausted, prepare, show
|
|
74
|
+
from .audit import ERROR, OK, REFUSED, AuditEvent, AuditSink, StorageAuditSink
|
|
75
|
+
from .config import ConfigError, GatewayConfig, ModelConfig, resolve_timezone
|
|
76
|
+
from .costs import CostCapExceeded, CostMeter, LedgerError, cost_usd, estimate_usage
|
|
77
|
+
from .keys import key_lookup, key_resolver
|
|
78
|
+
from .presets import ANTHROPIC, FAKE
|
|
79
|
+
from .prices import ModelPrices
|
|
80
|
+
from .stream import stream_target
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class GatewayOptions:
|
|
85
|
+
"""Run-time parts of a ``Gateway`` (the ``GatewayConfig`` holds the configuration).
|
|
86
|
+
|
|
87
|
+
``storage``: where costs go (``None`` = an in-memory SQLite ledger owned by the gateway). ``clock``: wall
|
|
88
|
+
POSIX seconds (``time.time``) for cost timestamps and the day boundary; ``monotonic``: seconds for cooldowns
|
|
89
|
+
(``time.monotonic``); tests pass a ``FakeClock`` to each. ``env``: where ``key_env`` variables are looked up
|
|
90
|
+
(``None`` = the process environment, read at call time; never shown in the ``repr``).
|
|
91
|
+
``providers``: ready ``Provider`` objects by model id, used instead of building one (required for
|
|
92
|
+
``provider = "fake"`` entries; tests put ``FakeProvider`` objects here). ``http_backend``: passed to the
|
|
93
|
+
providers the gateway builds. ``notice``: called with a plain sentence when a model's key variable is
|
|
94
|
+
missing at start (never the value), when a capped class runs on the in-memory ledger and when an audit sink
|
|
95
|
+
fails. ``audit``: where one ``AuditEvent`` per attempt goes (``None`` = ``StorageAuditSink(storage)`` when a
|
|
96
|
+
``storage`` is given, else nowhere; ``lambda event: None`` switches it off). ``audit_extra(request) ->
|
|
97
|
+
mapping``: fields the app adds to each event on purpose (a session, a user; message bodies only if the app
|
|
98
|
+
chooses to); they never override a standard field. ``stream_deadline``: seconds a whole stream of a provider
|
|
99
|
+
the gateway builds may take (None = no limit; each read is bounded by the read timeout anyway)."""
|
|
100
|
+
|
|
101
|
+
storage: Storage | None = None
|
|
102
|
+
clock: Callable[[], float] = time.time
|
|
103
|
+
monotonic: Callable[[], float] = time.monotonic
|
|
104
|
+
env: Mapping[str, str] | None = field(default=None, repr=False)
|
|
105
|
+
providers: Mapping[str, Provider] = field(default_factory=dict)
|
|
106
|
+
http_backend: Any = None
|
|
107
|
+
notice: Callable[[str], None] | None = None
|
|
108
|
+
audit: AuditSink | None = None
|
|
109
|
+
audit_extra: Callable[[ChatRequest], Mapping[str, Any]] | None = None
|
|
110
|
+
stream_deadline: float | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Gateway:
|
|
114
|
+
"""Routes calls by class name or model id (see the module docstring). Safe to share between threads; the
|
|
115
|
+
daily cap is soft (parallel calls can overshoot it)."""
|
|
116
|
+
|
|
117
|
+
def __init__(self, config: GatewayConfig, options: GatewayOptions | None = None) -> None:
|
|
118
|
+
if not isinstance(config, GatewayConfig):
|
|
119
|
+
raise TypeError("Gateway needs a GatewayConfig")
|
|
120
|
+
self.config = config
|
|
121
|
+
self.options = GatewayOptions() if options is None else options
|
|
122
|
+
self._tz = resolve_timezone(config.timezone)
|
|
123
|
+
self._lookup = key_lookup(self.options.env)
|
|
124
|
+
_check_caps(config)
|
|
125
|
+
self._providers = _build_providers(config, self.options, self._lookup)
|
|
126
|
+
self._owned = self.options.storage is None
|
|
127
|
+
self._storage: Storage = self.options.storage or SqliteStorage(":memory:", clock=self.options.clock)
|
|
128
|
+
self.prices = ModelPrices.from_config(config)
|
|
129
|
+
self.meter = CostMeter(self._storage, clock=self.options.clock, timezone=self._tz)
|
|
130
|
+
storage = self.options.storage
|
|
131
|
+
self._audit_sink = self.options.audit or (StorageAuditSink(storage) if storage is not None else None)
|
|
132
|
+
self._cool_until: dict[str, float] = {}
|
|
133
|
+
self._lock = threading.Lock()
|
|
134
|
+
self._announce()
|
|
135
|
+
|
|
136
|
+
def __repr__(self) -> str:
|
|
137
|
+
return f"Gateway(targets={list(self.targets())!r})"
|
|
138
|
+
|
|
139
|
+
def __enter__(self) -> Gateway:
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
def __exit__(self, *exc: object) -> None:
|
|
143
|
+
self.close()
|
|
144
|
+
|
|
145
|
+
def close(self) -> None:
|
|
146
|
+
"""Close the in-memory ledger the gateway owns; a storage passed in ``options`` stays open (its owner
|
|
147
|
+
closes it)."""
|
|
148
|
+
if self._owned:
|
|
149
|
+
self._storage.close()
|
|
150
|
+
|
|
151
|
+
def targets(self) -> tuple[str, ...]:
|
|
152
|
+
"""Every name a caller may ask for: the class names, then the model ids."""
|
|
153
|
+
return self.config.targets()
|
|
154
|
+
|
|
155
|
+
def healthy(self, model_id: str) -> bool:
|
|
156
|
+
"""True when ``model_id`` has its key (or needs none) and is not cooling down."""
|
|
157
|
+
if model_id not in self.config.models:
|
|
158
|
+
raise ValueError(f"unknown model id {show(model_id)}; known: {', '.join(self.config.models)}")
|
|
159
|
+
return self._has_key(model_id) and not self._cooling(model_id, self.options.monotonic())
|
|
160
|
+
|
|
161
|
+
def spent_today(self, class_name: str) -> float:
|
|
162
|
+
"""USD recorded for ``class_name`` since the last local midnight (``GatewayConfig.timezone``)."""
|
|
163
|
+
if class_name not in self.config.classes:
|
|
164
|
+
raise ValueError(f"unknown class {show(class_name)}; known: {', '.join(self.config.classes)}")
|
|
165
|
+
return self.meter.spent(class_name)
|
|
166
|
+
|
|
167
|
+
def provider(self, target: str) -> Provider:
|
|
168
|
+
"""A ``Provider`` whose ``complete`` and ``stream`` route through this gateway to ``target`` (checked
|
|
169
|
+
now)."""
|
|
170
|
+
self._route(target)
|
|
171
|
+
return _TargetProvider(self, target)
|
|
172
|
+
|
|
173
|
+
def complete(self, target: str, request: ChatRequest) -> ChatCompletion:
|
|
174
|
+
"""One answer from the first model of ``target`` that serves it (see the module docstring).
|
|
175
|
+
|
|
176
|
+
Raises ``ValueError`` for an unknown target, ``CostCapExceeded`` when a daily cap is spent,
|
|
177
|
+
``LedgerError`` when the cost ledger fails, ``ProviderError`` when no model has its key, on a
|
|
178
|
+
non-retryable error, or when every model failed."""
|
|
179
|
+
scope, members = self._route(target)
|
|
180
|
+
self._check_caps(target, request)
|
|
181
|
+
failures: list[tuple[str, ProviderError]] = []
|
|
182
|
+
for model_id in self._order(members):
|
|
183
|
+
model = self.config.models[model_id]
|
|
184
|
+
attempt = Attempt(target, scope, model, request, self.options.monotonic())
|
|
185
|
+
try:
|
|
186
|
+
completion = self._providers[model_id].complete(prepare(model, request))
|
|
187
|
+
except ProviderError as exc:
|
|
188
|
+
self._audit(attempt, ERROR, status=exc.status, error=exc.kind)
|
|
189
|
+
if not exc.retryable:
|
|
190
|
+
raise
|
|
191
|
+
self._cool_down(model_id, exc)
|
|
192
|
+
failures.append((model_id, exc))
|
|
193
|
+
continue
|
|
194
|
+
self._charge(attempt, completion)
|
|
195
|
+
return completion
|
|
196
|
+
raise exhausted(target, failures)
|
|
197
|
+
|
|
198
|
+
def stream(self, target: str, request: ChatRequest) -> Iterator[ChatCompletionChunk]:
|
|
199
|
+
"""The chunks of the first model of ``target`` that starts streaming; fallback and cooldown only before
|
|
200
|
+
the first chunk with output, ``StreamInterrupted`` (with the ``partial`` text) after it; cost and audit at
|
|
201
|
+
the end, also for a broken or abandoned stream (``rexlib.gateway.stream``).
|
|
202
|
+
|
|
203
|
+
The target, the cap (``CostCapExceeded``) and the keys are checked now and again on the first ``next()``
|
|
204
|
+
(when the first model is called), so a generator kept for a while still honours the cap and cooldowns. Close the generator (or let it end) to release the connection."""
|
|
205
|
+
scope, members = self._route(target)
|
|
206
|
+
self._check_caps(target, request)
|
|
207
|
+
self._order(members)
|
|
208
|
+
return stream_target(self, target, scope, members, request)
|
|
209
|
+
|
|
210
|
+
# --- routing ---------------------------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
def _route(self, target: str) -> tuple[str, tuple[str, ...]]:
|
|
213
|
+
"""(class charged, model ids to try) of a class name or a model id; a model id is charged to the first
|
|
214
|
+
capped class listing it, else to the first class listing it."""
|
|
215
|
+
config = self.config
|
|
216
|
+
if isinstance(target, str) and target in config.classes:
|
|
217
|
+
return target, config.classes[target].models
|
|
218
|
+
if isinstance(target, str) and target in config.models:
|
|
219
|
+
capped = self._capped_classes(target)
|
|
220
|
+
return (capped[0] if capped else self._classes_of(target)[0]), (target,)
|
|
221
|
+
raise ValueError(f"unknown target {show(target)}; known: {', '.join(config.targets())}")
|
|
222
|
+
|
|
223
|
+
def _classes_of(self, model_id: str) -> list[str]:
|
|
224
|
+
return [c.name for c in self.config.classes.values() if model_id in c.models]
|
|
225
|
+
|
|
226
|
+
def _capped_classes(self, model_id: str) -> list[str]:
|
|
227
|
+
return [n for n in self._classes_of(model_id) if self.config.classes[n].daily_cap_usd is not None]
|
|
228
|
+
|
|
229
|
+
def _order(self, members: tuple[str, ...]) -> list[str]:
|
|
230
|
+
"""Members with their key, those not cooling down first; all of them when every one is cooling."""
|
|
231
|
+
usable = [m for m in members if self._has_key(m)]
|
|
232
|
+
if not usable:
|
|
233
|
+
missing = ", ".join(f"{m} ({self.config.models[m].key_env} not set)" for m in members)
|
|
234
|
+
raise ProviderError(f"no usable model: {missing}", kind=ProviderError.AUTH)
|
|
235
|
+
now = self.options.monotonic()
|
|
236
|
+
ready = [m for m in usable if not self._cooling(m, now)]
|
|
237
|
+
return ready or usable
|
|
238
|
+
|
|
239
|
+
def _has_key(self, model_id: str) -> bool:
|
|
240
|
+
name = self.config.models[model_id].key_env
|
|
241
|
+
return name is None or self._lookup(name) is not None
|
|
242
|
+
|
|
243
|
+
def _cooling(self, model_id: str, now: float) -> bool:
|
|
244
|
+
with self._lock:
|
|
245
|
+
return self._cool_until.get(model_id, 0.0) > now
|
|
246
|
+
|
|
247
|
+
def _cool_down(self, model_id: str, error: ProviderError) -> None:
|
|
248
|
+
until = self.options.monotonic() + max(self.config.cooldown, error.retry_after or 0.0)
|
|
249
|
+
with self._lock: # a shorter cooldown never cuts a longer one already running
|
|
250
|
+
self._cool_until[model_id] = max(self._cool_until.get(model_id, until), until)
|
|
251
|
+
|
|
252
|
+
def _announce(self) -> None:
|
|
253
|
+
notice = self.options.notice
|
|
254
|
+
if notice is None:
|
|
255
|
+
return
|
|
256
|
+
for model_id, model in self.config.models.items():
|
|
257
|
+
if not self._has_key(model_id):
|
|
258
|
+
notice(f"model {model_id!r} is skipped while the environment variable {model.key_env} is not set")
|
|
259
|
+
capped = [n for n, c in self.config.classes.items() if c.daily_cap_usd is not None]
|
|
260
|
+
if capped and self._owned:
|
|
261
|
+
notice(f"classes {', '.join(capped)} have a daily cap but no storage: what they spend is kept in memory "
|
|
262
|
+
"only and forgotten at exit (pass GatewayOptions.storage)")
|
|
263
|
+
|
|
264
|
+
# --- costs -----------------------------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
def _check_caps(self, target: str, request: ChatRequest) -> None:
|
|
267
|
+
"""Every capped class the call could spend for (the class itself, or each capped class listing a model
|
|
268
|
+
id) must have cap left; ``CostCapExceeded`` names the first one that has none (one ``refused`` audit
|
|
269
|
+
event, nothing sent)."""
|
|
270
|
+
scopes = [target] if target in self.config.classes else self._capped_classes(target)
|
|
271
|
+
for scope in scopes:
|
|
272
|
+
try:
|
|
273
|
+
self.meter.check(scope, self.config.classes[scope].daily_cap_usd)
|
|
274
|
+
except StorageError as exc:
|
|
275
|
+
raise LedgerError(f"the cost ledger failed before the call ({type(exc).__name__}); nothing was "
|
|
276
|
+
"sent") from exc
|
|
277
|
+
except CostCapExceeded as exc:
|
|
278
|
+
self._send(request, target, lambda extra: AuditEvent(
|
|
279
|
+
ts=self.options.clock(), target=target, class_name=exc.class_name, model=None, provider=None,
|
|
280
|
+
outcome=REFUSED, ms=0.0, error=exc.kind, spent=exc.spent, cap=exc.cap, extra=extra))
|
|
281
|
+
raise
|
|
282
|
+
|
|
283
|
+
def _charge(self, attempt: Attempt, completion: ChatCompletion) -> None:
|
|
284
|
+
"""Record the cost of an answer (``LedgerError`` when the ledger fails) and audit the attempt."""
|
|
285
|
+
model = attempt.model
|
|
286
|
+
usage = Usage.from_dict(completion.usage)
|
|
287
|
+
estimated = usage is None
|
|
288
|
+
if usage is None:
|
|
289
|
+
usage = estimate_usage(attempt.request, completion)
|
|
290
|
+
price = self.prices.price(model.id)
|
|
291
|
+
usd = cost_usd(price, usage) if price is not None else 0.0
|
|
292
|
+
audit = {"usd": usd, "estimated": estimated, "priced": price is not None,
|
|
293
|
+
"input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens,
|
|
294
|
+
"cache_read_tokens": usage.cache_read_tokens, "cache_write_tokens": usage.cache_write_tokens}
|
|
295
|
+
try:
|
|
296
|
+
self.meter.charge(attempt.scope, usage, price, model=model.id, target=attempt.target,
|
|
297
|
+
estimated=estimated)
|
|
298
|
+
except StorageError as exc:
|
|
299
|
+
self._audit(attempt, OK, error=ProviderError.STORAGE, **audit)
|
|
300
|
+
raise LedgerError(f"the answer of {model.id!r} arrived but its cost could not be recorded "
|
|
301
|
+
f"({type(exc).__name__}); the answer is in .completion", completion) from exc
|
|
302
|
+
self._audit(attempt, OK, **audit)
|
|
303
|
+
|
|
304
|
+
# --- audit -----------------------------------------------------------------------------------------------
|
|
305
|
+
|
|
306
|
+
def _audit(self, attempt: Attempt, outcome: str, **fields: Any) -> None:
|
|
307
|
+
"""One ``AuditEvent`` of an attempt to the sink (see ``_send``)."""
|
|
308
|
+
options = self.options
|
|
309
|
+
self._send(attempt.request, attempt.model.id, lambda extra: AuditEvent(
|
|
310
|
+
ts=options.clock(), target=attempt.target, class_name=attempt.scope, model=attempt.model.id,
|
|
311
|
+
provider=attempt.model.provider, outcome=outcome,
|
|
312
|
+
ms=round((options.monotonic() - attempt.started) * 1000.0, 3), extra=extra, **fields))
|
|
313
|
+
|
|
314
|
+
def _send(self, request: ChatRequest, label: str,
|
|
315
|
+
make: Callable[[Mapping[str, Any]], AuditEvent]) -> None:
|
|
316
|
+
"""``make(extra)`` to the sink (``label`` names the model or target in a failure message). A failing sink (or ``audit_extra``, or ``notice``) never fails the call: the
|
|
317
|
+
cost ledger is the record of money and fails closed; an audit failure goes to ``notice``, and when that
|
|
318
|
+
is missing or fails too, to a logged warning."""
|
|
319
|
+
sink, options = self._audit_sink, self.options
|
|
320
|
+
if sink is None:
|
|
321
|
+
return
|
|
322
|
+
try:
|
|
323
|
+
sink(make(dict(options.audit_extra(request)) if options.audit_extra is not None else {}))
|
|
324
|
+
except Exception as exc: # noqa: BLE001 - any sink failure; the call itself already succeeded or failed
|
|
325
|
+
self._report(f"audit event of {show(label)} lost: the audit sink failed ({type(exc).__name__})")
|
|
326
|
+
|
|
327
|
+
def _report(self, message: str) -> None:
|
|
328
|
+
"""``message`` to ``notice``; to a logged warning when there is no ``notice`` or it raises."""
|
|
329
|
+
notice = self.options.notice
|
|
330
|
+
if notice is not None:
|
|
331
|
+
try:
|
|
332
|
+
notice(message)
|
|
333
|
+
return
|
|
334
|
+
except Exception as exc: # noqa: BLE001 - a broken notice must not fail a call either
|
|
335
|
+
message = f"{message}; notice failed too ({type(exc).__name__})"
|
|
336
|
+
logging.getLogger(__name__).warning("%s", message)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class _TargetProvider:
|
|
340
|
+
"""``Gateway.provider(target)``: the ``Provider`` protocol bound to one target."""
|
|
341
|
+
|
|
342
|
+
def __init__(self, gateway: Gateway, target: str) -> None:
|
|
343
|
+
self.gateway = gateway
|
|
344
|
+
self.target = target
|
|
345
|
+
|
|
346
|
+
def __repr__(self) -> str:
|
|
347
|
+
return f"GatewayProvider(target={self.target!r})"
|
|
348
|
+
|
|
349
|
+
def complete(self, request: ChatRequest) -> ChatCompletion:
|
|
350
|
+
return self.gateway.complete(self.target, request)
|
|
351
|
+
|
|
352
|
+
def stream(self, request: ChatRequest) -> Iterator[ChatCompletionChunk]:
|
|
353
|
+
return self.gateway.stream(self.target, request)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _check_caps(config: GatewayConfig) -> None:
|
|
357
|
+
"""A class with a daily cap must price every model it lists (an unpriced model would make the cap a hole)."""
|
|
358
|
+
for name, entry in config.classes.items():
|
|
359
|
+
if entry.daily_cap_usd is None:
|
|
360
|
+
continue
|
|
361
|
+
for model_id in entry.models:
|
|
362
|
+
if config.models[model_id].price is None:
|
|
363
|
+
raise ConfigError(f"classes.{name} has daily_cap_usd but model {model_id!r} has no price")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _build_providers(config: GatewayConfig, options: GatewayOptions,
|
|
367
|
+
lookup: Callable[[str], str | None]) -> dict[str, Provider]:
|
|
368
|
+
given = dict(options.providers)
|
|
369
|
+
unknown = sorted(set(given) - set(config.models))
|
|
370
|
+
if unknown:
|
|
371
|
+
raise ConfigError(f"GatewayOptions.providers names unknown model {show(unknown[0])}")
|
|
372
|
+
built: dict[str, Provider] = {}
|
|
373
|
+
for model_id, model in config.models.items():
|
|
374
|
+
if model_id in given:
|
|
375
|
+
built[model_id] = given[model_id]
|
|
376
|
+
elif model.provider == FAKE:
|
|
377
|
+
raise ConfigError(f"models.{model_id}: provider 'fake' needs GatewayOptions.providers[{model_id!r}]")
|
|
378
|
+
else:
|
|
379
|
+
built[model_id] = _make_provider(config, model, options, lookup)
|
|
380
|
+
return built
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _make_provider(config: GatewayConfig, model: ModelConfig, options: GatewayOptions,
|
|
384
|
+
lookup: Callable[[str], str | None]) -> Provider:
|
|
385
|
+
key = key_resolver(lookup, model.key_env) if model.key_env is not None else None
|
|
386
|
+
client = AnthropicMessages if model.provider == ANTHROPIC else OpenAIChat
|
|
387
|
+
assert model.base_url is not None # ModelConfig guarantees a base_url for every provider but 'fake'
|
|
388
|
+
provider = client(model.base_url, key, model.model, timeout=config.read_timeout,
|
|
389
|
+
connect_timeout=config.connect_timeout, http_backend=options.http_backend)
|
|
390
|
+
provider.stream_deadline = options.stream_deadline
|
|
391
|
+
return provider
|