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/loop/core.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
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
|
+
"""``run()``: model call, tool calls, repeat; see ``rexlib.loop`` for the contract."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
from collections.abc import Iterable, Iterator, Mapping, Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ..messages import ChatCompletionChunk, ChatMessage, Usage
|
|
14
|
+
from ..providers.base import ChatRequest, Provider
|
|
15
|
+
from ..providers.errors import ProviderError
|
|
16
|
+
from ..tools.base import Tool
|
|
17
|
+
from ..tools.registry import ToolRegistry
|
|
18
|
+
from .calls import ToolRunner, unique_calls
|
|
19
|
+
from .options import LoopHooks, RunOptions, RunResult, RunStatus, Stop
|
|
20
|
+
from .stream import estimate_usage, fold_stream, stream_error
|
|
21
|
+
|
|
22
|
+
_REFUSALS = frozenset({"content_filter", "refusal"})
|
|
23
|
+
_DEFAULT_OPTIONS = RunOptions()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _ProviderFailed(Exception):
|
|
27
|
+
"""A ``ProviderError`` raised by the provider (not by a hook), carried up to ``run``."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, error: ProviderError) -> None:
|
|
30
|
+
super().__init__(str(error))
|
|
31
|
+
self.error = error
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _PricingFailed(Exception):
|
|
35
|
+
"""Pricing a finished call failed (``cost_fn`` or ``prices`` raised); ``message`` is the answer received."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, reason: str) -> None:
|
|
38
|
+
super().__init__(reason)
|
|
39
|
+
self.reason = reason
|
|
40
|
+
self.message: dict[str, Any] = {}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run(provider: Provider, messages: Sequence[ChatMessage | Mapping[str, Any]],
|
|
44
|
+
tools: ToolRegistry | Iterable[Tool] | None = None, hooks: LoopHooks | None = None, *,
|
|
45
|
+
options: RunOptions | None = None) -> RunResult:
|
|
46
|
+
"""Run the model with tools until it answers or a limit stops it. ``tools`` is a ``ToolRegistry`` or any
|
|
47
|
+
iterable of ``Tool`` objects; ``options`` None means ``RunOptions()``."""
|
|
48
|
+
options = options or _DEFAULT_OPTIONS
|
|
49
|
+
if options.cost_fn is not None and options.prices is not None:
|
|
50
|
+
raise ValueError("give RunOptions.cost_fn or RunOptions.prices, not both")
|
|
51
|
+
if options.limits.cost_cap_usd is not None and options.cost_fn is None and options.prices is None:
|
|
52
|
+
raise ValueError("Limits.cost_cap_usd needs RunOptions.cost_fn (a callable (usage, model) -> USD) or "
|
|
53
|
+
"RunOptions.prices (a price table)")
|
|
54
|
+
_check_prices(options)
|
|
55
|
+
state = _Run(provider, messages, _tool_table(tools), hooks or LoopHooks(), options)
|
|
56
|
+
while True:
|
|
57
|
+
stop = state.check_limits()
|
|
58
|
+
if stop is None and state.hooks.before_model is not None:
|
|
59
|
+
stop = state.hooks.before_model(state.turns, state.messages)
|
|
60
|
+
if stop is not None:
|
|
61
|
+
return state.result(stop.status, stop.reason)
|
|
62
|
+
try:
|
|
63
|
+
message, finish = state.call_model()
|
|
64
|
+
except _ProviderFailed as failed:
|
|
65
|
+
return state.result(RunStatus.ERROR, str(failed.error), failed.error)
|
|
66
|
+
except _PricingFailed as failed: # the answer is kept, its unanswered tool calls dropped (valid history)
|
|
67
|
+
failed.message.pop("tool_calls", None)
|
|
68
|
+
state.messages.append(failed.message)
|
|
69
|
+
return state.result(RunStatus.ERROR, failed.reason)
|
|
70
|
+
if finish == "length": # unfinished tool calls are dropped: the history stays valid
|
|
71
|
+
message.pop("tool_calls", None)
|
|
72
|
+
elif message.get("tool_calls"):
|
|
73
|
+
message["tool_calls"] = unique_calls(message["tool_calls"], state.turns)
|
|
74
|
+
state.messages.append(message)
|
|
75
|
+
if finish == "length":
|
|
76
|
+
return state.result(RunStatus.MAX_TOKENS)
|
|
77
|
+
if finish in _REFUSALS:
|
|
78
|
+
return state.result(RunStatus.REFUSED)
|
|
79
|
+
if not message.get("tool_calls"):
|
|
80
|
+
return state.result(RunStatus.COMPLETE)
|
|
81
|
+
state.messages.extend(state.runner.run_all(message["tool_calls"]))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _check_prices(options: RunOptions) -> None:
|
|
85
|
+
"""``RunOptions.prices`` must price ``RunOptions.model`` before any call is made: a zero ``Usage`` is priced
|
|
86
|
+
once (a ``ModelPrices`` without ``model``, or an unknown or unpriced name, fails here, not after a paid call)."""
|
|
87
|
+
if options.prices is None:
|
|
88
|
+
return
|
|
89
|
+
try:
|
|
90
|
+
options.prices.cost(Usage(), options.model)
|
|
91
|
+
except Exception as exc:
|
|
92
|
+
raise ValueError(f"RunOptions.prices cannot price RunOptions.model={options.model!r} ({exc}); for a "
|
|
93
|
+
"gateway target use prices.for_target(target)") from exc
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _tool_table(tools: ToolRegistry | Iterable[Tool] | None) -> dict[str, Tool]:
|
|
97
|
+
if tools is None:
|
|
98
|
+
return {}
|
|
99
|
+
if isinstance(tools, ToolRegistry):
|
|
100
|
+
found = (tools.get(name) for name in tools.list_tools())
|
|
101
|
+
return {t.name: t for t in found if t is not None}
|
|
102
|
+
return {t.name: t for t in tools}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _as_dict(message: ChatMessage | Mapping[str, Any]) -> dict[str, Any]:
|
|
106
|
+
return message.to_dict() if isinstance(message, ChatMessage) else copy.deepcopy(dict(message))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _provider_chunks(stream: Iterable[ChatCompletionChunk]) -> Iterator[ChatCompletionChunk]:
|
|
110
|
+
"""The provider's chunks; its failures (raised or sent as error chunks) become ``_ProviderFailed``."""
|
|
111
|
+
iterator = iter(stream)
|
|
112
|
+
while True:
|
|
113
|
+
try:
|
|
114
|
+
chunk = next(iterator)
|
|
115
|
+
except StopIteration:
|
|
116
|
+
return
|
|
117
|
+
except ProviderError as exc:
|
|
118
|
+
raise _ProviderFailed(exc) from exc
|
|
119
|
+
error = stream_error(chunk)
|
|
120
|
+
if error is not None:
|
|
121
|
+
raise _ProviderFailed(error)
|
|
122
|
+
yield chunk
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class _Run:
|
|
126
|
+
"""Mutable state of one ``run`` call."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, provider: Provider, messages: Sequence[ChatMessage | Mapping[str, Any]],
|
|
129
|
+
tools: dict[str, Tool], hooks: LoopHooks, options: RunOptions) -> None:
|
|
130
|
+
self.provider, self.hooks, self.options, self.limits = provider, hooks, options, options.limits
|
|
131
|
+
self.messages: list[dict[str, Any]] = [_as_dict(m) for m in messages]
|
|
132
|
+
self.usage = Usage()
|
|
133
|
+
self.cost = 0.0
|
|
134
|
+
self.turns = 0
|
|
135
|
+
self.estimated = False
|
|
136
|
+
self.started = options.clock()
|
|
137
|
+
self.runner = ToolRunner(tools, options, hooks, self.time_left)
|
|
138
|
+
|
|
139
|
+
def time_left(self) -> float | None:
|
|
140
|
+
if self.limits.run_timeout is None:
|
|
141
|
+
return None
|
|
142
|
+
return self.limits.run_timeout - (self.options.clock() - self.started)
|
|
143
|
+
|
|
144
|
+
def check_limits(self) -> Stop | None:
|
|
145
|
+
lim, used = self.limits, self.usage
|
|
146
|
+
prompt = used.input_tokens + used.cache_read_tokens + used.cache_write_tokens
|
|
147
|
+
if lim.max_turns is not None and self.turns >= lim.max_turns:
|
|
148
|
+
return Stop(RunStatus.TURN_LIMIT, f"{self.turns} model calls")
|
|
149
|
+
if lim.max_input_tokens is not None and prompt >= lim.max_input_tokens:
|
|
150
|
+
return Stop(RunStatus.TOKEN_LIMIT, f"{prompt} input tokens")
|
|
151
|
+
if lim.cost_cap_usd is not None and self.cost >= lim.cost_cap_usd:
|
|
152
|
+
return Stop(RunStatus.COST_LIMIT, f"{self.cost:.6f} USD spent")
|
|
153
|
+
left = self.time_left()
|
|
154
|
+
if left is not None and left <= 0:
|
|
155
|
+
return Stop(RunStatus.TIME_LIMIT, f"run_timeout of {lim.run_timeout:g} s passed")
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
def result(self, status: RunStatus, reason: str = "", error: ProviderError | None = None) -> RunResult:
|
|
159
|
+
last: dict[str, Any] = next((m for m in reversed(self.messages) if m.get("role") == "assistant"), {})
|
|
160
|
+
content = last.get("content")
|
|
161
|
+
return RunResult(text=content if isinstance(content, str) else "", status=status, messages=self.messages,
|
|
162
|
+
usage=self.usage, cost_usd=self.cost, turns=self.turns,
|
|
163
|
+
tool_decisions=tuple(self.runner.decisions), reason=reason, error=error,
|
|
164
|
+
estimated=self.estimated)
|
|
165
|
+
|
|
166
|
+
def call_model(self) -> tuple[dict[str, Any], str | None]:
|
|
167
|
+
"""One model call: the assistant message as a dict and the finish reason; usage (estimated when the
|
|
168
|
+
provider sent none) and cost counted."""
|
|
169
|
+
request = ChatRequest(messages=list(self.messages), model=self.options.model,
|
|
170
|
+
tools=self.runner.schemas() or None, max_tokens=self.limits.max_output_tokens_per_call)
|
|
171
|
+
self.turns += 1
|
|
172
|
+
message, finish, usage, model = self._streamed(request) if self.options.stream else self._completed(request)
|
|
173
|
+
if usage is None:
|
|
174
|
+
usage, self.estimated = estimate_usage(self.messages, message), True
|
|
175
|
+
try:
|
|
176
|
+
self._count(usage, model or None)
|
|
177
|
+
except _PricingFailed as failed:
|
|
178
|
+
failed.message = message
|
|
179
|
+
raise
|
|
180
|
+
return message, finish
|
|
181
|
+
|
|
182
|
+
def _completed(self, request: ChatRequest) -> tuple[dict[str, Any], str | None, Usage | None, str]:
|
|
183
|
+
try:
|
|
184
|
+
completion = self.provider.complete(request)
|
|
185
|
+
if not completion.choices:
|
|
186
|
+
raise ProviderError("the answer has no choices", kind=ProviderError.BAD_RESPONSE)
|
|
187
|
+
except ProviderError as exc:
|
|
188
|
+
raise _ProviderFailed(exc) from exc
|
|
189
|
+
choice = completion.choices[0]
|
|
190
|
+
raw = choice.get("message")
|
|
191
|
+
message = {"role": "assistant", **copy.deepcopy(raw if isinstance(raw, Mapping) else {})}
|
|
192
|
+
return message, choice.get("finish_reason"), completion.token_usage, completion.model
|
|
193
|
+
|
|
194
|
+
def _streamed(self, request: ChatRequest) -> tuple[dict[str, Any], str | None, Usage | None, str]:
|
|
195
|
+
try:
|
|
196
|
+
stream = self.provider.stream(request)
|
|
197
|
+
except ProviderError as exc:
|
|
198
|
+
raise _ProviderFailed(exc) from exc
|
|
199
|
+
close = getattr(stream, "close", None)
|
|
200
|
+
seen: list[str] = []
|
|
201
|
+
|
|
202
|
+
def on_token(text: str) -> None:
|
|
203
|
+
seen.append(text)
|
|
204
|
+
if self.hooks.on_token is not None:
|
|
205
|
+
self.hooks.on_token(text)
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
return fold_stream(_provider_chunks(stream), on_token)
|
|
209
|
+
except _ProviderFailed as failed:
|
|
210
|
+
self._count_broken(failed.error, "".join(seen))
|
|
211
|
+
raise
|
|
212
|
+
finally: # an abandoned stream releases its connection
|
|
213
|
+
if callable(close):
|
|
214
|
+
close()
|
|
215
|
+
|
|
216
|
+
def _count_broken(self, error: ProviderError, partial: str) -> None:
|
|
217
|
+
"""Count a stream that broke after output: the usage the error carries (a gateway's
|
|
218
|
+
``StreamInterrupted`` says what it charged), else an estimate from the partial text; nothing when no text
|
|
219
|
+
came (a failure before output costs nothing). A pricing failure here is ignored: the run already ends with
|
|
220
|
+
the provider error."""
|
|
221
|
+
usage = getattr(error, "usage", None)
|
|
222
|
+
if isinstance(usage, Usage):
|
|
223
|
+
estimated = bool(getattr(error, "estimated", False))
|
|
224
|
+
elif partial:
|
|
225
|
+
usage, estimated = estimate_usage(self.messages, {"content": partial}), True
|
|
226
|
+
else:
|
|
227
|
+
return
|
|
228
|
+
self.estimated = self.estimated or estimated
|
|
229
|
+
try:
|
|
230
|
+
self._count(usage, None)
|
|
231
|
+
except _PricingFailed:
|
|
232
|
+
pass
|
|
233
|
+
|
|
234
|
+
def _count(self, usage: Usage, answered: str | None) -> None:
|
|
235
|
+
"""Add the call's usage and cost; ``answered`` = the model the answer names (may be empty)."""
|
|
236
|
+
u = self.usage
|
|
237
|
+
self.usage = Usage(u.input_tokens + usage.input_tokens, u.output_tokens + usage.output_tokens,
|
|
238
|
+
u.cache_read_tokens + usage.cache_read_tokens,
|
|
239
|
+
u.cache_write_tokens + usage.cache_write_tokens)
|
|
240
|
+
if self.hooks.on_usage is not None:
|
|
241
|
+
self.hooks.on_usage(usage)
|
|
242
|
+
asked, options = self.options.model, self.options
|
|
243
|
+
try:
|
|
244
|
+
if options.cost_fn is not None:
|
|
245
|
+
self.cost += float(options.cost_fn(usage, answered or asked))
|
|
246
|
+
elif options.prices is not None:
|
|
247
|
+
self.cost += float(options.prices.cost(usage, asked or answered))
|
|
248
|
+
except Exception as exc: # a pricing failure ends the run as an error result, never escapes run()
|
|
249
|
+
raise _PricingFailed(f"pricing the call failed ({type(exc).__name__}: {exc})") from exc
|
rexlib/loop/options.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
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
|
+
"""The loop's value types: options, limits, tool policy, hooks, statuses and the result."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from typing import Any, Protocol
|
|
14
|
+
|
|
15
|
+
from ..messages import ToolCall, Usage
|
|
16
|
+
from ..providers.errors import ProviderError
|
|
17
|
+
from ..tools.base import ToolResult
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RunStatus(str, Enum):
|
|
21
|
+
"""Why a run ended."""
|
|
22
|
+
|
|
23
|
+
COMPLETE = "complete" # the model answered without tool calls
|
|
24
|
+
MAX_TOKENS = "max_tokens" # the model hit its output token limit
|
|
25
|
+
TURN_LIMIT = "turn_limit" # Limits.max_turns model calls made
|
|
26
|
+
TOKEN_LIMIT = "token_limit" # Limits.max_input_tokens used
|
|
27
|
+
COST_LIMIT = "cost_limit" # Limits.cost_cap_usd spent
|
|
28
|
+
TIME_LIMIT = "time_limit" # Limits.run_timeout passed
|
|
29
|
+
REFUSED = "refused" # the model or its server refused (content filter)
|
|
30
|
+
STOPPED = "stopped" # a before_model hook returned Stop()
|
|
31
|
+
ERROR = "error" # the provider failed; RunResult.error holds the ProviderError
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Decision(str, Enum):
|
|
35
|
+
"""A tool policy decision; ``ToolPolicy.decide`` may return these or the plain strings."""
|
|
36
|
+
|
|
37
|
+
ALLOW = "allow"
|
|
38
|
+
ASK = "ask"
|
|
39
|
+
DENY = "deny"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Stop:
|
|
44
|
+
"""Returned by ``before_model`` to end the run (e.g. a budget kept outside the loop)."""
|
|
45
|
+
|
|
46
|
+
status: RunStatus = RunStatus.STOPPED
|
|
47
|
+
reason: str = ""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Limits:
|
|
52
|
+
"""Run limits; ``None`` means no limit. ``max_input_tokens`` counts the whole prompt of every call (input +
|
|
53
|
+
cache reads + cache writes). Timeouts are seconds; each tool timeout is cut to the time left of
|
|
54
|
+
``run_timeout``. ``cost_cap_usd`` needs ``RunOptions.cost_fn`` or ``RunOptions.prices``."""
|
|
55
|
+
|
|
56
|
+
max_turns: int | None = 50
|
|
57
|
+
max_input_tokens: int | None = None
|
|
58
|
+
max_output_tokens_per_call: int | None = None
|
|
59
|
+
cost_cap_usd: float | None = None
|
|
60
|
+
run_timeout: float | None = None
|
|
61
|
+
tool_timeout: float | None = None
|
|
62
|
+
max_tool_result_chars: int | None = None
|
|
63
|
+
max_calls_per_tool: int | None = None
|
|
64
|
+
max_concurrent_tools: int = 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
Decide = Callable[[ToolCall, dict[str, Any]], "Decision | str | tuple[Decision | str, str]"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class ToolPolicy:
|
|
72
|
+
"""Which tool calls run. ``enabled`` None = every tool given to ``run``; ``max_calls`` and ``timeouts``
|
|
73
|
+
override ``Limits.max_calls_per_tool`` and ``Limits.tool_timeout`` per tool name; ``decide(call, args)`` is the
|
|
74
|
+
generic decision point (a role table, a rule engine, a prompt) and gets copies; ``ask(call, args) -> bool``
|
|
75
|
+
answers ``Decision.ASK``. With ``max_concurrent_tools > 1`` an argument re-check from ``around_tool`` may call
|
|
76
|
+
``decide`` and ``ask`` from worker threads."""
|
|
77
|
+
|
|
78
|
+
enabled: frozenset[str] | None = None
|
|
79
|
+
max_calls: Mapping[str, int] = field(default_factory=dict)
|
|
80
|
+
timeouts: Mapping[str, float] = field(default_factory=dict)
|
|
81
|
+
decide: Decide | None = None
|
|
82
|
+
ask: Callable[[ToolCall, dict[str, Any]], bool] | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class LoopHooks:
|
|
87
|
+
"""Optional callbacks; see ``rexlib.loop``."""
|
|
88
|
+
|
|
89
|
+
before_model: Callable[[int, list[dict[str, Any]]], Stop | None] | None = None
|
|
90
|
+
around_tool: Callable[[ToolCall, Callable[..., ToolResult]], ToolResult] | None = None
|
|
91
|
+
on_usage: Callable[[Usage], None] | None = None
|
|
92
|
+
on_token: Callable[[str], None] | None = None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class PriceTable(Protocol):
|
|
96
|
+
"""A price table for ``RunOptions.prices``: ``cost(usage, model) -> USD`` of one call. ``run`` prices a zero
|
|
97
|
+
``Usage`` for ``RunOptions.model`` before the first call, so a table that cannot price that name fails up front
|
|
98
|
+
(``ValueError``). Recommended: ``gateway.prices.for_target(target)`` (a fixed price; a class at its highest
|
|
99
|
+
member price); a plain ``ModelPrices`` needs ``RunOptions.model``."""
|
|
100
|
+
|
|
101
|
+
def cost(self, usage: Usage, model: str | None, /) -> float: ...
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True)
|
|
105
|
+
class RunOptions:
|
|
106
|
+
"""``model`` None = the provider's default; ``cost_fn(usage, model) -> USD`` or ``prices`` (a ``PriceTable``,
|
|
107
|
+
e.g. the gateway's price table) prices each call, one of them is required by ``Limits.cost_cap_usd`` and
|
|
108
|
+
giving both is a ``ValueError``. ``cost_fn`` gets the model the answer names (else ``model``); ``prices`` gets
|
|
109
|
+
``model`` when it is set (the name the caller asked for: a class gives its conservative bound), else the
|
|
110
|
+
answer's model. A pricing failure after a call ends the run with ``RunStatus.ERROR`` (``reason`` says why,
|
|
111
|
+
``error`` is None; the answer stays in the history). ``clock`` returns seconds (monotonic); ``stream`` uses ``provider.stream``."""
|
|
112
|
+
|
|
113
|
+
model: str | None = None
|
|
114
|
+
limits: Limits = field(default_factory=Limits)
|
|
115
|
+
tool_policy: ToolPolicy = field(default_factory=ToolPolicy)
|
|
116
|
+
cost_fn: Callable[[Usage, str | None], float] | None = None
|
|
117
|
+
clock: Callable[[], float] = time.monotonic
|
|
118
|
+
stream: bool = False
|
|
119
|
+
prices: PriceTable | None = None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class ToolDecision:
|
|
124
|
+
"""One policy decision (an "ask" ends as ALLOW or DENY). A call whose arguments ``around_tool`` changed is
|
|
125
|
+
checked again and recorded a second time."""
|
|
126
|
+
|
|
127
|
+
call_id: str
|
|
128
|
+
tool: str
|
|
129
|
+
decision: Decision
|
|
130
|
+
reason: str = ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True)
|
|
134
|
+
class RunResult:
|
|
135
|
+
"""``text`` = the last assistant text; ``messages`` = the conversation as OpenAI-shape dicts; ``turns`` =
|
|
136
|
+
model calls made; ``reason`` = why the run stopped; ``error`` = the ``ProviderError`` of status ERROR (None
|
|
137
|
+
when pricing a call failed);
|
|
138
|
+
``estimated`` = some call sent no usage and its tokens were estimated (characters / 4)."""
|
|
139
|
+
|
|
140
|
+
text: str
|
|
141
|
+
status: RunStatus
|
|
142
|
+
messages: list[dict[str, Any]]
|
|
143
|
+
usage: Usage
|
|
144
|
+
cost_usd: float
|
|
145
|
+
turns: int
|
|
146
|
+
tool_decisions: tuple[ToolDecision, ...]
|
|
147
|
+
reason: str = ""
|
|
148
|
+
error: ProviderError | None = None
|
|
149
|
+
estimated: bool = False
|
rexlib/loop/stream.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
"""Streamed chunks folded into one assistant message, and a token estimate for calls that report no usage."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from ..messages import ChatCompletionChunk, Usage
|
|
14
|
+
from ..providers.errors import ProviderError
|
|
15
|
+
|
|
16
|
+
_MESSAGE_KEYS = frozenset({"role", "content", "tool_calls"})
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def fold_stream(chunks: Iterable[ChatCompletionChunk], on_token: Callable[[str], None] | None = None
|
|
20
|
+
) -> tuple[dict[str, Any], str | None, Usage | None, str]:
|
|
21
|
+
"""Fold streamed chunks into (assistant message dict, finish reason, usage, model).
|
|
22
|
+
|
|
23
|
+
Text goes to ``on_token`` piece by piece. Tool call deltas are joined by ``index`` (arguments concatenated,
|
|
24
|
+
other keys such as vendor signatures kept). Other message-level delta fields (``reasoning_content`` ...) are
|
|
25
|
+
kept: strings are concatenated, other values replace. A chunk with ``error`` raises ``ProviderError``."""
|
|
26
|
+
text: list[str] = []
|
|
27
|
+
calls: dict[int, dict[str, Any]] = {}
|
|
28
|
+
extra: dict[str, Any] = {}
|
|
29
|
+
finish, usage, model = None, None, ""
|
|
30
|
+
for chunk in chunks:
|
|
31
|
+
error = stream_error(chunk)
|
|
32
|
+
if error is not None:
|
|
33
|
+
raise error
|
|
34
|
+
model = chunk.model or model
|
|
35
|
+
delta = chunk.delta
|
|
36
|
+
if chunk.content:
|
|
37
|
+
text.append(chunk.content)
|
|
38
|
+
if on_token is not None:
|
|
39
|
+
on_token(chunk.content)
|
|
40
|
+
for position, call in enumerate(delta.get("tool_calls") or ()):
|
|
41
|
+
_merge_call(calls, call, position)
|
|
42
|
+
_merge_extra(extra, delta)
|
|
43
|
+
finish = chunk.finish_reason or finish
|
|
44
|
+
usage = chunk.token_usage or usage
|
|
45
|
+
message: dict[str, Any] = {"role": "assistant", **extra, "content": "".join(text) if text else None}
|
|
46
|
+
if calls:
|
|
47
|
+
message["tool_calls"] = [calls[i] for i in sorted(calls)]
|
|
48
|
+
return message, finish, usage, model
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def stream_error(chunk: ChatCompletionChunk) -> ProviderError | None:
|
|
52
|
+
"""The ``ProviderError`` for a chunk that carries ``error`` (with or without choices), else None."""
|
|
53
|
+
if not chunk.error:
|
|
54
|
+
return None
|
|
55
|
+
return ProviderError(f"error in the stream: {chunk.error}", kind=ProviderError.BAD_RESPONSE)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _merge_extra(extra: dict[str, Any], delta: Mapping[str, Any]) -> None:
|
|
59
|
+
for key, value in delta.items():
|
|
60
|
+
if key in _MESSAGE_KEYS or value is None:
|
|
61
|
+
continue
|
|
62
|
+
old = extra.get(key)
|
|
63
|
+
extra[key] = old + value if isinstance(old, str) and isinstance(value, str) else value
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _merge_call(calls: dict[int, dict[str, Any]], delta: Mapping[str, Any], position: int) -> None:
|
|
67
|
+
index = delta.get("index")
|
|
68
|
+
entry = calls.setdefault(index if isinstance(index, int) else position,
|
|
69
|
+
{"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
|
|
70
|
+
for key, value in delta.items():
|
|
71
|
+
if key == "function" and isinstance(value, Mapping):
|
|
72
|
+
fn = entry["function"]
|
|
73
|
+
fn["name"] = fn["name"] or str(value.get("name") or "")
|
|
74
|
+
fn["arguments"] += str(value.get("arguments") or "")
|
|
75
|
+
elif key not in ("index", "function") and value:
|
|
76
|
+
entry[key] = value
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _chars(value: Any) -> int:
|
|
80
|
+
return len(value if isinstance(value, str) else json.dumps(value, ensure_ascii=False, default=str))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def estimate_usage(prompt: Sequence[Mapping[str, Any]], message: Mapping[str, Any]) -> Usage:
|
|
84
|
+
"""Rough usage for a call that reported none: characters / 4 (rounded up) of the prompt messages and of the
|
|
85
|
+
answer's text and tool call arguments. Used only so token and cost limits still hold."""
|
|
86
|
+
answer = _chars(message.get("content") or "") + sum(
|
|
87
|
+
_chars((c.get("function") or {}).get("arguments") or "") for c in message.get("tool_calls") or ())
|
|
88
|
+
return Usage(input_tokens=(_chars(list(prompt)) + 3) // 4, output_tokens=(answer + 3) // 4)
|