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
rexlib/messages.py ADDED
@@ -0,0 +1,221 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
3
+ # AI models: nvidia nemotron ultra, claude-opus-5-5, claude-sonnet-5-5
4
+ # Licensed under MIT License
5
+ """Chat message types in the OpenAI chat-completions shape, plus provider-neutral token usage.
6
+
7
+ One class set (before rexlib, rex had two copies of these classes with small differences). Construction from
8
+ API JSON ignores keys a class does not know: servers add fields over time (``system_fingerprint``,
9
+ ``service_tier``, ...). ``usage`` stays the raw dict the server sent; ``token_usage`` gives it as a ``Usage``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field, fields
15
+ from typing import Any
16
+
17
+
18
+ def _known_fields(cls: type, data: dict[str, Any]) -> dict[str, Any]:
19
+ """Keep only the keys of ``data`` that are fields of dataclass ``cls``."""
20
+ names = {f.name for f in fields(cls)}
21
+ return {k: v for k, v in data.items() if k in names}
22
+
23
+
24
+ def _count(value: Any) -> int:
25
+ try:
26
+ number = int(value or 0)
27
+ except (TypeError, ValueError):
28
+ return 0
29
+ return max(number, 0)
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Usage:
34
+ """Tokens of one model call. ``input_tokens`` excludes cache reads and cache writes, which are counted apart
35
+ (each has its own price)."""
36
+
37
+ input_tokens: int = 0
38
+ output_tokens: int = 0
39
+ cache_read_tokens: int = 0
40
+ cache_write_tokens: int = 0
41
+
42
+ @property
43
+ def total_tokens(self) -> int:
44
+ return self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens
45
+
46
+ @classmethod
47
+ def from_dict(cls, data: dict[str, Any] | None) -> Usage | None:
48
+ """Usage from an OpenAI Chat (``prompt_tokens``, ``prompt_tokens_details.cached_tokens``; LiteLLM adds
49
+ ``cache_creation_input_tokens``, also counted in ``prompt_tokens``), OpenAI Responses (``input_tokens``,
50
+ ``input_tokens_details.cached_tokens``, counted in ``input_tokens``) or Anthropic (``input_tokens``,
51
+ ``cache_read_input_tokens``, ``cache_creation_input_tokens``, counted apart) usage object."""
52
+ if not isinstance(data, dict):
53
+ return None
54
+ written = _count(data.get("cache_creation_input_tokens"))
55
+ if "prompt_tokens" in data or "completion_tokens" in data:
56
+ cached = _detail(data, "prompt_tokens_details")
57
+ return cls(input_tokens=max(_count(data.get("prompt_tokens")) - cached - written, 0),
58
+ output_tokens=_count(data.get("completion_tokens")), cache_read_tokens=cached,
59
+ cache_write_tokens=written)
60
+ cached = _detail(data, "input_tokens_details")
61
+ return cls(input_tokens=max(_count(data.get("input_tokens")) - cached, 0),
62
+ output_tokens=_count(data.get("output_tokens")),
63
+ cache_read_tokens=_count(data.get("cache_read_input_tokens")) + cached, cache_write_tokens=written)
64
+
65
+
66
+ def _detail(data: dict[str, Any], key: str) -> int:
67
+ """``data[key]["cached_tokens"]`` as a count (0 when missing or not a dict)."""
68
+ details = data.get(key)
69
+ return _count(details.get("cached_tokens")) if isinstance(details, dict) else 0
70
+
71
+
72
+ @dataclass
73
+ class ToolCall:
74
+ id: str
75
+ type: str = "function"
76
+ function: dict[str, Any] = field(default_factory=dict)
77
+ # Position of the call in a streamed response. Only set on stream deltas;
78
+ # continuation deltas carry the index but no id. Never sent to the API.
79
+ index: int | None = None
80
+
81
+ def to_dict(self) -> dict[str, Any]:
82
+ return {"id": self.id, "type": self.type, "function": self.function}
83
+
84
+ @classmethod
85
+ def from_dict(cls, data: dict[str, Any]) -> ToolCall:
86
+ index = data.get("index")
87
+ return cls(
88
+ id=data.get("id") or "",
89
+ type=data.get("type") or "function",
90
+ function=data.get("function") or {},
91
+ index=index if isinstance(index, int) else None,
92
+ )
93
+
94
+
95
+ @dataclass
96
+ class ChatMessage:
97
+ role: str
98
+ content: str | None = None
99
+ tool_calls: list[ToolCall] | None = None
100
+ tool_call_id: str | None = None
101
+
102
+ def to_dict(self) -> dict[str, Any]:
103
+ d: dict[str, Any] = {"role": self.role}
104
+ if self.content is not None:
105
+ d["content"] = self.content
106
+ if self.tool_calls:
107
+ d["tool_calls"] = [tc.to_dict() for tc in self.tool_calls]
108
+ if self.tool_call_id:
109
+ d["tool_call_id"] = self.tool_call_id
110
+ return d
111
+
112
+ @classmethod
113
+ def from_dict(cls, data: dict[str, Any]) -> ChatMessage:
114
+ """Inverse of ``to_dict``; unknown keys are ignored."""
115
+ tcs = data.get("tool_calls")
116
+ return cls(
117
+ role=data.get("role") or "user",
118
+ content=data.get("content"),
119
+ tool_calls=[ToolCall.from_dict(tc) for tc in tcs] if tcs else None,
120
+ tool_call_id=data.get("tool_call_id"),
121
+ )
122
+
123
+ @classmethod
124
+ def user(cls, content: str) -> ChatMessage:
125
+ return cls(role="user", content=content)
126
+
127
+ @classmethod
128
+ def assistant(cls, content: str | None = None, tool_calls: list[ToolCall] | None = None) -> ChatMessage:
129
+ return cls(role="assistant", content=content, tool_calls=tool_calls)
130
+
131
+ @classmethod
132
+ def system(cls, content: str) -> ChatMessage:
133
+ return cls(role="system", content=content)
134
+
135
+ @classmethod
136
+ def tool(cls, tool_call_id: str, content: str) -> ChatMessage:
137
+ return cls(role="tool", content=content, tool_call_id=tool_call_id)
138
+
139
+
140
+ @dataclass
141
+ class ChatCompletionChunk:
142
+ """One streamed delta. Every field has a default: an error-only or usage-only chunk is still a chunk."""
143
+
144
+ id: str = ""
145
+ model: str = ""
146
+ choices: list[dict[str, Any]] = field(default_factory=list)
147
+ created: int = 0
148
+ object: str = "chat.completion.chunk"
149
+ error: Any = None
150
+ usage: dict[str, Any] | None = None
151
+
152
+ @classmethod
153
+ def from_dict(cls, data: dict[str, Any]) -> ChatCompletionChunk:
154
+ """Build from API JSON, ignoring fields this class does not know. ``ValueError`` for a shape no server
155
+ sends: ``choices`` not a list of objects, a ``delta`` that is not an object, ``usage`` not an object."""
156
+ if not isinstance(data, dict):
157
+ raise ValueError("a stream chunk must be a JSON object")
158
+ choices = data.get("choices") or []
159
+ if not isinstance(choices, list) or not all(isinstance(c, dict) for c in choices):
160
+ raise ValueError("chunk 'choices' must be a list of objects")
161
+ if not all(isinstance(c.get("delta") or {}, dict) for c in choices):
162
+ raise ValueError("chunk 'delta' must be an object")
163
+ if data.get("usage") is not None and not isinstance(data["usage"], dict):
164
+ raise ValueError("chunk 'usage' must be an object")
165
+ return cls(**_known_fields(cls, data))
166
+
167
+ @property
168
+ def delta(self) -> dict[str, Any]:
169
+ delta: dict[str, Any] = self.choices[0].get("delta", {}) if self.choices else {}
170
+ return delta
171
+
172
+ @property
173
+ def content(self) -> str | None:
174
+ return self.delta.get("content")
175
+
176
+ @property
177
+ def tool_calls(self) -> list[ToolCall] | None:
178
+ tcs = self.delta.get("tool_calls")
179
+ if tcs:
180
+ return [ToolCall.from_dict(tc) for tc in tcs]
181
+ return None
182
+
183
+ @property
184
+ def finish_reason(self) -> str | None:
185
+ return self.choices[0].get("finish_reason") if self.choices else None
186
+
187
+ @property
188
+ def token_usage(self) -> Usage | None:
189
+ return Usage.from_dict(self.usage)
190
+
191
+
192
+ @dataclass
193
+ class ChatCompletion:
194
+ id: str
195
+ model: str
196
+ choices: list[dict[str, Any]]
197
+ created: int
198
+ object: str = "chat.completion"
199
+ usage: dict[str, Any] | None = None
200
+
201
+ @classmethod
202
+ def from_dict(cls, data: dict[str, Any]) -> ChatCompletion:
203
+ """Build from API JSON, ignoring fields this class does not know."""
204
+ return cls(**_known_fields(cls, data))
205
+
206
+ @property
207
+ def message(self) -> ChatMessage:
208
+ choice = self.choices[0] if self.choices else {}
209
+ msg_data = choice.get("message", {})
210
+ tool_calls = None
211
+ if msg_data.get("tool_calls"):
212
+ tool_calls = [ToolCall.from_dict(tc) for tc in msg_data["tool_calls"]]
213
+ return ChatMessage(
214
+ role=msg_data.get("role", "assistant"),
215
+ content=msg_data.get("content"),
216
+ tool_calls=tool_calls,
217
+ )
218
+
219
+ @property
220
+ def token_usage(self) -> Usage | None:
221
+ return Usage.from_dict(self.usage)
@@ -0,0 +1,11 @@
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
+ """Model clients: ``ChatRequest``, the ``Provider`` protocol, ``ProviderError``; ``OpenAIChat`` and
6
+ ``AnthropicMessages`` live in ``rexlib.providers.openai`` and ``rexlib.providers.anthropic`` (not imported here, so ``rexlib.wire`` can use ``ChatRequest`` without a cycle)."""
7
+
8
+ from .base import ChatRequest, Provider
9
+ from .errors import ProviderError
10
+
11
+ __all__ = ["ChatRequest", "Provider", "ProviderError"]
@@ -0,0 +1,108 @@
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
+ """``AnthropicMessages``: a client for the Anthropic Messages API, same shape as ``OpenAIChat``.
6
+
7
+ Public source: the Anthropic API reference (``POST /v1/messages``, headers ``x-api-key`` and
8
+ ``anthropic-version``, streaming events, errors). Requests and answers use rexlib's OpenAI-shaped types; the
9
+ mapping is ``rexlib.wire.anthropic_messages``. One HTTP attempt per call; failures raise ``ProviderError``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable, Iterator
15
+ from typing import Any
16
+ from urllib.parse import urlsplit, urlunsplit
17
+
18
+ from ..messages import ChatCompletion, ChatCompletionChunk
19
+ from ..wire import anthropic_messages as wire
20
+ from .base import ChatRequest
21
+ from .errors import display_url
22
+ from .http import CONNECT_TIMEOUT, StdlibHttp
23
+ from .openai import READ_TIMEOUT
24
+ from .transport import CHUNK_ERRORS, ApiKey, JsonEndpoint, check_endpoint, close_quietly
25
+
26
+ _ALWAYS_SENT = frozenset({"model", "messages", "max_tokens", "stream"})
27
+
28
+
29
+ class AnthropicMessages:
30
+ """``complete(request)`` and ``stream(request)`` over ``POST <base>/v1/messages``.
31
+
32
+ ``base_url``: the API host, with or without ``/v1``. ``api_key``, ``timeout``, ``connect_timeout`` and
33
+ ``http_backend`` work as for ``OpenAIChat``. ``max_tokens`` (required by Anthropic) comes from the request,
34
+ else from the model name (``rexlib.wire.anthropic_messages.model_max_tokens``). The attribute
35
+ ``stream_deadline``: as for ``OpenAIChat`` (seconds for a whole stream, None = no limit). ``request.extra`` fields
36
+ (``thinking``, ``metadata``, ``top_k`` ...) are added to the request unless ``deny`` names them.
37
+ """
38
+
39
+ def __init__(self, base_url: str, api_key: ApiKey, model: str, *, timeout: float = READ_TIMEOUT,
40
+ connect_timeout: float = CONNECT_TIMEOUT, http_backend: Any = None,
41
+ deny: Iterable[str] | None = None) -> None:
42
+ parts = urlsplit(base_url.strip())
43
+ self.stream_deadline: float | None = None # seconds for a whole stream; set after construction
44
+ self.api_base = urlunsplit((parts.scheme, parts.netloc, parts.path.rstrip("/").removesuffix("/v1"), "", ""))
45
+ check_endpoint(base_url.strip(), api_key)
46
+ self.model = model
47
+ self.timeout = timeout
48
+ self.deny = frozenset(deny or ())
49
+ http = http_backend if http_backend is not None else StdlibHttp(connect_timeout)
50
+ url = self.api_base + "/v1/messages" + (f"?{parts.query}" if parts.query else "")
51
+ self._endpoint = JsonEndpoint(url, api_key, timeout, http)
52
+
53
+ def __repr__(self) -> str:
54
+ return f"AnthropicMessages({display_url(self.api_base)!r}, model={self.model!r})" # never a credential
55
+
56
+ def complete(self, request: ChatRequest) -> ChatCompletion:
57
+ """One answer (OpenAI shape, usage with cache tokens). ``ProviderError`` on failure."""
58
+ ep = self._endpoint
59
+ key = ep.resolve_key()
60
+ resp = ep.post(self._payload(request, stream=False), self._headers(False, key), stream=False, key=key)
61
+ ep.raise_for_status(resp, key)
62
+ data = ep.read_json(resp, key)
63
+ try:
64
+ return wire.parse_message(data)
65
+ except ValueError as exc:
66
+ raise ep.bad_response(exc, getattr(resp, "status", None)) from exc
67
+
68
+ def stream(self, request: ChatRequest) -> Iterator[ChatCompletionChunk]:
69
+ """Chunks as they arrive; the last one carries the finish reason and the usage (input and cache tokens from
70
+ ``message_start``, output tokens from ``message_delta``; no usage when the stream sent none). An ``error``
71
+ event raises; a body that ends before ``message_stop`` (and without a stop reason) raises
72
+ ``ProviderError`` (``network``). The response is closed when the stream ends or the generator is closed
73
+ (also on ``KeyboardInterrupt``). Event data that is not JSON, or an event of a shape no server sends (a
74
+ ``message`` that is no object, a ``delta`` list, a block without ``index``), raises ``ProviderError``
75
+ (``bad_response``); no data event within the read timeout or a stream longer than ``stream_deadline``
76
+ raises ``ProviderError`` (``timeout``)."""
77
+ ep = self._endpoint
78
+ key = ep.resolve_key()
79
+ resp = ep.post(self._payload(request, stream=True), self._headers(True, key), stream=True, key=key)
80
+ try:
81
+ ep.raise_for_status(resp, key)
82
+ chunks = wire.events_to_chunks(ep.events(resp, key, self.stream_deadline), request.model or self.model,
83
+ strict=True)
84
+ while True:
85
+ try:
86
+ chunk = ChatCompletionChunk.from_dict(next(chunks))
87
+ except StopIteration:
88
+ return
89
+ except CHUNK_ERRORS as exc: # broken JSON (a NUL byte, a cut object) or a shape no server sends
90
+ raise ep.bad_response(exc) from exc
91
+ yield chunk
92
+ finally:
93
+ close_quietly(resp)
94
+
95
+ def _payload(self, request: ChatRequest, stream: bool) -> dict[str, Any]:
96
+ payload = wire.build_request(wire.chat_body(request, self.model), stream=stream)
97
+ for key, value in request.extra.items():
98
+ payload.setdefault(key, value)
99
+ return {k: v for k, v in payload.items() if k in _ALWAYS_SENT or k not in self.deny}
100
+
101
+ @staticmethod
102
+ def _headers(stream: bool, key: str | None) -> dict[str, str]:
103
+ headers = {"Content-Type": "application/json", "anthropic-version": wire.ANTHROPIC_VERSION}
104
+ if key:
105
+ headers["x-api-key"] = key
106
+ if stream:
107
+ headers["Accept"] = "text/event-stream"
108
+ return headers
@@ -0,0 +1,53 @@
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
+ """``ChatRequest`` (one model call, provider-neutral) and the ``Provider`` protocol every client implements."""
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterator, Mapping, Sequence
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Protocol, runtime_checkable
12
+
13
+ from ..messages import ChatCompletion, ChatCompletionChunk, ChatMessage
14
+
15
+ _CREDENTIAL_KEYS = frozenset({"api_key", "apikey", "authorization", "x_api_key", "key", "access_token", "token"})
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class ChatRequest:
20
+ """One model call.
21
+
22
+ ``messages`` are ``ChatMessage`` objects or plain dicts in the OpenAI message shape; a dict is sent as given
23
+ (minus the provider's deny-list), so vendor fields such as Gemini's ``extra_content.google.thought_signature``,
24
+ DeepSeek's ``reasoning_content`` or OpenRouter's ``reasoning_details`` survive a round trip when the caller
25
+ passes the raw assistant message back. ``model`` None means the provider's default model. ``None`` and empty
26
+ values are left out of the request. ``extra`` holds further request fields (``reasoning_effort``, ``seed``,
27
+ ``response_format``, a vendor's own keys ...); they are sent unless the provider's deny-list names them.
28
+ Credential-looking ``extra`` keys (``api_key``, ``authorization``, ``x-api-key`` ...) are refused with
29
+ ``ValueError``: keys belong to the provider object, never into a request body.
30
+ """
31
+
32
+ messages: Sequence[ChatMessage | Mapping[str, Any]]
33
+ model: str | None = None
34
+ tools: Sequence[Mapping[str, Any]] | None = None
35
+ tool_choice: str | Mapping[str, Any] | None = None
36
+ temperature: float | None = None
37
+ max_tokens: int | None = None
38
+ extra: Mapping[str, Any] = field(default_factory=dict)
39
+
40
+ def __post_init__(self) -> None:
41
+ bad = sorted(k for k in self.extra if k.lower().replace("-", "_") in _CREDENTIAL_KEYS)
42
+ if bad:
43
+ raise ValueError(f"ChatRequest.extra must not carry credentials: {', '.join(bad)}")
44
+
45
+
46
+ @runtime_checkable
47
+ class Provider(Protocol):
48
+ """A model client: ``complete`` returns the whole answer; ``stream`` yields chunks, the last carrying usage
49
+ when the server sends it. Both raise ``ProviderError`` on failure."""
50
+
51
+ def complete(self, request: ChatRequest) -> ChatCompletion: ...
52
+
53
+ def stream(self, request: ChatRequest) -> Iterator[ChatCompletionChunk]: ...
@@ -0,0 +1,191 @@
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
+ """``ProviderError``: one exception for every failed model call, with a category a caller can act on.
6
+
7
+ Categories (``ProviderError.kind``) follow the HTTP meanings the provider API documentation gives (OpenAI and
8
+ Anthropic error-code pages): ``auth`` (401, 403: fix the key, do not retry), ``rate_limit`` (429: retry after
9
+ ``retry_after`` seconds when the server sent ``Retry-After``), ``server`` (5xx, including Anthropic's 529
10
+ "overloaded"), ``timeout`` (408, or no answer in time), ``network`` (connect refused, connection lost),
11
+ ``bad_request`` (any other 4xx: the request itself is wrong, every model would refuse it), ``bad_response`` (the
12
+ server answered with something that is not the expected JSON, or a line longer than the limit) and ``tls`` (the
13
+ server's certificate failed verification: a configuration or interception problem, never retried); the gateway
14
+ adds ``storage`` (its cost ledger failed) and ``unsupported`` (the call is not available; kept for providers
15
+ that cannot stream). ``retryable`` is true for ``rate_limit``, ``server``, ``timeout`` and ``network``.
16
+
17
+ The message never contains a credential: the URL is shown without user info and with credential-like query
18
+ values (``key``, ``token``, ``sig`` ...) replaced by ``***``, and a server that echoes the key or such a value in
19
+ its error text gets it replaced by ``***`` before the text is stored.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import email.utils
25
+ import math
26
+ import ssl
27
+ import time
28
+ from collections.abc import Iterable, Mapping
29
+ from datetime import timezone
30
+ from types import MappingProxyType
31
+ from typing import Any
32
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
33
+
34
+ DETAIL_CHARS = 300 # server error text kept in the message (whitespace collapsed)
35
+ RETRY_AFTER_MAX = 3600.0 # seconds; a longer Retry-After is capped (a broken or hostile server must not park us)
36
+ _CREDENTIAL_WORDS = ("key", "token", "secret", "sig", "auth", "password", "credential")
37
+
38
+
39
+ class ProviderError(RuntimeError):
40
+ """A failed model call. ``status`` is the HTTP status (None for network errors and timeouts)."""
41
+
42
+ AUTH = "auth"
43
+ RATE_LIMIT = "rate_limit"
44
+ SERVER = "server"
45
+ TIMEOUT = "timeout"
46
+ NETWORK = "network"
47
+ BAD_REQUEST = "bad_request"
48
+ BAD_RESPONSE = "bad_response"
49
+ TLS = "tls"
50
+ STORAGE = "storage"
51
+ UNSUPPORTED = "unsupported"
52
+ RETRYABLE_KINDS = frozenset({RATE_LIMIT, SERVER, TIMEOUT, NETWORK})
53
+
54
+ def __init__(self, message: str, *, kind: str, status: int | None = None, retry_after: float | None = None,
55
+ detail: str = "") -> None:
56
+ super().__init__(message)
57
+ self.kind = kind
58
+ self.status = status
59
+ self.retry_after = retry_after
60
+ self.detail = detail
61
+
62
+ @property
63
+ def retryable(self) -> bool:
64
+ return self.kind in self.RETRYABLE_KINDS
65
+
66
+ def __repr__(self) -> str:
67
+ return f"ProviderError({str(self)!r}, kind={self.kind!r}, status={self.status!r})"
68
+
69
+
70
+ def kind_for_status(status: int) -> str:
71
+ """Category of an HTTP error status (>= 400)."""
72
+ if status in (401, 403):
73
+ return ProviderError.AUTH
74
+ if status == 429:
75
+ return ProviderError.RATE_LIMIT
76
+ if status == 408:
77
+ return ProviderError.TIMEOUT
78
+ if status >= 500:
79
+ return ProviderError.SERVER
80
+ return ProviderError.BAD_REQUEST
81
+
82
+
83
+ # OpenAI-style error ``code`` / ``type`` strings (OpenAI error-code documentation; LiteLLM and OpenRouter use the
84
+ # same names) -> kind, for errors that arrive without an HTTP status (an error event inside a stream).
85
+ _CODE_KINDS: Mapping[str, str] = MappingProxyType({
86
+ "invalid_api_key": ProviderError.AUTH, "authentication_error": ProviderError.AUTH,
87
+ "permission_error": ProviderError.AUTH, "unauthorized": ProviderError.AUTH,
88
+ "insufficient_quota": ProviderError.AUTH, # billing: surface it, a retry cannot help
89
+ "rate_limit_exceeded": ProviderError.RATE_LIMIT, "rate_limit_error": ProviderError.RATE_LIMIT,
90
+ "context_length_exceeded": ProviderError.BAD_REQUEST, "invalid_request_error": ProviderError.BAD_REQUEST,
91
+ "model_not_found": ProviderError.BAD_REQUEST, "not_found_error": ProviderError.BAD_REQUEST,
92
+ "content_filter": ProviderError.BAD_REQUEST, "server_error": ProviderError.SERVER,
93
+ "overloaded_error": ProviderError.SERVER, "api_error": ProviderError.SERVER,
94
+ })
95
+
96
+
97
+ def kind_for_error(code: Any, error_type: Any = None) -> str:
98
+ """Kind of an error object without an HTTP status: an int ``code`` >= 400 as a status, else the known
99
+ ``code`` or ``type`` string, else ``server``."""
100
+ if isinstance(code, int) and not isinstance(code, bool) and code >= 400:
101
+ return kind_for_status(code)
102
+ for name in (code, error_type):
103
+ if isinstance(name, str) and name.lower() in _CODE_KINDS:
104
+ return _CODE_KINDS[name.lower()]
105
+ return ProviderError.SERVER
106
+
107
+
108
+ def _is_credential_name(name: str) -> bool:
109
+ lowered = name.lower()
110
+ return any(word in lowered for word in _CREDENTIAL_WORDS)
111
+
112
+
113
+ def url_secrets(url: str) -> list[str]:
114
+ """Credential values carried in a URL: the user-info user and password and credential-like query values."""
115
+ parts = urlsplit(url)
116
+ found = [v for v in (parts.username, parts.password) if v]
117
+ found += [v for k, v in parse_qsl(parts.query, keep_blank_values=True) if v and _is_credential_name(k)]
118
+ return found
119
+
120
+
121
+ def display_url(url: str) -> str:
122
+ """``url`` safe to show: no user info, credential-like query values replaced by ``***``."""
123
+ parts = urlsplit(url)
124
+ netloc = parts.netloc.rpartition("@")[2]
125
+ query = urlencode([(k, "***" if _is_credential_name(k) else v)
126
+ for k, v in parse_qsl(parts.query, keep_blank_values=True)], safe="*")
127
+ return urlunsplit((parts.scheme, netloc, parts.path, query, parts.fragment))
128
+
129
+
130
+ def _secret_list(secrets: str | Iterable[str] | None) -> list[str]:
131
+ if not secrets:
132
+ return []
133
+ return [secrets] if isinstance(secrets, str) else [s for s in secrets if s]
134
+
135
+
136
+ def clip_detail(raw: Any, secrets: str | Iterable[str] | None = None) -> str:
137
+ """Server error text for a message: decoded, whitespace collapsed, ``secrets`` masked, at most 300 chars."""
138
+ text = raw.decode("utf-8", "replace") if isinstance(raw, (bytes, bytearray)) else str(raw or "")
139
+ for secret in sorted(_secret_list(secrets), key=len, reverse=True):
140
+ text = text.replace(secret, "***")
141
+ return " ".join(text.split())[:DETAIL_CHARS]
142
+
143
+
144
+ def retry_after_seconds(value: str | None, now: float | None = None) -> float | None:
145
+ """``Retry-After`` header (seconds or an HTTP date, RFC 9110 section 10.2.3) as seconds in 0..3600, or None
146
+ (missing, not a finite number, not a date). A date without a zone is taken as UTC."""
147
+ if not value:
148
+ return None
149
+ value = value.strip()
150
+ try:
151
+ seconds = float(value)
152
+ except ValueError:
153
+ try:
154
+ when = email.utils.parsedate_to_datetime(value)
155
+ except (TypeError, ValueError, IndexError):
156
+ return None
157
+ if when.tzinfo is None:
158
+ when = when.replace(tzinfo=timezone.utc)
159
+ seconds = when.timestamp() - (time.time() if now is None else now)
160
+ if not math.isfinite(seconds):
161
+ return None
162
+ return min(max(seconds, 0.0), RETRY_AFTER_MAX)
163
+
164
+
165
+ def http_error(status: int, url: str, body: Any = b"", headers: Any = None,
166
+ secret: str | Iterable[str] | None = None) -> ProviderError:
167
+ """``ProviderError`` for an HTTP error answer: ``HTTP <status> from <display url>[: <detail>]``.
168
+ ``retry_after`` is read on 429, 503 and Anthropic's 529 "overloaded" (each may carry ``Retry-After``)."""
169
+ detail = clip_detail(body, _secret_list(secret) + url_secrets(url))
170
+ retry_after = None
171
+ getter = getattr(headers, "get", None)
172
+ if status in (429, 503, 529) and callable(getter):
173
+ retry_after = retry_after_seconds(getter("Retry-After"))
174
+ message = f"HTTP {status} from {display_url(url)}" + (f": {detail}" if detail else "")
175
+ return ProviderError(message, kind=kind_for_status(status), status=status, retry_after=retry_after, detail=detail)
176
+
177
+
178
+ def transport_error(exc: BaseException, url: str, secret: str | Iterable[str] | None = None) -> ProviderError:
179
+ """``ProviderError`` for an exception raised by the HTTP backend (any backend: matched by type and name;
180
+ kikolib's ``TLSVerifyError`` and ``HttpTimeout`` included)."""
181
+ if isinstance(exc, ProviderError):
182
+ return exc
183
+ name = type(exc).__name__.lower()
184
+ if isinstance(exc, ssl.SSLCertVerificationError) or "tlsverify" in name or "certverif" in name:
185
+ kind = ProviderError.TLS
186
+ elif isinstance(exc, TimeoutError) or "timeout" in name:
187
+ kind = ProviderError.TIMEOUT
188
+ else:
189
+ kind = ProviderError.NETWORK
190
+ detail = clip_detail(f"{type(exc).__name__}: {exc}", _secret_list(secret) + url_secrets(url))
191
+ return ProviderError(f"{kind} error calling {display_url(url)}: {detail}", kind=kind, detail=detail)