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.
Files changed (58) hide show
  1. rexlib/__init__.py +75 -0
  2. rexlib/cli/__init__.py +44 -0
  3. rexlib/cli/commands.py +99 -0
  4. rexlib/cli/console.py +83 -0
  5. rexlib/cli/options.py +47 -0
  6. rexlib/cli/permissions.py +174 -0
  7. rexlib/cli/render.py +78 -0
  8. rexlib/cli/repl.py +97 -0
  9. rexlib/cli/session.py +99 -0
  10. rexlib/container/__init__.py +33 -0
  11. rexlib/container/detect.py +151 -0
  12. rexlib/container/model.py +111 -0
  13. rexlib/container/probe.py +191 -0
  14. rexlib/container/resolve.py +151 -0
  15. rexlib/gateway/__init__.py +56 -0
  16. rexlib/gateway/attempts.py +51 -0
  17. rexlib/gateway/audit.py +173 -0
  18. rexlib/gateway/config.py +383 -0
  19. rexlib/gateway/costs.py +157 -0
  20. rexlib/gateway/keys.py +46 -0
  21. rexlib/gateway/presets.py +59 -0
  22. rexlib/gateway/prices.py +134 -0
  23. rexlib/gateway/router.py +391 -0
  24. rexlib/gateway/stream.py +224 -0
  25. rexlib/loop/__init__.py +63 -0
  26. rexlib/loop/calls.py +220 -0
  27. rexlib/loop/core.py +249 -0
  28. rexlib/loop/options.py +149 -0
  29. rexlib/loop/stream.py +88 -0
  30. rexlib/messages.py +221 -0
  31. rexlib/providers/__init__.py +11 -0
  32. rexlib/providers/anthropic.py +108 -0
  33. rexlib/providers/base.py +53 -0
  34. rexlib/providers/errors.py +191 -0
  35. rexlib/providers/http.py +124 -0
  36. rexlib/providers/openai.py +148 -0
  37. rexlib/providers/transport.py +163 -0
  38. rexlib/py.typed +0 -0
  39. rexlib/storage/__init__.py +30 -0
  40. rexlib/storage/base.py +144 -0
  41. rexlib/storage/contract.py +262 -0
  42. rexlib/storage/registry.py +49 -0
  43. rexlib/storage/sqlite.py +219 -0
  44. rexlib/testing.py +160 -0
  45. rexlib/tools/__init__.py +12 -0
  46. rexlib/tools/base.py +116 -0
  47. rexlib/tools/executor.py +105 -0
  48. rexlib/tools/function_tool.py +168 -0
  49. rexlib/tools/registry.py +66 -0
  50. rexlib/wire/__init__.py +6 -0
  51. rexlib/wire/anthropic_messages.py +300 -0
  52. rexlib/wire/openai_chat.py +134 -0
  53. rexlib/wire/sse.py +85 -0
  54. rexlib_py-0.9.0a1.dist-info/METADATA +251 -0
  55. rexlib_py-0.9.0a1.dist-info/RECORD +58 -0
  56. rexlib_py-0.9.0a1.dist-info/WHEEL +5 -0
  57. rexlib_py-0.9.0a1.dist-info/licenses/LICENSE +21 -0
  58. rexlib_py-0.9.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,383 @@
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
+ """``GatewayConfig``: model entries, classes and gateway settings from a dict or a TOML file, strictly checked.
6
+
7
+ timezone = "UTC" # day boundary of the daily caps; absent = the system's local time
8
+ cooldown = 30.0 # seconds a model rests after a fallback-worthy error
9
+ connect_timeout = 10.0
10
+ read_timeout = 300.0
11
+
12
+ [models.sonnet] # the key is the model id the gateway knows it by
13
+ preset = "anthropic" # or provider = "anthropic" | "openai-compatible" | "fake" (+ base_url, key_env)
14
+ model = "claude-sonnet-4-5" # the upstream model name (default: the model id)
15
+ context = 200000 # optional
16
+ max_output = 8192 # optional; requests are clamped to it (step G2)
17
+ price = { in = 3.0, out = 15.0 } # USD per million tokens; cache_read / cache_write default to 10 % / 125 %
18
+ # of in (Anthropic's multipliers; set them for other providers)
19
+
20
+ [classes]
21
+ large = ["sonnet", "gpt"] # ordered: primary first, the order is the fallback order
22
+ small = { models = ["haiku"], daily_cap_usd = 2.0 }
23
+
24
+ Every table rejects an unknown key with its name (a typo must not switch a cost cap off). ``key_env`` is the NAME
25
+ of the environment variable holding the key (``[A-Z_][A-Z0-9_]*``, not starting like a real key: ``AIza``, ``sk-``,
26
+ ``nvapi-``, ``xai-``, ``gsk_``); nothing reads it here (the router does, step G2), and a refused value is never
27
+ shown. A key would go only over https or to a loopback host, so a plain-http ``base_url`` with a ``key_env`` is
28
+ refused; credentials inside a URL (user info, a key in the query), a fragment, a backslash, spaces and control
29
+ characters are refused. Every model must be in a class, a name cannot be both a class and a model id, and classes
30
+ name only known models. ``ModelConfig``, ``ClassConfig`` and ``Price`` check themselves, so a directly built
31
+ ``GatewayConfig`` is as safe as one from ``from_dict``; an app's ``presets=`` table is checked the same way. Errors
32
+ are ``ConfigError`` (a ``ValueError``) naming the place (``models.sonnet.price.in``).
33
+
34
+ Public sources: the Python ``tomllib`` and ``zoneinfo`` documentation; the shape of a model entry follows the
35
+ LiteLLM Router ``model_list`` documentation (https://docs.litellm.ai/docs/routing); the cache price multipliers are
36
+ Anthropic's published prompt-caching prices.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import datetime
42
+ import math
43
+ import re
44
+ import tomllib
45
+ from urllib.parse import urlsplit
46
+ from collections.abc import Mapping
47
+ from dataclasses import dataclass
48
+ from os import PathLike
49
+ from pathlib import Path
50
+ from types import MappingProxyType
51
+ from typing import Any, cast
52
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
53
+
54
+ from rexlib.providers.errors import url_secrets
55
+ from rexlib.providers.transport import check_endpoint
56
+
57
+ from .presets import FAKE, PRESETS, PROVIDERS, Preset
58
+
59
+ TOP_KEYS = ("models", "classes", "timezone", "cooldown", "connect_timeout", "read_timeout")
60
+ MODEL_KEYS = ("preset", "provider", "model", "base_url", "key_env", "context", "max_output", "price")
61
+ PRICE_KEYS = ("in", "out", "cache_read", "cache_write")
62
+ CLASS_KEYS = ("models", "daily_cap_usd")
63
+ # Default cache prices when an entry gives none: Anthropic's published prompt-caching multipliers (cache read = 10 %,
64
+ # 5-minute cache write = 125 % of the input price). Other providers price caching differently: set them explicitly.
65
+ CACHE_READ_FACTOR = 0.10
66
+ CACHE_WRITE_FACTOR = 1.25
67
+ PRICE_DIGITS = 9 # derived prices are rounded to 1e-9 USD per million tokens (no float noise like 0.30000000000000004)
68
+ _ENV_NAME = re.compile(r"[A-Z_][A-Z0-9_]{0,127}")
69
+ KEY_PREFIXES = ("AIza", "sk-", "nvapi-", "xai-", "gsk_") # how real keys start (Google, OpenAI/Anthropic, NVIDIA ...)
70
+ _NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}") # model ids and class names
71
+
72
+
73
+ class ConfigError(ValueError):
74
+ """An invalid gateway configuration; the message names the place and never shows a key."""
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class Price:
79
+ """USD per million tokens (the unit providers publish) for input, output, cache read and cache write."""
80
+
81
+ input: float
82
+ output: float
83
+ cache_read: float
84
+ cache_write: float
85
+
86
+ def __post_init__(self) -> None:
87
+ for name in ("input", "output", "cache_read", "cache_write"):
88
+ _number(getattr(self, name), f"price.{name}")
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class ModelConfig:
93
+ """One model entry: ``provider`` (a name of ``PROVIDERS``), upstream ``model`` name, ``base_url`` and
94
+ ``key_env`` (``None`` for ``fake``; ``key_env`` ``None`` = no key), optional ``context`` / ``max_output``
95
+ token counts and ``price`` (``None`` = unknown)."""
96
+
97
+ id: str
98
+ provider: str
99
+ model: str
100
+ base_url: str | None = None
101
+ key_env: str | None = None
102
+ context: int | None = None
103
+ max_output: int | None = None
104
+ price: Price | None = None
105
+
106
+ def __post_init__(self) -> None:
107
+ """The same checks as ``from_dict``, so a directly built entry is as safe (``key_env = ""`` -> ``None``)."""
108
+ where = f"models.{self.id}"
109
+ _name(self.id, "models")
110
+ if self.provider not in PROVIDERS:
111
+ raise ConfigError(f"{where}.provider must be one of {', '.join(PROVIDERS)}")
112
+ _text(self.model, f"{where}.model")
113
+ key_env = None if self.key_env is None else _key_env(self.key_env, where)
114
+ object.__setattr__(self, "key_env", key_env)
115
+ object.__setattr__(self, "base_url", _endpoint(self.provider, self.base_url, key_env, where))
116
+ for size in ("context", "max_output"):
117
+ if getattr(self, size) is not None:
118
+ _count(getattr(self, size), f"{where}.{size}")
119
+ if self.price is not None and not isinstance(self.price, Price):
120
+ raise ConfigError(f"{where}.price must be a Price")
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class ClassConfig:
125
+ """A model class: free ``name``, ordered model ids (primary first = fallback order), optional soft daily cap."""
126
+
127
+ name: str
128
+ models: tuple[str, ...]
129
+ daily_cap_usd: float | None = None
130
+
131
+ def __post_init__(self) -> None:
132
+ """The same checks as ``from_dict``; ``models`` becomes a tuple."""
133
+ where = f"classes.{self.name}"
134
+ _name(self.name, "classes")
135
+ if isinstance(self.models, (str, bytes)) or not isinstance(self.models, (list, tuple)) or not self.models:
136
+ raise ConfigError(f"{where}.models must be a non-empty list of model ids")
137
+ ids = tuple(_text(member, f"{where}.models") for member in self.models)
138
+ if len(set(ids)) != len(ids):
139
+ raise ConfigError(f"{where}.models lists a model twice")
140
+ object.__setattr__(self, "models", ids)
141
+ if self.daily_cap_usd is not None:
142
+ _number(self.daily_cap_usd, f"{where}.daily_cap_usd")
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class GatewayConfig:
147
+ """Checked gateway configuration (``from_dict`` / ``from_toml``). ``models`` and ``classes`` are read-only
148
+ mappings in configuration order; every check also runs on direct construction (each entry checks itself).
149
+ Not hashable (``__hash__ = None``): it holds mappings."""
150
+
151
+ __hash__ = None # type: ignore[assignment] # frozen, but its mappings are not hashable
152
+
153
+ models: Mapping[str, ModelConfig]
154
+ classes: Mapping[str, ClassConfig]
155
+ timezone: str | None = None
156
+ cooldown: float = 30.0
157
+ connect_timeout: float = 10.0
158
+ read_timeout: float = 300.0
159
+
160
+ def __post_init__(self) -> None:
161
+ object.__setattr__(self, "models", MappingProxyType(dict(self.models)))
162
+ object.__setattr__(self, "classes", MappingProxyType(dict(self.classes)))
163
+ _check_links(self.models, self.classes)
164
+ _number(self.cooldown, "cooldown")
165
+ _number(self.connect_timeout, "connect_timeout", positive=True)
166
+ _number(self.read_timeout, "read_timeout", positive=True)
167
+ resolve_timezone(self.timezone)
168
+
169
+ @classmethod
170
+ def from_dict(cls, data: Mapping[str, Any], *, presets: Mapping[str, Preset] | None = None) -> GatewayConfig:
171
+ """Build from plain data (TOML-shaped; see the module docstring). ``presets`` default: ``PRESETS``."""
172
+ _check_keys(data, TOP_KEYS, "configuration")
173
+ table = PRESETS if presets is None else _check_presets(presets)
174
+ models = {mid: _parse_model(mid, raw, table) for mid, raw in _table(data, "models").items()}
175
+ classes = {name: _parse_class(name, raw) for name, raw in _table(data, "classes").items()}
176
+ settings = {key: _number(data[key], key) for key in ("cooldown", "connect_timeout", "read_timeout")
177
+ if key in data}
178
+ timezone = data.get("timezone")
179
+ if timezone is not None and not isinstance(timezone, str):
180
+ raise ConfigError("timezone must be a zone name such as 'UTC' or 'Europe/Sofia'")
181
+ return cls(models, classes, timezone, **settings)
182
+
183
+ @classmethod
184
+ def from_toml(cls, path: str | PathLike[str], *,
185
+ presets: Mapping[str, Preset] | None = None) -> GatewayConfig:
186
+ """Read a TOML file (stdlib ``tomllib``) and build as ``from_dict``."""
187
+ file = Path(path)
188
+ try:
189
+ data = tomllib.loads(file.read_text(encoding="utf-8"))
190
+ except tomllib.TOMLDecodeError as exc:
191
+ raise ConfigError(f"{file.name}: not valid TOML: {exc}") from None
192
+ except UnicodeDecodeError:
193
+ raise ConfigError(f"{file.name}: not UTF-8 text") from None
194
+ return cls.from_dict(data, presets=presets)
195
+
196
+ def targets(self) -> tuple[str, ...]:
197
+ """Every name a caller may ask for: the class names, then the model ids, in configuration order."""
198
+ return (*self.classes, *self.models)
199
+
200
+
201
+ def resolve_timezone(name: str | None) -> datetime.tzinfo | None:
202
+ """The zone of the daily-cap day boundary: ``None`` = the system's local time, ``"UTC"`` needs no time zone
203
+ database, any other IANA name is read through ``zoneinfo`` (on Windows that needs the ``tzdata`` package)."""
204
+ if name is None:
205
+ return None
206
+ if name.upper() == "UTC":
207
+ return datetime.UTC
208
+ try:
209
+ return ZoneInfo(name)
210
+ except (ZoneInfoNotFoundError, ValueError):
211
+ raise ConfigError(f"timezone {_show(name)} is not known (an IANA name; on Windows install tzdata, "
212
+ "or use 'UTC')") from None
213
+
214
+
215
+ def _show(name: object) -> str:
216
+ """A configuration name for a message: ``repr``, cut to 40 characters."""
217
+ text = str(name)
218
+ return repr(text if len(text) <= 40 else text[:40] + "...")
219
+
220
+
221
+ def _check_keys(data: object, allowed: tuple[str, ...], where: str) -> None:
222
+ if not isinstance(data, Mapping):
223
+ raise ConfigError(f"{where} must be a table")
224
+ for key in data:
225
+ if key not in allowed:
226
+ raise ConfigError(f"{where}: unknown key {_show(key)}; known: {', '.join(allowed)}")
227
+
228
+
229
+ def _table(data: Mapping[str, Any], key: str) -> Mapping[str, Any]:
230
+ value = data.get(key)
231
+ if not isinstance(value, Mapping) or not value:
232
+ raise ConfigError(f"{key} must be a non-empty table")
233
+ for name in value:
234
+ _name(name, key)
235
+ return value
236
+
237
+
238
+ def _name(name: object, table: str) -> str:
239
+ if not isinstance(name, str) or not _NAME.fullmatch(name):
240
+ raise ConfigError(f"{table}: name {_show(name)} is not valid (letters, digits and . _ : / @ + -; "
241
+ "a letter or digit first; at most 128)")
242
+ return name
243
+
244
+
245
+ def _number(value: object, where: str, *, positive: bool = False) -> float:
246
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
247
+ raise ConfigError(f"{where} must be a finite number")
248
+ if value < 0 or (positive and value == 0):
249
+ raise ConfigError(f"{where} must be {'> 0' if positive else '>= 0'}")
250
+ return float(value)
251
+
252
+
253
+ def _count(value: object, where: str) -> int:
254
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
255
+ raise ConfigError(f"{where} must be a whole number > 0")
256
+ return value
257
+
258
+
259
+ def _text(value: object, where: str) -> str:
260
+ if not isinstance(value, str) or not value.strip():
261
+ raise ConfigError(f"{where} must be a non-empty string")
262
+ return value.strip()
263
+
264
+
265
+ def _parse_price(raw: object, where: str) -> Price:
266
+ _check_keys(raw, PRICE_KEYS, where)
267
+ raw = cast(Mapping[str, Any], raw)
268
+ if "in" not in raw or "out" not in raw:
269
+ raise ConfigError(f"{where} needs 'in' and 'out' (USD per million tokens)")
270
+ given = {key: _number(raw[key], f"{where}.{key}") for key in PRICE_KEYS if key in raw}
271
+ cache_read = given.get("cache_read", round(given["in"] * CACHE_READ_FACTOR, PRICE_DIGITS))
272
+ cache_write = given.get("cache_write", round(given["in"] * CACHE_WRITE_FACTOR, PRICE_DIGITS))
273
+ return Price(given["in"], given["out"], cache_read, cache_write)
274
+
275
+
276
+ def _parse_model(model_id: str, raw: object, presets: Mapping[str, Preset]) -> ModelConfig:
277
+ where = f"models.{model_id}"
278
+ _check_keys(raw, MODEL_KEYS, where)
279
+ raw = cast(Mapping[str, Any], raw)
280
+ preset = _preset(raw, where, presets)
281
+ provider = preset.provider if preset else _text(raw.get("provider"), f"{where}.provider")
282
+ if provider not in PROVIDERS:
283
+ raise ConfigError(f"{where}.provider must be one of {', '.join(PROVIDERS)}")
284
+ base_url = raw.get("base_url", preset.base_url if preset else None)
285
+ key_env = _key_env(raw["key_env"], where) if "key_env" in raw else (preset.key_env if preset else None)
286
+ base_url = _endpoint(provider, base_url, key_env, where)
287
+ price = _parse_price(raw["price"], f"{where}.price") if "price" in raw else None
288
+ sizes = {key: _count(raw[key], f"{where}.{key}") for key in ("context", "max_output") if key in raw}
289
+ model = _text(raw.get("model", model_id), f"{where}.model")
290
+ return ModelConfig(model_id, provider, model, base_url, key_env, price=price, **sizes)
291
+
292
+
293
+ def _preset(raw: Mapping[str, Any], where: str, presets: Mapping[str, Preset]) -> Preset | None:
294
+ if "preset" not in raw:
295
+ if "provider" not in raw:
296
+ raise ConfigError(f"{where} needs 'preset' (one of {', '.join(presets)}) or 'provider'")
297
+ return None
298
+ if "provider" in raw:
299
+ raise ConfigError(f"{where}: give 'preset' or 'provider', not both")
300
+ name = raw["preset"]
301
+ if not isinstance(name, str) or name not in presets:
302
+ raise ConfigError(f"{where}.preset {_show(name)} is not known; known: {', '.join(presets)}")
303
+ return presets[name]
304
+
305
+
306
+ def _check_presets(presets: Mapping[str, Preset]) -> Mapping[str, Preset]:
307
+ """An app's presets table: every entry a ``Preset`` with a known provider, a valid ``key_env`` and endpoint."""
308
+ if not isinstance(presets, Mapping):
309
+ raise ConfigError("presets must be a mapping of name -> Preset")
310
+ for name, preset in presets.items():
311
+ where = f"presets.{_name(name, 'presets')}"
312
+ if not isinstance(preset, Preset):
313
+ raise ConfigError(f"{where} must be a Preset")
314
+ if preset.provider not in PROVIDERS:
315
+ raise ConfigError(f"{where}.provider must be one of {', '.join(PROVIDERS)}")
316
+ key_env = None if preset.key_env is None else _key_env(preset.key_env, where)
317
+ if preset.provider != FAKE:
318
+ _endpoint(preset.provider, preset.base_url, key_env, where)
319
+ return presets
320
+
321
+
322
+ def _key_env(value: object, where: str) -> str | None:
323
+ """The variable NAME (upper case); ``""`` = no key. Anything else, and anything starting like a real key, is
324
+ refused without echoing it (it may be a pasted key)."""
325
+ if value == "":
326
+ return None
327
+ if not isinstance(value, str) or not _ENV_NAME.fullmatch(value) or value.startswith(KEY_PREFIXES):
328
+ raise ConfigError(f"{where}.key_env must be the NAME of an environment variable (upper-case letters, "
329
+ "digits, '_'), never the key itself (value not shown)")
330
+ return value
331
+
332
+
333
+ def _endpoint(provider: str, base_url: object, key_env: str | None, where: str) -> str | None:
334
+ if provider == FAKE:
335
+ if base_url is not None or key_env is not None:
336
+ raise ConfigError(f"{where}: provider 'fake' takes no base_url or key_env")
337
+ return None
338
+ url = _text(base_url, f"{where}.base_url")
339
+ if "\\" in url or any(ch.isspace() or ord(ch) < 32 for ch in url):
340
+ raise ConfigError(f"{where}.base_url holds a backslash, a space or a control character (not shown)")
341
+ try:
342
+ if urlsplit(url).fragment or "#" in url:
343
+ raise ConfigError(f"{where}.base_url must not carry a fragment ('#...')")
344
+ if url_secrets(url):
345
+ raise ConfigError(f"{where}.base_url carries credentials (user info or a key in the query; not shown); "
346
+ "name the key's variable in key_env")
347
+ check_endpoint(url, key_env)
348
+ except ConfigError:
349
+ raise
350
+ except ValueError as exc: # check_endpoint shows the URL without credentials; urlsplit errors show nothing
351
+ raise ConfigError(f"{where}.base_url: {exc}") from None
352
+ return url
353
+
354
+
355
+ def _parse_class(name: str, raw: object) -> ClassConfig:
356
+ where = f"classes.{name}"
357
+ if isinstance(raw, (list, tuple)):
358
+ raw = {"models": raw}
359
+ _check_keys(raw, CLASS_KEYS, where)
360
+ raw = cast(Mapping[str, Any], raw)
361
+ cap = _number(raw["daily_cap_usd"], f"{where}.daily_cap_usd") if "daily_cap_usd" in raw else None
362
+ return ClassConfig(name, raw.get("models"), cap) # type: ignore[arg-type] # ClassConfig checks the list
363
+
364
+
365
+ def _check_links(models: Mapping[str, ModelConfig], classes: Mapping[str, ClassConfig]) -> None:
366
+ if not models or not classes:
367
+ raise ConfigError("a gateway needs at least one model and one class")
368
+ filed = [(key, entry.id) for key, entry in models.items()] + [(k, c.name) for k, c in classes.items()]
369
+ for key, name in filed:
370
+ if key != name:
371
+ raise ConfigError(f"entry {_show(key)} is filed under another name ({_show(name)})")
372
+ both = sorted(classes.keys() & models.keys())
373
+ if both:
374
+ raise ConfigError(f"{_show(both[0])} is both a class and a model id (a target must be one or the other)")
375
+ listed: set[str] = set()
376
+ for name, entry in classes.items():
377
+ for member in entry.models:
378
+ if member not in models:
379
+ raise ConfigError(f"classes.{name} lists unknown model {_show(member)}")
380
+ listed.add(member)
381
+ for model_id in models:
382
+ if model_id not in listed:
383
+ raise ConfigError(f"model {_show(model_id)} is in no class (a model in no class is unusable)")
@@ -0,0 +1,157 @@
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
+ """Cost math, the cost ledger and the daily cap: ``Price`` x ``Usage``, ``CostMeter``, ``CostCapExceeded``.
6
+
7
+ - ``cost_usd(price, usage)``: USD of one call; ``Price`` is USD per million tokens (the unit providers publish),
8
+ the four token counts of ``Usage`` each have their own price (input without cache, output, cache read, cache
9
+ write, as the providers report them).
10
+ - ``estimate_usage(request, completion)``: about 4 characters per token, for an answer without usage (the same
11
+ rule as ``rexlib.loop``); the cost record then says ``estimated: true``.
12
+ - ``day_bounds(now, tz)``: POSIX seconds of the local midnight that starts the day of ``now`` and of the next one,
13
+ in the ``GatewayConfig.timezone`` zone (``None`` = the system's local time).
14
+ - ``CostMeter(storage, *, clock, timezone)``: the cost records of a ``Storage`` (written by the ``Gateway`` after
15
+ each answer, readable by any app): ``charge(scope, usage, price, **fields)`` records one call,
16
+ ``record(entry)`` any entry (a per-user budget, ``scope = "user:ann"``), ``spent(scope, since=None)`` sums
17
+ (``None`` = since the last local midnight), ``day()`` gives the bounds of today, ``check(scope, cap)`` raises
18
+ ``CostCapExceeded``. A ``StorageError`` passes through as is (the ``Gateway`` turns it into ``LedgerError``).
19
+ - ``CostCapExceeded``: a ``ProviderError`` of kind ``cost_cap`` (never retryable): the class's soft daily cap is
20
+ spent; it holds until ``resets_at``.
21
+ - ``LedgerError``: a ``ProviderError`` of kind ``storage`` (never retryable): the cost ledger failed. Before
22
+ dispatch (reading what was spent) nothing was sent and ``completion`` is None; after dispatch (recording the
23
+ cost) the paid answer is kept in ``completion``. The ``StorageError`` is the ``__cause__``.
24
+
25
+ The cap is soft: it is checked before each call against what the storage has recorded, so calls running in
26
+ parallel can overshoot it by their own cost.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import datetime
32
+ import json
33
+ import time
34
+ from collections.abc import Callable, Mapping
35
+ from typing import Any
36
+
37
+ from rexlib.messages import ChatCompletion, ChatMessage, Usage
38
+ from rexlib.providers.base import ChatRequest
39
+ from rexlib.providers.errors import ProviderError
40
+ from rexlib.storage import Storage
41
+
42
+ from .config import Price, resolve_timezone
43
+
44
+ CHARS_PER_TOKEN = 4
45
+ PER_MILLION = 1_000_000
46
+
47
+
48
+ class CostCapExceeded(ProviderError):
49
+ """The soft daily cap of ``class_name`` is spent (``spent`` >= ``cap`` USD) until ``resets_at`` (POSIX
50
+ seconds of the next local midnight). Not retryable before then."""
51
+
52
+ COST_CAP = "cost_cap"
53
+
54
+ def __init__(self, class_name: str, spent: float, cap: float, resets_at: float) -> None:
55
+ super().__init__(f"daily cost cap of class {class_name!r} reached: {spent:.4f} of {cap:.4f} USD spent "
56
+ "today", kind=self.COST_CAP, status=None)
57
+ self.class_name = class_name
58
+ self.spent = spent
59
+ self.cap = cap
60
+ self.resets_at = resets_at
61
+
62
+
63
+ class LedgerError(ProviderError):
64
+ """The cost ledger (``Storage``) failed; ``completion`` is the answer already received (after dispatch) or
65
+ None (before dispatch, nothing was sent). ``rexlib.run`` returns a partial result whose ``error`` is this."""
66
+
67
+ def __init__(self, message: str, completion: ChatCompletion | None = None) -> None:
68
+ super().__init__(message, kind=ProviderError.STORAGE)
69
+ self.completion = completion
70
+
71
+
72
+ def cost_usd(price: Price, usage: Usage) -> float:
73
+ """USD of one call: each token count times its price per million tokens."""
74
+ total = (usage.input_tokens * price.input + usage.output_tokens * price.output
75
+ + usage.cache_read_tokens * price.cache_read + usage.cache_write_tokens * price.cache_write)
76
+ return total / PER_MILLION
77
+
78
+
79
+ def estimate_usage(request: ChatRequest, completion: ChatCompletion) -> Usage:
80
+ """Input tokens from the characters of the request messages and tools, output tokens from the answer's
81
+ message (text and tool calls), about ``CHARS_PER_TOKEN`` characters per token, at least 1 each."""
82
+ sent = sum(len(_text_of(m)) for m in request.messages) + len(_dump(request.tools or []))
83
+ choice = completion.choices[0] if completion.choices else {}
84
+ answer = _dump(choice.get("message") or {})
85
+ return Usage(input_tokens=max(sent // CHARS_PER_TOKEN, 1), output_tokens=max(len(answer) // CHARS_PER_TOKEN, 1))
86
+
87
+
88
+ def _text_of(message: ChatMessage | Mapping[str, Any]) -> str:
89
+ if isinstance(message, ChatMessage):
90
+ return _dump(message.to_dict())
91
+ return _dump(message)
92
+
93
+
94
+ def _dump(value: Any) -> str:
95
+ return json.dumps(value, ensure_ascii=False, default=str)
96
+
97
+
98
+ def day_bounds(now: float, tz: datetime.tzinfo | None) -> tuple[float, float]:
99
+ """POSIX seconds of the midnight that starts the day of ``now`` in ``tz`` and of the next midnight (a day
100
+ may be 23 or 25 hours long around a daylight-saving change)."""
101
+ if tz is None:
102
+ today = datetime.datetime.fromtimestamp(now).date()
103
+ start = datetime.datetime.combine(today, datetime.time())
104
+ end = datetime.datetime.combine(today + datetime.timedelta(days=1), datetime.time())
105
+ else:
106
+ today = datetime.datetime.fromtimestamp(now, tz).date()
107
+ start = datetime.datetime.combine(today, datetime.time(), tzinfo=tz)
108
+ end = datetime.datetime.combine(today + datetime.timedelta(days=1), datetime.time(), tzinfo=tz)
109
+ return start.timestamp(), end.timestamp()
110
+
111
+
112
+ class CostMeter:
113
+ """The cost records of ``storage`` (rexlib design 2.1, "Costs"): what was spent per scope (a class, a user, a
114
+ project ...) and since when. The day starts at local midnight of ``timezone`` (a ``tzinfo``, an IANA name,
115
+ ``"UTC"``, or ``None`` = the system's local time) on the wall ``clock`` (POSIX seconds). Holds no totals of
116
+ its own: every answer comes from the storage, so it survives a restart and is shared by every meter and
117
+ gateway on the same storage. Safe to share between threads when the storage is."""
118
+
119
+ def __init__(self, storage: Storage, *, clock: Callable[[], float] = time.time,
120
+ timezone: datetime.tzinfo | str | None = None) -> None:
121
+ self.storage = storage
122
+ self.clock = clock
123
+ self.timezone = resolve_timezone(timezone) if isinstance(timezone, str) or timezone is None else timezone
124
+
125
+ def __repr__(self) -> str:
126
+ return f"CostMeter(storage={type(self.storage).__name__}, timezone={self.timezone!r})"
127
+
128
+ def day(self) -> tuple[float, float]:
129
+ """POSIX seconds of the last local midnight and of the next one."""
130
+ return day_bounds(self.clock(), self.timezone)
131
+
132
+ def spent(self, scope: str, since: float | None = None) -> float:
133
+ """USD recorded for ``scope`` since ``since`` (POSIX seconds; ``None`` = the last local midnight)."""
134
+ return self.storage.spent(scope, self.day()[0] if since is None else since)
135
+
136
+ def check(self, scope: str, cap: float | None) -> None:
137
+ """``CostCapExceeded`` when ``scope`` has spent ``cap`` USD or more today (``None`` = no cap)."""
138
+ if cap is None:
139
+ return
140
+ start, end = self.day()
141
+ spent = self.storage.spent(scope, start)
142
+ if spent >= cap:
143
+ raise CostCapExceeded(scope, spent, cap, end)
144
+
145
+ def record(self, entry: Mapping[str, Any]) -> None:
146
+ """Record one cost entry (``scope``, ``usd``, any further plain fields); ``ts`` defaults to ``clock()``."""
147
+ self.storage.record_cost({"ts": self.clock(), **entry})
148
+
149
+ def charge(self, scope: str, usage: Usage, price: Price | None, **fields: Any) -> dict[str, Any]:
150
+ """Record one call: ``usd`` = ``price`` x ``usage`` (0 when ``price`` is None: ``priced: false``), the
151
+ four token counts, ``ts``, plus ``fields`` (``model``, ``target``, ``estimated`` ...). Returns the entry."""
152
+ entry = {**fields, "scope": scope, "usd": cost_usd(price, usage) if price is not None else 0.0,
153
+ "ts": self.clock(), "input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens,
154
+ "cache_read_tokens": usage.cache_read_tokens, "cache_write_tokens": usage.cache_write_tokens,
155
+ "priced": price is not None}
156
+ self.storage.record_cost(entry)
157
+ return entry
rexlib/gateway/keys.py ADDED
@@ -0,0 +1,46 @@
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
+ """Key lookup for the router: the value of the variable a model entry names in ``key_env``, read at call time.
6
+
7
+ This is the only gateway module that reads the process environment (the rules test allows it here and nowhere
8
+ else in the gateway tier), and it reads only the variables named by ``key_env``. A key value is returned to the
9
+ provider object that sends it and is never put into a message, a notice, a cost record or a ``repr``; messages
10
+ name the variable, never its content.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from collections.abc import Callable, Mapping
17
+
18
+ KeyLookup = Callable[[str], str | None]
19
+
20
+
21
+ def key_lookup(env: Mapping[str, str] | None) -> KeyLookup:
22
+ """A function ``name -> key or None`` over ``env`` (a test's dict), or over the live process environment
23
+ when ``env`` is None (read on every call, so a key set or rotated later is seen; a blank or non-string value
24
+ counts as missing)."""
25
+ if env is None:
26
+ return _from_process
27
+ table = env
28
+
29
+ def lookup(name: str) -> str | None:
30
+ value = table.get(name)
31
+ return value.strip() or None if isinstance(value, str) else None # a non-str value counts as missing
32
+
33
+ return lookup
34
+
35
+
36
+ def _from_process(name: str) -> str | None:
37
+ return (os.environ.get(name) or "").strip() or None
38
+
39
+
40
+ def key_resolver(lookup: KeyLookup, name: str) -> Callable[[], str | None]:
41
+ """The ``api_key`` callable a provider calls before every request (``rexlib.providers.transport.ApiKey``)."""
42
+
43
+ def resolve() -> str | None:
44
+ return lookup(name)
45
+
46
+ return resolve
@@ -0,0 +1,59 @@
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
+ """Provider presets: the wire, base URL and key variable NAME of well-known endpoints (rexlib design 2.1).
6
+
7
+ A model entry names a preset (``preset = "openrouter"``) instead of spelling out ``provider``, ``base_url`` and
8
+ ``key_env``; its own ``base_url`` / ``key_env`` still win. ``PRESETS`` is read-only (rexlib keeps no process-wide
9
+ state); an app adds its own presets by passing an extended table::
10
+
11
+ presets = {**rexlib.gateway.PRESETS, "office": Preset("openai-compatible", "https://llm.example/v1", "OFFICE_KEY")}
12
+ config = GatewayConfig.from_dict(data, presets=presets)
13
+
14
+ URL rule (``rexlib.wire.openai_chat.api_root``): a bare host gets ``/v1``; any other path is the API root
15
+ (Gemini's ``/v1beta/openai``). Local proxies carry no key variable; a model entry may name one (``key_env``).
16
+
17
+ Public sources, re-verified 2026-11-29 (rexlib step G1): Anthropic API overview (``https://api.anthropic.com``,
18
+ ``POST /v1/messages``; ``ANTHROPIC_API_KEY`` is the SDKs' variable), OpenAI API reference
19
+ (``https://api.openai.com/v1``, ``$OPENAI_API_KEY`` in the examples), OpenRouter quickstart
20
+ (``https://openrouter.ai/api/v1``, ``OPENROUTER_API_KEY``), Gemini OpenAI compatibility
21
+ (``https://generativelanguage.googleapis.com/v1beta/openai/``, ``GEMINI_API_KEY``), NVIDIA NIM LLM API reference
22
+ (``https://integrate.api.nvidia.com/v1/chat/completions``; the page names no variable, ``NVIDIA_API_KEY`` is the
23
+ common convention), Ollama OpenAI compatibility (``http://localhost:11434/v1``, key ignored locally). ``kiko`` and
24
+ ``cgw`` are rex's own local proxies (kiko on 127.0.0.1:4000, cgw ``scripts/claude_cli_gateway.py`` moved to
25
+ 127.0.0.1:4100 when kiko holds 4000, as in rex's ``docs/CONNECTING-MODELS.md``).
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from collections.abc import Mapping
31
+ from dataclasses import dataclass
32
+ from types import MappingProxyType
33
+
34
+ ANTHROPIC = "anthropic"
35
+ OPENAI_COMPATIBLE = "openai-compatible"
36
+ FAKE = "fake" # a scripted provider for tests (no URL, no key)
37
+ PROVIDERS = (ANTHROPIC, OPENAI_COMPATIBLE, FAKE)
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class Preset:
42
+ """Defaults for a model entry: ``provider`` (a name of ``PROVIDERS``), ``base_url``, ``key_env`` (the NAME of
43
+ the environment variable holding the key, never the key; ``None`` = no key)."""
44
+
45
+ provider: str
46
+ base_url: str
47
+ key_env: str | None = None
48
+
49
+
50
+ PRESETS: Mapping[str, Preset] = MappingProxyType({
51
+ "anthropic": Preset(ANTHROPIC, "https://api.anthropic.com", "ANTHROPIC_API_KEY"),
52
+ "openai": Preset(OPENAI_COMPATIBLE, "https://api.openai.com/v1", "OPENAI_API_KEY"),
53
+ "openrouter": Preset(OPENAI_COMPATIBLE, "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"),
54
+ "gemini": Preset(OPENAI_COMPATIBLE, "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"),
55
+ "nvidia": Preset(OPENAI_COMPATIBLE, "https://integrate.api.nvidia.com/v1", "NVIDIA_API_KEY"),
56
+ "ollama": Preset(OPENAI_COMPATIBLE, "http://127.0.0.1:11434/v1"),
57
+ "kiko": Preset(OPENAI_COMPATIBLE, "http://127.0.0.1:4000/v1"),
58
+ "cgw": Preset(OPENAI_COMPATIBLE, "http://127.0.0.1:4100/v1"),
59
+ })