rexlib-py 0.9.0a1__tar.gz
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_py-0.9.0a1/LICENSE +21 -0
- rexlib_py-0.9.0a1/PKG-INFO +251 -0
- rexlib_py-0.9.0a1/README.md +225 -0
- rexlib_py-0.9.0a1/pyproject.toml +50 -0
- rexlib_py-0.9.0a1/rexlib/__init__.py +75 -0
- rexlib_py-0.9.0a1/rexlib/cli/__init__.py +44 -0
- rexlib_py-0.9.0a1/rexlib/cli/commands.py +99 -0
- rexlib_py-0.9.0a1/rexlib/cli/console.py +83 -0
- rexlib_py-0.9.0a1/rexlib/cli/options.py +47 -0
- rexlib_py-0.9.0a1/rexlib/cli/permissions.py +174 -0
- rexlib_py-0.9.0a1/rexlib/cli/render.py +78 -0
- rexlib_py-0.9.0a1/rexlib/cli/repl.py +97 -0
- rexlib_py-0.9.0a1/rexlib/cli/session.py +99 -0
- rexlib_py-0.9.0a1/rexlib/container/__init__.py +33 -0
- rexlib_py-0.9.0a1/rexlib/container/detect.py +151 -0
- rexlib_py-0.9.0a1/rexlib/container/model.py +111 -0
- rexlib_py-0.9.0a1/rexlib/container/probe.py +191 -0
- rexlib_py-0.9.0a1/rexlib/container/resolve.py +151 -0
- rexlib_py-0.9.0a1/rexlib/gateway/__init__.py +56 -0
- rexlib_py-0.9.0a1/rexlib/gateway/attempts.py +51 -0
- rexlib_py-0.9.0a1/rexlib/gateway/audit.py +173 -0
- rexlib_py-0.9.0a1/rexlib/gateway/config.py +383 -0
- rexlib_py-0.9.0a1/rexlib/gateway/costs.py +157 -0
- rexlib_py-0.9.0a1/rexlib/gateway/keys.py +46 -0
- rexlib_py-0.9.0a1/rexlib/gateway/presets.py +59 -0
- rexlib_py-0.9.0a1/rexlib/gateway/prices.py +134 -0
- rexlib_py-0.9.0a1/rexlib/gateway/router.py +391 -0
- rexlib_py-0.9.0a1/rexlib/gateway/stream.py +224 -0
- rexlib_py-0.9.0a1/rexlib/loop/__init__.py +63 -0
- rexlib_py-0.9.0a1/rexlib/loop/calls.py +220 -0
- rexlib_py-0.9.0a1/rexlib/loop/core.py +249 -0
- rexlib_py-0.9.0a1/rexlib/loop/options.py +149 -0
- rexlib_py-0.9.0a1/rexlib/loop/stream.py +88 -0
- rexlib_py-0.9.0a1/rexlib/messages.py +221 -0
- rexlib_py-0.9.0a1/rexlib/providers/__init__.py +11 -0
- rexlib_py-0.9.0a1/rexlib/providers/anthropic.py +108 -0
- rexlib_py-0.9.0a1/rexlib/providers/base.py +53 -0
- rexlib_py-0.9.0a1/rexlib/providers/errors.py +191 -0
- rexlib_py-0.9.0a1/rexlib/providers/http.py +124 -0
- rexlib_py-0.9.0a1/rexlib/providers/openai.py +148 -0
- rexlib_py-0.9.0a1/rexlib/providers/transport.py +163 -0
- rexlib_py-0.9.0a1/rexlib/py.typed +0 -0
- rexlib_py-0.9.0a1/rexlib/storage/__init__.py +30 -0
- rexlib_py-0.9.0a1/rexlib/storage/base.py +144 -0
- rexlib_py-0.9.0a1/rexlib/storage/contract.py +262 -0
- rexlib_py-0.9.0a1/rexlib/storage/registry.py +49 -0
- rexlib_py-0.9.0a1/rexlib/storage/sqlite.py +219 -0
- rexlib_py-0.9.0a1/rexlib/testing.py +160 -0
- rexlib_py-0.9.0a1/rexlib/tools/__init__.py +12 -0
- rexlib_py-0.9.0a1/rexlib/tools/base.py +116 -0
- rexlib_py-0.9.0a1/rexlib/tools/executor.py +105 -0
- rexlib_py-0.9.0a1/rexlib/tools/function_tool.py +168 -0
- rexlib_py-0.9.0a1/rexlib/tools/registry.py +66 -0
- rexlib_py-0.9.0a1/rexlib/wire/__init__.py +6 -0
- rexlib_py-0.9.0a1/rexlib/wire/anthropic_messages.py +300 -0
- rexlib_py-0.9.0a1/rexlib/wire/openai_chat.py +134 -0
- rexlib_py-0.9.0a1/rexlib/wire/sse.py +85 -0
- rexlib_py-0.9.0a1/rexlib_py.egg-info/PKG-INFO +251 -0
- rexlib_py-0.9.0a1/rexlib_py.egg-info/SOURCES.txt +60 -0
- rexlib_py-0.9.0a1/rexlib_py.egg-info/dependency_links.txt +1 -0
- rexlib_py-0.9.0a1/rexlib_py.egg-info/top_level.txt +1 -0
- rexlib_py-0.9.0a1/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rexlib-py
|
|
3
|
+
Version: 0.9.0a1
|
|
4
|
+
Summary: Stdlib-only building blocks for AI apps: messages, tools, providers, loop, model gateway
|
|
5
|
+
Author-email: Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/peterkokosharov/rex
|
|
8
|
+
Project-URL: Source, https://github.com/peterkokosharov/rex
|
|
9
|
+
Project-URL: Changelog, https://github.com/peterkokosharov/rex/blob/main/rexlib/CHANGELOG.md
|
|
10
|
+
Keywords: llm,ai,agent,gateway,openai,anthropic,streaming,tools,stdlib
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
<!--
|
|
28
|
+
Author: Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
29
|
+
AI models: claude-opus-5-5
|
|
30
|
+
Licensed under MIT License
|
|
31
|
+
-->
|
|
32
|
+
|
|
33
|
+
# rexlib
|
|
34
|
+
|
|
35
|
+
Stdlib-only building blocks for Python AI apps: chat messages, tools, OpenAI-compatible and Anthropic providers
|
|
36
|
+
(complete and stream), a small agent loop with limits and a tool policy, a model gateway (classes of models with
|
|
37
|
+
fallback, cooldown, daily cost caps, prices, audit events), SQLite storage for costs and audit, a container probe,
|
|
38
|
+
and a line-based prompt (`rexlib.cli`). No dependencies outside the Python standard library.
|
|
39
|
+
|
|
40
|
+
- Install: `pip install --pre rexlib-py` (the import name is `rexlib`). Python >= 3.12. Status: **0.9.0a1**, an
|
|
41
|
+
alpha: names and behaviour may still change before 1.0.
|
|
42
|
+
- `import rexlib` loads no sub-module; public names are re-exported lazily and typed (`py.typed`).
|
|
43
|
+
- Promise: from 1.0 the names in `rexlib.__all__` (core and gateway) follow SemVer. `rexlib.cli` and the later
|
|
44
|
+
agent tier, app kit and bridges stay 0.x (reachable by module name, may change in any minor release).
|
|
45
|
+
- Source, design notes, demos and tests: https://github.com/peterkokosharov/rex (folder `rexlib/`; demos in
|
|
46
|
+
`rexlib/demos/`, the design in `docs/design/2026-11-29-rexlib-1.0.md`). The rex app, an AI coding assistant in
|
|
47
|
+
the terminal, is built on it: its `rex rt` prompt is `rexlib.cli` with rex's tools and permission rules.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from rexlib import ChatMessage, ChatRequest, OpenAIChat
|
|
51
|
+
|
|
52
|
+
chat = OpenAIChat("https://api.openai.com/v1", "sk-...", "gpt-4o-mini")
|
|
53
|
+
print(chat.complete(ChatRequest([ChatMessage.user("Say hi")])).message.content)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The loop with a tool, limits and a policy, tested without network:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from rexlib import ChatMessage, Limits, RunOptions, ToolPolicy, function_tool, run
|
|
60
|
+
from rexlib.testing import FakeProvider, reply, tool_call
|
|
61
|
+
|
|
62
|
+
@function_tool
|
|
63
|
+
def add(a: int, b: int) -> int:
|
|
64
|
+
"""Add two numbers."""
|
|
65
|
+
return a + b
|
|
66
|
+
|
|
67
|
+
fake = FakeProvider([reply(tool_calls=[tool_call("add", a=1, b=2)]), "3"])
|
|
68
|
+
options = RunOptions(limits=Limits(max_turns=5), tool_policy=ToolPolicy(decide=lambda call, args: "allow"))
|
|
69
|
+
result = run(fake, [ChatMessage.user("1+2?")], [add], options=options)
|
|
70
|
+
print(result.status.value, result.text) # complete 3
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Streaming (step ST1): `provider.stream(request)` yields `ChatCompletionChunk`s for both wires; the last chunk
|
|
74
|
+
carries the finish reason and the usage when the server sends it (OpenAI only with `stream_options.include_usage`,
|
|
75
|
+
which is asked for; Anthropic input and cache tokens from `message_start`, output tokens from `message_delta`). A
|
|
76
|
+
stream without usage gives none, and `run()` then estimates (about 4 characters per token, `result.estimated`).
|
|
77
|
+
A body that ends before `[DONE]` / `message_stop` (and without a finish reason) is a `ProviderError` (`network`),
|
|
78
|
+
never a short answer. Event parsing (`rexlib.wire.sse`) handles CRLF, comments, multi-line data and events split
|
|
79
|
+
across reads, with a 4 MiB event and a 64 MiB body limit; the read timeout bounds every wait for the next bytes.
|
|
80
|
+
Closing the generator (or Ctrl-C while reading) closes the HTTP response.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from rexlib import LoopHooks, RunOptions
|
|
84
|
+
|
|
85
|
+
result = run(chat, [ChatMessage.user("Tell a short story")],
|
|
86
|
+
hooks=LoopHooks(on_token=lambda text: print(text, end="", flush=True)),
|
|
87
|
+
options=RunOptions(stream=True))
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Costs, audit events and sessions go through a small `Storage` protocol; SQLite (stdlib) is built in, other
|
|
91
|
+
backends plug in through a `name -> factory` table and must pass `rexlib.storage.contract.run_contract`:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from rexlib.storage import open_storage
|
|
95
|
+
|
|
96
|
+
with open_storage("sqlite:///~/.rex/rex.db") as store: # or "sqlite://:memory:"; leaving closes it
|
|
97
|
+
store.record_cost({"scope": "large", "usd": 0.012, "model": "m1"})
|
|
98
|
+
store.append_audit({"kind": "gateway.call", "session": "s1", "outcome": "ok"})
|
|
99
|
+
print(store.spent("large", since=0.0), store.query_audit(kind="gateway.call", limit=20))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Audit events come back in append (insertion) order, never sorted by their `ts`; `limit=N` gives the newest N,
|
|
103
|
+
still in append order.
|
|
104
|
+
|
|
105
|
+
The gateway starts with its configuration (step G1): model entries from presets or spelled
|
|
106
|
+
out, classes with free names whose order is the fallback order, prices in USD per million tokens. Every unknown key
|
|
107
|
+
is refused by name; `key_env` names the variable that holds a key and is read only by the router:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from rexlib import GatewayConfig
|
|
111
|
+
|
|
112
|
+
config = GatewayConfig.from_dict({
|
|
113
|
+
"models": {
|
|
114
|
+
"sonnet": {"preset": "anthropic", "model": "claude-sonnet-4-5", "price": {"in": 3.0, "out": 15.0}},
|
|
115
|
+
"local": {"preset": "ollama", "model": "llama3.1", "price": {"in": 0, "out": 0}}, # a capped class prices all
|
|
116
|
+
},
|
|
117
|
+
"classes": {"large": ["sonnet", "local"], "small": {"models": ["local"], "daily_cap_usd": 1.0}},
|
|
118
|
+
}) # or GatewayConfig.from_toml("gateway.toml")
|
|
119
|
+
print(config.targets(), config.models["sonnet"].price) # cache prices default to 10 % / 125 % of "in"
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Presets (`rexlib.PRESETS`): `anthropic`, `openai`, `openrouter`, `gemini`, `nvidia`, `ollama`, `kiko`, `cgw` (the
|
|
123
|
+
last two are rex's local proxies on 127.0.0.1); an app adds its own with `from rexlib import PRESETS, Preset` and
|
|
124
|
+
`presets={**PRESETS, "mine": Preset("openai-compatible", "https://llm.example/v1", "MINE_KEY")}`. A bad entry raises
|
|
125
|
+
`rexlib.ConfigError` (a `ValueError`; it names the place, never a key).
|
|
126
|
+
|
|
127
|
+
The `Gateway` routes a call by class name (or model id): the first model of the class that is not cooling down
|
|
128
|
+
serves it; on a retryable error (connect error, timeout, 408, 429, 5xx, Anthropic's 529) that model rests for
|
|
129
|
+
`cooldown` seconds (or the server's `Retry-After`) and the next one is tried; 400, 401/403 and broken answers
|
|
130
|
+
surface at once. A model whose `key_env` variable is not set at call time is skipped (the error names the
|
|
131
|
+
variable, never a value). Each successful call is charged to its class through a `Storage` (`record_cost`, USD
|
|
132
|
+
from `Price` x usage); a class's soft `daily_cap_usd` is checked before each call against what was spent since
|
|
133
|
+
local midnight in the configured `timezone`, and survives a restart when the storage is a file:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from rexlib import ChatMessage, ChatRequest, CostCapExceeded, Gateway, GatewayOptions, open_storage, run
|
|
137
|
+
|
|
138
|
+
store = open_storage("sqlite:///~/.rex/rex.db")
|
|
139
|
+
with Gateway(config, GatewayOptions(storage=store)) as gateway:
|
|
140
|
+
answer = gateway.complete("large", ChatRequest([ChatMessage.user("hi")]))
|
|
141
|
+
result = run(gateway.provider("large"), [ChatMessage.user("1+2?")]) # any Provider consumer
|
|
142
|
+
print(gateway.spent_today("small"), gateway.healthy("sonnet"))
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Tests pass `GatewayOptions(providers={"sonnet": FakeProvider([...])}, env={...}, clock=FakeClock(...))`: no
|
|
146
|
+
network, no waiting.
|
|
147
|
+
|
|
148
|
+
Streaming through the gateway (step ST2): `gateway.stream(target, request)` (and `gateway.provider(target).stream`)
|
|
149
|
+
routes like `complete`, with fallback and cooldown only **before** the first chunk with output; the caller never
|
|
150
|
+
gets two half answers. After it, a failure ends the stream with `StreamInterrupted` (a `ProviderError` with the
|
|
151
|
+
upstream kind, the text passed on in `partial`, the model in `model`). The cap is checked before dispatch; cost
|
|
152
|
+
and the audit event (`streamed: true`) come at the end, from the stream's usage or estimated (`estimated: true`),
|
|
153
|
+
also for a stream that breaks or that the caller abandons (outcome `abandoned`, e.g. Ctrl-C, or a `break` at the
|
|
154
|
+
finish reason before the stream ended: read to the end to get `ok`). `StreamInterrupted.usage` is what was
|
|
155
|
+
charged, and `run()` counts it. `GatewayOptions(stream_deadline=600)` bounds a whole stream (default: no limit);
|
|
156
|
+
a stream that sends only keep-alive comments for longer than the read timeout fails with `timeout`:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from rexlib import StreamInterrupted
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
for chunk in gateway.stream("large", ChatRequest([ChatMessage.user("Write a haiku")])):
|
|
163
|
+
print(chunk.content or "", end="", flush=True)
|
|
164
|
+
except StreamInterrupted as broken:
|
|
165
|
+
print(f"\n[cut after {len(broken.partial)} characters: {broken.kind}]")
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
The loop streams through a gateway the same way (step ST3): `run(gateway.provider("large"), messages,
|
|
169
|
+
hooks=LoopHooks(on_token=...), options=RunOptions(stream=True, prices=gateway.prices.for_target("large")))` gives the
|
|
170
|
+
same result, limits and audit as without streaming; a stream cut after output ends the run with `RunStatus.ERROR`
|
|
171
|
+
and `result.error` = `StreamInterrupted`; Ctrl-C closes the HTTP response, the gateway records the abandoned
|
|
172
|
+
attempt, and the `KeyboardInterrupt` propagates. A runnable offline example: `demos/gateway_streaming.py`
|
|
173
|
+
in the repository (`PYTHONPATH=. python demos/gateway_streaming.py` in the `rexlib/` folder).
|
|
174
|
+
|
|
175
|
+
Prices, costs and audit (step G3). `gateway.prices` (a `ModelPrices`) has one price per model and one per class at
|
|
176
|
+
its highest member price, so a loop's cost limit can check a conservative bound before it knows which model
|
|
177
|
+
serves; `gateway.meter` (a `CostMeter`) reads and writes the cost records, also for budgets of your own. Every
|
|
178
|
+
attempt (each model tried) leaves one `gateway.call` `AuditEvent`: target, class, model, provider, outcome,
|
|
179
|
+
tokens, USD, duration, error kind and status, never a prompt, an answer or a key. With a storage the events go to
|
|
180
|
+
`append_audit`; `JsonlAuditSink`, `LoggingAuditSink` or any callable can be passed instead:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from rexlib import CostMeter, JsonlAuditSink, Limits, RunOptions
|
|
184
|
+
|
|
185
|
+
gateway = Gateway(config, GatewayOptions(storage=store, audit_extra=lambda request: {"user": "ann"}))
|
|
186
|
+
options = RunOptions(limits=Limits(cost_cap_usd=0.50), prices=gateway.prices.for_target("large"))
|
|
187
|
+
result = run(gateway.provider("large"), [ChatMessage.user("plan my week")], options=options)
|
|
188
|
+
print(store.query_audit(kind="gateway.call", user="ann", limit=10))
|
|
189
|
+
CostMeter(store).record({"scope": "user:ann", "usd": 0.02}) # a budget of your own
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Use `gateway.prices.for_target(target)` for `RunOptions.prices`: a fixed price that never fails. A plain
|
|
193
|
+
`ModelPrices` needs `RunOptions.model` and is checked before the first call. `audit_extra` is the app's explicit
|
|
194
|
+
opt-in for further fields (a session, a user); a failing audit sink (or `notice`) never fails a call (the cost
|
|
195
|
+
ledger does: it is the record of money). A cap refusal leaves one `refused` event with `spent` and `cap`.
|
|
196
|
+
`JsonlAuditSink` creates its file owner-only (0o600), writes each line with one `os.write`, and expects one
|
|
197
|
+
writer process per file; rotating the file is the app's job.
|
|
198
|
+
|
|
199
|
+
Where does the runtime live? `detect_container()` answers like an old CGI User-Agent (Lynx or Netscape): the app
|
|
200
|
+
picks its renderer from the result and keeps one logic. Each value comes with its source; per field, arguments in
|
|
201
|
+
code win over a TOML file the app names, then `REX_CONTAINER` (`key=value;key=value`), then detection. Config and
|
|
202
|
+
variable are strict (a broken one is refused whole and shown as `Evidence("refused", reason, source)`); detection
|
|
203
|
+
reads only environment variables, a few small files and parent process names, never raises and needs no network or
|
|
204
|
+
subprocess. `embedded` is declared by the host app, never guessed. **These are hints: never use them for a security
|
|
205
|
+
decision** (whoever starts the process controls every source).
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
from rexlib import detect_container
|
|
209
|
+
|
|
210
|
+
here = detect_container(channel="tui", config="container.toml") # a missing file is skipped
|
|
211
|
+
print(here.os.system, here.host_app, here.mode, here.hints, here.channel, here.interactive)
|
|
212
|
+
print(here.source_of("host_app")) # e.g. "detected: TERMINAL_EMULATOR=JetBrains-JediTerm"
|
|
213
|
+
print(here.to_dict()) # JSON-ready, evidence included
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Values: `host_app` intellij, vscode, windows-terminal, conhost, apple-terminal, iterm, ssh, tmux, screen, unknown;
|
|
217
|
+
`mode` native, docker (any OCI container, Podman included), sandbox (Flatpak, Windows Sandbox), embedded; `hints`
|
|
218
|
+
wsl, ci, codespaces, flatpak, podman; `channel` tui, gui, web, cli (the default), embedded. Tests inject a
|
|
219
|
+
`rexlib.container.Probe` (environment, file reader, parent-process lookup, OS name, streams).
|
|
220
|
+
|
|
221
|
+
A prompt for any app (`rexlib.cli`, 0.x: reachable by module name, not promised): a line-based REPL over a
|
|
222
|
+
gateway, stdlib only, no curses. It streams answers, runs tools behind permission questions and knows `/help`,
|
|
223
|
+
`/tools`, `/cost` (today per class and this session), `/model NAME` (or `/class`), `/reset` and `/quit`. Ctrl-C
|
|
224
|
+
cancels an answer; a second Ctrl-C at the prompt (or Ctrl-D) quits. When `container.interactive` is false there
|
|
225
|
+
are no colours, each line read is echoed, and a tool call that would ask is denied. Keys are never printed.
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
from rexlib import GatewayConfig, cli, detect_container
|
|
229
|
+
|
|
230
|
+
config = GatewayConfig.from_toml("gateway.toml")
|
|
231
|
+
cli.workflow(config, detect_container(channel="cli"), tools=[add],
|
|
232
|
+
options=cli.CliOptions(policy={"add": "auto", "*": "ask"}, outward=frozenset({"fetch"})))
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
`policy` is a table `tool -> auto | ask | forbid` or a `ToolPolicy` (its `decide`); without one every tool asks.
|
|
236
|
+
Outward tools always ask and offer no "always"; "always" covers exactly the same arguments. The question shows the
|
|
237
|
+
whole call: long lines wrapped, runs of more than 8 blanks as `<N spaces>`, invisible Unicode characters as
|
|
238
|
+
`<U+XXXX>`; a call longer than 20 lines gets a warning with what is hidden, a `[v] view all` answer and no
|
|
239
|
+
"always". Control characters from the model, tools or servers never reach the terminal. Tests pass
|
|
240
|
+
`CliOptions(input_fn=..., output=io.StringIO(), gateway_options=GatewayOptions(providers={"m": FakeProvider([...])}))`.
|
|
241
|
+
In the rex app, `rex rt` (no arguments) is this prompt.
|
|
242
|
+
|
|
243
|
+
Tests live in the rex repository (`tests/test_rexlib_*.py`) and are not part of the wheel. `REXLIB_TEST_INSTALLED=1` runs them against an installed
|
|
244
|
+
rexlib instead of the checkout copy (CI does this with the built wheel).
|
|
245
|
+
|
|
246
|
+
Publishing notes (maintainers): a tag `rexlib-vX.Y.Z` starts `.github/workflows/publish-rexlib.yml`, which checks
|
|
247
|
+
the tag against `__version__`, builds, runs `twine check --strict`, a fresh-venv smoke test and the rexlib tests
|
|
248
|
+
against the built wheel, then publishes by PyPI trusted publishing (no stored token). The GitHub environment
|
|
249
|
+
`pypi` should list the owner as required reviewer, so every upload waits for one approval.
|
|
250
|
+
|
|
251
|
+
License: MIT (see `LICENSE`).
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Author: Peter Kokosharov <peter.kokosharov@gmail.com>
|
|
3
|
+
AI models: claude-opus-5-5
|
|
4
|
+
Licensed under MIT License
|
|
5
|
+
-->
|
|
6
|
+
|
|
7
|
+
# rexlib
|
|
8
|
+
|
|
9
|
+
Stdlib-only building blocks for Python AI apps: chat messages, tools, OpenAI-compatible and Anthropic providers
|
|
10
|
+
(complete and stream), a small agent loop with limits and a tool policy, a model gateway (classes of models with
|
|
11
|
+
fallback, cooldown, daily cost caps, prices, audit events), SQLite storage for costs and audit, a container probe,
|
|
12
|
+
and a line-based prompt (`rexlib.cli`). No dependencies outside the Python standard library.
|
|
13
|
+
|
|
14
|
+
- Install: `pip install --pre rexlib-py` (the import name is `rexlib`). Python >= 3.12. Status: **0.9.0a1**, an
|
|
15
|
+
alpha: names and behaviour may still change before 1.0.
|
|
16
|
+
- `import rexlib` loads no sub-module; public names are re-exported lazily and typed (`py.typed`).
|
|
17
|
+
- Promise: from 1.0 the names in `rexlib.__all__` (core and gateway) follow SemVer. `rexlib.cli` and the later
|
|
18
|
+
agent tier, app kit and bridges stay 0.x (reachable by module name, may change in any minor release).
|
|
19
|
+
- Source, design notes, demos and tests: https://github.com/peterkokosharov/rex (folder `rexlib/`; demos in
|
|
20
|
+
`rexlib/demos/`, the design in `docs/design/2026-11-29-rexlib-1.0.md`). The rex app, an AI coding assistant in
|
|
21
|
+
the terminal, is built on it: its `rex rt` prompt is `rexlib.cli` with rex's tools and permission rules.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from rexlib import ChatMessage, ChatRequest, OpenAIChat
|
|
25
|
+
|
|
26
|
+
chat = OpenAIChat("https://api.openai.com/v1", "sk-...", "gpt-4o-mini")
|
|
27
|
+
print(chat.complete(ChatRequest([ChatMessage.user("Say hi")])).message.content)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The loop with a tool, limits and a policy, tested without network:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from rexlib import ChatMessage, Limits, RunOptions, ToolPolicy, function_tool, run
|
|
34
|
+
from rexlib.testing import FakeProvider, reply, tool_call
|
|
35
|
+
|
|
36
|
+
@function_tool
|
|
37
|
+
def add(a: int, b: int) -> int:
|
|
38
|
+
"""Add two numbers."""
|
|
39
|
+
return a + b
|
|
40
|
+
|
|
41
|
+
fake = FakeProvider([reply(tool_calls=[tool_call("add", a=1, b=2)]), "3"])
|
|
42
|
+
options = RunOptions(limits=Limits(max_turns=5), tool_policy=ToolPolicy(decide=lambda call, args: "allow"))
|
|
43
|
+
result = run(fake, [ChatMessage.user("1+2?")], [add], options=options)
|
|
44
|
+
print(result.status.value, result.text) # complete 3
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Streaming (step ST1): `provider.stream(request)` yields `ChatCompletionChunk`s for both wires; the last chunk
|
|
48
|
+
carries the finish reason and the usage when the server sends it (OpenAI only with `stream_options.include_usage`,
|
|
49
|
+
which is asked for; Anthropic input and cache tokens from `message_start`, output tokens from `message_delta`). A
|
|
50
|
+
stream without usage gives none, and `run()` then estimates (about 4 characters per token, `result.estimated`).
|
|
51
|
+
A body that ends before `[DONE]` / `message_stop` (and without a finish reason) is a `ProviderError` (`network`),
|
|
52
|
+
never a short answer. Event parsing (`rexlib.wire.sse`) handles CRLF, comments, multi-line data and events split
|
|
53
|
+
across reads, with a 4 MiB event and a 64 MiB body limit; the read timeout bounds every wait for the next bytes.
|
|
54
|
+
Closing the generator (or Ctrl-C while reading) closes the HTTP response.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from rexlib import LoopHooks, RunOptions
|
|
58
|
+
|
|
59
|
+
result = run(chat, [ChatMessage.user("Tell a short story")],
|
|
60
|
+
hooks=LoopHooks(on_token=lambda text: print(text, end="", flush=True)),
|
|
61
|
+
options=RunOptions(stream=True))
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Costs, audit events and sessions go through a small `Storage` protocol; SQLite (stdlib) is built in, other
|
|
65
|
+
backends plug in through a `name -> factory` table and must pass `rexlib.storage.contract.run_contract`:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from rexlib.storage import open_storage
|
|
69
|
+
|
|
70
|
+
with open_storage("sqlite:///~/.rex/rex.db") as store: # or "sqlite://:memory:"; leaving closes it
|
|
71
|
+
store.record_cost({"scope": "large", "usd": 0.012, "model": "m1"})
|
|
72
|
+
store.append_audit({"kind": "gateway.call", "session": "s1", "outcome": "ok"})
|
|
73
|
+
print(store.spent("large", since=0.0), store.query_audit(kind="gateway.call", limit=20))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Audit events come back in append (insertion) order, never sorted by their `ts`; `limit=N` gives the newest N,
|
|
77
|
+
still in append order.
|
|
78
|
+
|
|
79
|
+
The gateway starts with its configuration (step G1): model entries from presets or spelled
|
|
80
|
+
out, classes with free names whose order is the fallback order, prices in USD per million tokens. Every unknown key
|
|
81
|
+
is refused by name; `key_env` names the variable that holds a key and is read only by the router:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from rexlib import GatewayConfig
|
|
85
|
+
|
|
86
|
+
config = GatewayConfig.from_dict({
|
|
87
|
+
"models": {
|
|
88
|
+
"sonnet": {"preset": "anthropic", "model": "claude-sonnet-4-5", "price": {"in": 3.0, "out": 15.0}},
|
|
89
|
+
"local": {"preset": "ollama", "model": "llama3.1", "price": {"in": 0, "out": 0}}, # a capped class prices all
|
|
90
|
+
},
|
|
91
|
+
"classes": {"large": ["sonnet", "local"], "small": {"models": ["local"], "daily_cap_usd": 1.0}},
|
|
92
|
+
}) # or GatewayConfig.from_toml("gateway.toml")
|
|
93
|
+
print(config.targets(), config.models["sonnet"].price) # cache prices default to 10 % / 125 % of "in"
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Presets (`rexlib.PRESETS`): `anthropic`, `openai`, `openrouter`, `gemini`, `nvidia`, `ollama`, `kiko`, `cgw` (the
|
|
97
|
+
last two are rex's local proxies on 127.0.0.1); an app adds its own with `from rexlib import PRESETS, Preset` and
|
|
98
|
+
`presets={**PRESETS, "mine": Preset("openai-compatible", "https://llm.example/v1", "MINE_KEY")}`. A bad entry raises
|
|
99
|
+
`rexlib.ConfigError` (a `ValueError`; it names the place, never a key).
|
|
100
|
+
|
|
101
|
+
The `Gateway` routes a call by class name (or model id): the first model of the class that is not cooling down
|
|
102
|
+
serves it; on a retryable error (connect error, timeout, 408, 429, 5xx, Anthropic's 529) that model rests for
|
|
103
|
+
`cooldown` seconds (or the server's `Retry-After`) and the next one is tried; 400, 401/403 and broken answers
|
|
104
|
+
surface at once. A model whose `key_env` variable is not set at call time is skipped (the error names the
|
|
105
|
+
variable, never a value). Each successful call is charged to its class through a `Storage` (`record_cost`, USD
|
|
106
|
+
from `Price` x usage); a class's soft `daily_cap_usd` is checked before each call against what was spent since
|
|
107
|
+
local midnight in the configured `timezone`, and survives a restart when the storage is a file:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from rexlib import ChatMessage, ChatRequest, CostCapExceeded, Gateway, GatewayOptions, open_storage, run
|
|
111
|
+
|
|
112
|
+
store = open_storage("sqlite:///~/.rex/rex.db")
|
|
113
|
+
with Gateway(config, GatewayOptions(storage=store)) as gateway:
|
|
114
|
+
answer = gateway.complete("large", ChatRequest([ChatMessage.user("hi")]))
|
|
115
|
+
result = run(gateway.provider("large"), [ChatMessage.user("1+2?")]) # any Provider consumer
|
|
116
|
+
print(gateway.spent_today("small"), gateway.healthy("sonnet"))
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Tests pass `GatewayOptions(providers={"sonnet": FakeProvider([...])}, env={...}, clock=FakeClock(...))`: no
|
|
120
|
+
network, no waiting.
|
|
121
|
+
|
|
122
|
+
Streaming through the gateway (step ST2): `gateway.stream(target, request)` (and `gateway.provider(target).stream`)
|
|
123
|
+
routes like `complete`, with fallback and cooldown only **before** the first chunk with output; the caller never
|
|
124
|
+
gets two half answers. After it, a failure ends the stream with `StreamInterrupted` (a `ProviderError` with the
|
|
125
|
+
upstream kind, the text passed on in `partial`, the model in `model`). The cap is checked before dispatch; cost
|
|
126
|
+
and the audit event (`streamed: true`) come at the end, from the stream's usage or estimated (`estimated: true`),
|
|
127
|
+
also for a stream that breaks or that the caller abandons (outcome `abandoned`, e.g. Ctrl-C, or a `break` at the
|
|
128
|
+
finish reason before the stream ended: read to the end to get `ok`). `StreamInterrupted.usage` is what was
|
|
129
|
+
charged, and `run()` counts it. `GatewayOptions(stream_deadline=600)` bounds a whole stream (default: no limit);
|
|
130
|
+
a stream that sends only keep-alive comments for longer than the read timeout fails with `timeout`:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from rexlib import StreamInterrupted
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
for chunk in gateway.stream("large", ChatRequest([ChatMessage.user("Write a haiku")])):
|
|
137
|
+
print(chunk.content or "", end="", flush=True)
|
|
138
|
+
except StreamInterrupted as broken:
|
|
139
|
+
print(f"\n[cut after {len(broken.partial)} characters: {broken.kind}]")
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
The loop streams through a gateway the same way (step ST3): `run(gateway.provider("large"), messages,
|
|
143
|
+
hooks=LoopHooks(on_token=...), options=RunOptions(stream=True, prices=gateway.prices.for_target("large")))` gives the
|
|
144
|
+
same result, limits and audit as without streaming; a stream cut after output ends the run with `RunStatus.ERROR`
|
|
145
|
+
and `result.error` = `StreamInterrupted`; Ctrl-C closes the HTTP response, the gateway records the abandoned
|
|
146
|
+
attempt, and the `KeyboardInterrupt` propagates. A runnable offline example: `demos/gateway_streaming.py`
|
|
147
|
+
in the repository (`PYTHONPATH=. python demos/gateway_streaming.py` in the `rexlib/` folder).
|
|
148
|
+
|
|
149
|
+
Prices, costs and audit (step G3). `gateway.prices` (a `ModelPrices`) has one price per model and one per class at
|
|
150
|
+
its highest member price, so a loop's cost limit can check a conservative bound before it knows which model
|
|
151
|
+
serves; `gateway.meter` (a `CostMeter`) reads and writes the cost records, also for budgets of your own. Every
|
|
152
|
+
attempt (each model tried) leaves one `gateway.call` `AuditEvent`: target, class, model, provider, outcome,
|
|
153
|
+
tokens, USD, duration, error kind and status, never a prompt, an answer or a key. With a storage the events go to
|
|
154
|
+
`append_audit`; `JsonlAuditSink`, `LoggingAuditSink` or any callable can be passed instead:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from rexlib import CostMeter, JsonlAuditSink, Limits, RunOptions
|
|
158
|
+
|
|
159
|
+
gateway = Gateway(config, GatewayOptions(storage=store, audit_extra=lambda request: {"user": "ann"}))
|
|
160
|
+
options = RunOptions(limits=Limits(cost_cap_usd=0.50), prices=gateway.prices.for_target("large"))
|
|
161
|
+
result = run(gateway.provider("large"), [ChatMessage.user("plan my week")], options=options)
|
|
162
|
+
print(store.query_audit(kind="gateway.call", user="ann", limit=10))
|
|
163
|
+
CostMeter(store).record({"scope": "user:ann", "usd": 0.02}) # a budget of your own
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Use `gateway.prices.for_target(target)` for `RunOptions.prices`: a fixed price that never fails. A plain
|
|
167
|
+
`ModelPrices` needs `RunOptions.model` and is checked before the first call. `audit_extra` is the app's explicit
|
|
168
|
+
opt-in for further fields (a session, a user); a failing audit sink (or `notice`) never fails a call (the cost
|
|
169
|
+
ledger does: it is the record of money). A cap refusal leaves one `refused` event with `spent` and `cap`.
|
|
170
|
+
`JsonlAuditSink` creates its file owner-only (0o600), writes each line with one `os.write`, and expects one
|
|
171
|
+
writer process per file; rotating the file is the app's job.
|
|
172
|
+
|
|
173
|
+
Where does the runtime live? `detect_container()` answers like an old CGI User-Agent (Lynx or Netscape): the app
|
|
174
|
+
picks its renderer from the result and keeps one logic. Each value comes with its source; per field, arguments in
|
|
175
|
+
code win over a TOML file the app names, then `REX_CONTAINER` (`key=value;key=value`), then detection. Config and
|
|
176
|
+
variable are strict (a broken one is refused whole and shown as `Evidence("refused", reason, source)`); detection
|
|
177
|
+
reads only environment variables, a few small files and parent process names, never raises and needs no network or
|
|
178
|
+
subprocess. `embedded` is declared by the host app, never guessed. **These are hints: never use them for a security
|
|
179
|
+
decision** (whoever starts the process controls every source).
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from rexlib import detect_container
|
|
183
|
+
|
|
184
|
+
here = detect_container(channel="tui", config="container.toml") # a missing file is skipped
|
|
185
|
+
print(here.os.system, here.host_app, here.mode, here.hints, here.channel, here.interactive)
|
|
186
|
+
print(here.source_of("host_app")) # e.g. "detected: TERMINAL_EMULATOR=JetBrains-JediTerm"
|
|
187
|
+
print(here.to_dict()) # JSON-ready, evidence included
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Values: `host_app` intellij, vscode, windows-terminal, conhost, apple-terminal, iterm, ssh, tmux, screen, unknown;
|
|
191
|
+
`mode` native, docker (any OCI container, Podman included), sandbox (Flatpak, Windows Sandbox), embedded; `hints`
|
|
192
|
+
wsl, ci, codespaces, flatpak, podman; `channel` tui, gui, web, cli (the default), embedded. Tests inject a
|
|
193
|
+
`rexlib.container.Probe` (environment, file reader, parent-process lookup, OS name, streams).
|
|
194
|
+
|
|
195
|
+
A prompt for any app (`rexlib.cli`, 0.x: reachable by module name, not promised): a line-based REPL over a
|
|
196
|
+
gateway, stdlib only, no curses. It streams answers, runs tools behind permission questions and knows `/help`,
|
|
197
|
+
`/tools`, `/cost` (today per class and this session), `/model NAME` (or `/class`), `/reset` and `/quit`. Ctrl-C
|
|
198
|
+
cancels an answer; a second Ctrl-C at the prompt (or Ctrl-D) quits. When `container.interactive` is false there
|
|
199
|
+
are no colours, each line read is echoed, and a tool call that would ask is denied. Keys are never printed.
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from rexlib import GatewayConfig, cli, detect_container
|
|
203
|
+
|
|
204
|
+
config = GatewayConfig.from_toml("gateway.toml")
|
|
205
|
+
cli.workflow(config, detect_container(channel="cli"), tools=[add],
|
|
206
|
+
options=cli.CliOptions(policy={"add": "auto", "*": "ask"}, outward=frozenset({"fetch"})))
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`policy` is a table `tool -> auto | ask | forbid` or a `ToolPolicy` (its `decide`); without one every tool asks.
|
|
210
|
+
Outward tools always ask and offer no "always"; "always" covers exactly the same arguments. The question shows the
|
|
211
|
+
whole call: long lines wrapped, runs of more than 8 blanks as `<N spaces>`, invisible Unicode characters as
|
|
212
|
+
`<U+XXXX>`; a call longer than 20 lines gets a warning with what is hidden, a `[v] view all` answer and no
|
|
213
|
+
"always". Control characters from the model, tools or servers never reach the terminal. Tests pass
|
|
214
|
+
`CliOptions(input_fn=..., output=io.StringIO(), gateway_options=GatewayOptions(providers={"m": FakeProvider([...])}))`.
|
|
215
|
+
In the rex app, `rex rt` (no arguments) is this prompt.
|
|
216
|
+
|
|
217
|
+
Tests live in the rex repository (`tests/test_rexlib_*.py`) and are not part of the wheel. `REXLIB_TEST_INSTALLED=1` runs them against an installed
|
|
218
|
+
rexlib instead of the checkout copy (CI does this with the built wheel).
|
|
219
|
+
|
|
220
|
+
Publishing notes (maintainers): a tag `rexlib-vX.Y.Z` starts `.github/workflows/publish-rexlib.yml`, which checks
|
|
221
|
+
the tag against `__version__`, builds, runs `twine check --strict`, a fresh-venv smoke test and the rexlib tests
|
|
222
|
+
against the built wheel, then publishes by PyPI trusted publishing (no stored token). The GitHub environment
|
|
223
|
+
`pypi` should list the owner as required reviewer, so every upload waits for one approval.
|
|
224
|
+
|
|
225
|
+
License: MIT (see `LICENSE`).
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# rexlib: the standard library for AI apps (design: docs/design/2026-11-29-rexlib-1.0.md in the rex repository).
|
|
2
|
+
# Own version and tags (rexlib-vX.Y.Z); single version source: rexlib/__init__.py (read below).
|
|
3
|
+
[project]
|
|
4
|
+
# Distribution name on PyPI ("rexlib" is taken there); the import name stays `rexlib`.
|
|
5
|
+
name = "rexlib-py"
|
|
6
|
+
dynamic = ["version"]
|
|
7
|
+
description = "Stdlib-only building blocks for AI apps: messages, tools, providers, loop, model gateway"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
license-files = ["LICENSE"]
|
|
11
|
+
authors = [{name = "Peter Kokosharov", email = "peter.kokosharov@gmail.com"}]
|
|
12
|
+
requires-python = ">=3.12"
|
|
13
|
+
# No runtime dependencies: every module imports only the standard library. kikolib (design R5) joins when a module
|
|
14
|
+
# actually imports it (pre-release audit I2).
|
|
15
|
+
dependencies = []
|
|
16
|
+
keywords = ["llm", "ai", "agent", "gateway", "openai", "anthropic", "streaming", "tools", "stdlib"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Topic :: Software Development :: Libraries",
|
|
27
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
28
|
+
"Typing :: Typed",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/peterkokosharov/rex"
|
|
33
|
+
Source = "https://github.com/peterkokosharov/rex"
|
|
34
|
+
Changelog = "https://github.com/peterkokosharov/rex/blob/main/rexlib/CHANGELOG.md"
|
|
35
|
+
|
|
36
|
+
[build-system]
|
|
37
|
+
# >= 77: PEP 639 license expressions (license = "MIT", license-files)
|
|
38
|
+
requires = ["setuptools>=77"]
|
|
39
|
+
build-backend = "setuptools.build_meta"
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.dynamic]
|
|
42
|
+
version = {attr = "rexlib.__version__"}
|
|
43
|
+
|
|
44
|
+
[tool.setuptools.packages.find]
|
|
45
|
+
where = ["."]
|
|
46
|
+
include = ["rexlib", "rexlib.*"]
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.package-data]
|
|
49
|
+
# PEP 561: the package ships its inline types
|
|
50
|
+
rexlib = ["py.typed"]
|
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
"""rexlib: stdlib-only building blocks for AI apps.
|
|
6
|
+
|
|
7
|
+
``import rexlib`` loads nothing else: public names are re-exported lazily through ``__getattr__`` from the
|
|
8
|
+
sub-module listed for them in ``_EXPORTS``; the ``TYPE_CHECKING`` block gives type checkers the same names.
|
|
9
|
+
``__all__`` is the stability promise of 1.0 (core and gateway tiers); the 0.x parts (agent tier, app kit,
|
|
10
|
+
bridges) are reachable only by module name and are never listed here.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import importlib
|
|
16
|
+
from types import MappingProxyType
|
|
17
|
+
|
|
18
|
+
TYPE_CHECKING = False # True for type checkers; not imported from typing, so `import rexlib` loads no other module
|
|
19
|
+
if TYPE_CHECKING: # static types for the lazy names below; never runs (tests/test_rexlib_typed_exports.py)
|
|
20
|
+
# "X as X" marks an explicit re-export for strict type checkers (no implicit re-export).
|
|
21
|
+
from rexlib.container import Container as Container, ContainerError as ContainerError
|
|
22
|
+
from rexlib.container import detect_container as detect_container
|
|
23
|
+
from rexlib.gateway import PRESETS as PRESETS, CostCapExceeded as CostCapExceeded, Gateway as Gateway
|
|
24
|
+
from rexlib.gateway import GatewayConfig as GatewayConfig, GatewayOptions as GatewayOptions, Price as Price
|
|
25
|
+
from rexlib.gateway import AuditEvent as AuditEvent, AuditSink as AuditSink, CostMeter as CostMeter
|
|
26
|
+
from rexlib.gateway import JsonlAuditSink as JsonlAuditSink, LoggingAuditSink as LoggingAuditSink
|
|
27
|
+
from rexlib.gateway import ModelPrices as ModelPrices, StorageAuditSink as StorageAuditSink
|
|
28
|
+
from rexlib.gateway import StreamInterrupted as StreamInterrupted
|
|
29
|
+
from rexlib.gateway import ConfigError as ConfigError, LedgerError as LedgerError, Preset as Preset
|
|
30
|
+
from rexlib.loop import Decision as Decision, Limits as Limits, LoopHooks as LoopHooks
|
|
31
|
+
from rexlib.loop import RunOptions as RunOptions, RunResult as RunResult, RunStatus as RunStatus, Stop as Stop
|
|
32
|
+
from rexlib.loop import ToolDecision as ToolDecision, ToolPolicy as ToolPolicy, run as run
|
|
33
|
+
from rexlib.messages import ChatCompletion as ChatCompletion, ChatCompletionChunk as ChatCompletionChunk
|
|
34
|
+
from rexlib.messages import ChatMessage as ChatMessage, ToolCall as ToolCall, Usage as Usage
|
|
35
|
+
from rexlib.providers import ChatRequest as ChatRequest, Provider as Provider, ProviderError as ProviderError
|
|
36
|
+
from rexlib.providers.anthropic import AnthropicMessages as AnthropicMessages
|
|
37
|
+
from rexlib.providers.openai import OpenAIChat as OpenAIChat
|
|
38
|
+
from rexlib.storage import SqliteStorage as SqliteStorage, Storage as Storage, open_storage as open_storage
|
|
39
|
+
from rexlib.storage import StorageError as StorageError
|
|
40
|
+
from rexlib.tools import Tool as Tool, ToolRegistry as ToolRegistry, ToolResult as ToolResult
|
|
41
|
+
from rexlib.tools import ToolSchema as ToolSchema, function_tool as function_tool
|
|
42
|
+
|
|
43
|
+
__version__ = "0.9.0a1"
|
|
44
|
+
|
|
45
|
+
# public name -> sub-module that defines it
|
|
46
|
+
_EXPORTS: MappingProxyType[str, str] = MappingProxyType({
|
|
47
|
+
**dict.fromkeys(("ChatCompletion", "ChatCompletionChunk", "ChatMessage", "ToolCall", "Usage"), "rexlib.messages"),
|
|
48
|
+
**dict.fromkeys(("Tool", "ToolRegistry", "ToolResult", "ToolSchema", "function_tool"), "rexlib.tools"),
|
|
49
|
+
**dict.fromkeys(("ChatRequest", "Provider", "ProviderError"), "rexlib.providers"),
|
|
50
|
+
"OpenAIChat": "rexlib.providers.openai",
|
|
51
|
+
"AnthropicMessages": "rexlib.providers.anthropic",
|
|
52
|
+
**dict.fromkeys(("Decision", "Limits", "LoopHooks", "RunOptions", "RunResult", "RunStatus", "Stop", "ToolDecision",
|
|
53
|
+
"ToolPolicy", "run"), "rexlib.loop"),
|
|
54
|
+
**dict.fromkeys(("SqliteStorage", "Storage", "StorageError", "open_storage"), "rexlib.storage"),
|
|
55
|
+
**dict.fromkeys(("Container", "ContainerError", "detect_container"), "rexlib.container"),
|
|
56
|
+
**dict.fromkeys(("AuditEvent", "AuditSink", "ConfigError", "CostCapExceeded", "CostMeter", "Gateway",
|
|
57
|
+
"GatewayConfig", "GatewayOptions", "JsonlAuditSink", "LedgerError", "LoggingAuditSink",
|
|
58
|
+
"ModelPrices", "PRESETS", "Preset", "Price", "StorageAuditSink", "StreamInterrupted"),
|
|
59
|
+
"rexlib.gateway"),
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
__all__ = sorted(_EXPORTS)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def __getattr__(name: str) -> object:
|
|
66
|
+
module = _EXPORTS.get(name)
|
|
67
|
+
if module is None:
|
|
68
|
+
raise AttributeError(f"module 'rexlib' has no attribute {name!r}")
|
|
69
|
+
value = getattr(importlib.import_module(module), name)
|
|
70
|
+
globals()[name] = value # resolve once
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def __dir__() -> list[str]:
|
|
75
|
+
return sorted(set(globals()) | set(_EXPORTS))
|