readthrough 0.4.0__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.
- readthrough/__init__.py +8 -0
- readthrough/__main__.py +3 -0
- readthrough/agents.py +344 -0
- readthrough/analyze.py +537 -0
- readthrough/assets/SKILL.md +86 -0
- readthrough/assets/defaults.toml +143 -0
- readthrough/assets/profile-reference.md +133 -0
- readthrough/assets/vendor/README.md +22 -0
- readthrough/assets/vendor/cose-base.js +3214 -0
- readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
- readthrough/assets/vendor/cytoscape.min.js +31 -0
- readthrough/assets/vendor/layout-base.js +5230 -0
- readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
- readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
- readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
- readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
- readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
- readthrough/assets/vendor/lucide-icons.js +36 -0
- readthrough/assets/vendor/marked.umd.js +82 -0
- readthrough/assets/vendor/purify.min.js +7 -0
- readthrough/assets/web/dashboard.css +202 -0
- readthrough/assets/web/dashboard.html +48 -0
- readthrough/assets/web/dashboard.js +937 -0
- readthrough/assets/web/setup.css +57 -0
- readthrough/assets/web/setup.html +28 -0
- readthrough/assets/web/setup.js +342 -0
- readthrough/assets/web/theme.css +36 -0
- readthrough/assistants.py +699 -0
- readthrough/brief.py +145 -0
- readthrough/build.py +616 -0
- readthrough/ci.py +107 -0
- readthrough/cli.py +958 -0
- readthrough/config.py +533 -0
- readthrough/contract.py +394 -0
- readthrough/engine.py +230 -0
- readthrough/faults.py +92 -0
- readthrough/files.py +110 -0
- readthrough/forges/__init__.py +614 -0
- readthrough/forges/azure_devops.py +658 -0
- readthrough/forges/forgejo.py +300 -0
- readthrough/forges/github.py +487 -0
- readthrough/forges/gitlab.py +335 -0
- readthrough/ledger.py +61 -0
- readthrough/limits.py +26 -0
- readthrough/logs.py +169 -0
- readthrough/membership.py +76 -0
- readthrough/model.py +177 -0
- readthrough/onboard.py +551 -0
- readthrough/onboard_model.py +319 -0
- readthrough/process.py +169 -0
- readthrough/profile.py +699 -0
- readthrough/py.typed +0 -0
- readthrough/registry.py +157 -0
- readthrough/review.py +394 -0
- readthrough/rules.py +111 -0
- readthrough/runtimes/__init__.py +297 -0
- readthrough/runtimes/anthropic.py +278 -0
- readthrough/runtimes/copilot.py +313 -0
- readthrough/runtimes/openai.py +307 -0
- readthrough/serve.py +817 -0
- readthrough/study.py +327 -0
- readthrough/system.py +205 -0
- readthrough/terminals.py +168 -0
- readthrough/tuning.py +266 -0
- readthrough/usage.py +169 -0
- readthrough/web_setup.py +635 -0
- readthrough-0.4.0.dist-info/METADATA +123 -0
- readthrough-0.4.0.dist-info/RECORD +73 -0
- readthrough-0.4.0.dist-info/WHEEL +4 -0
- readthrough-0.4.0.dist-info/entry_points.txt +2 -0
- readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""Model runtimes: the engines a study assistant runs on, behind one small protocol.
|
|
2
|
+
|
|
3
|
+
The study assistant's behaviour (the Socratic prompt, the eight tools, the evidence it writes) is the same
|
|
4
|
+
whoever the model is. What differs is mechanical: how a conversation is opened, how a prompt is sent, how
|
|
5
|
+
text, tool calls, and usage come back, and how a credential is found. That is a ``Runtime``. Each one is a
|
|
6
|
+
plugin in ``RUNTIMES``, with a dataclass of options the config loader validates:
|
|
7
|
+
|
|
8
|
+
* ``copilot`` runs on the Copilot SDK (the Copilot CLI as an engine). GitHub Copilot through its sign-in,
|
|
9
|
+
or a model provider of your own, with no GitHub account involved.
|
|
10
|
+
* ``anthropic`` talks to the Messages API over ``urllib``, with the tool loop here. Needs only an API key.
|
|
11
|
+
* ``openai`` talks to the Responses API the same way (OpenAI, or Azure OpenAI and Foundry with Entra).
|
|
12
|
+
|
|
13
|
+
A runtime never writes to the study log and never sees the harness; it hands the assistant ``Event``s and
|
|
14
|
+
calls the tool handlers the assistant gave it. Everything that must be true of the log (who wrote what, which
|
|
15
|
+
model reached a verdict, what each call cost) is the assistant's and the ledger's business.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import random
|
|
24
|
+
import time
|
|
25
|
+
from collections.abc import AsyncIterator, Callable, Coroutine
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any, Protocol
|
|
28
|
+
|
|
29
|
+
from readthrough.registry import Registry
|
|
30
|
+
|
|
31
|
+
log = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class ToolSpec:
|
|
36
|
+
"""One tool the assistant offers, in readthrough's own terms. Runtimes translate it to their wire format.
|
|
37
|
+
|
|
38
|
+
``schema`` is a JSON schema for the arguments (an object with properties). ``terminal`` tools end the
|
|
39
|
+
assistant's turn once called (asking a quiz question); a runtime stops the loop after one.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
name: str
|
|
43
|
+
description: str
|
|
44
|
+
schema: dict[str, Any]
|
|
45
|
+
handler: Callable[[dict[str, Any]], Coroutine[Any, Any, str]]
|
|
46
|
+
terminal: bool = False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Event:
|
|
51
|
+
"""What a runtime reports while a prompt runs. ``kind`` is one of:
|
|
52
|
+
|
|
53
|
+
``text``: ``text`` holds a delta of the reply.
|
|
54
|
+
``tool``: ``name`` holds a tool the model is calling (reported before the handler runs).
|
|
55
|
+
``usage``: ``usage`` holds one model call's accounting (see ``Usage``).
|
|
56
|
+
``done``: the turn ended; ``text`` holds the whole reply.
|
|
57
|
+
``error``: ``text`` holds why the turn failed.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
kind: str
|
|
61
|
+
text: str = ""
|
|
62
|
+
name: str = ""
|
|
63
|
+
usage: Usage | None = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class Usage:
|
|
68
|
+
"""One model call, in the provider's units. A quantity the provider didn't report is None, never 0."""
|
|
69
|
+
|
|
70
|
+
call_id: str | None
|
|
71
|
+
model: str
|
|
72
|
+
input_tokens: int | None = None
|
|
73
|
+
output_tokens: int | None = None
|
|
74
|
+
cache_read_tokens: int | None = None
|
|
75
|
+
cache_write_tokens: int | None = None
|
|
76
|
+
reasoning_tokens: int | None = None
|
|
77
|
+
multiplier: float | None = None # Copilot's premium-request multiplier
|
|
78
|
+
nano_aiu: float | None = None # Copilot's AI-credit consumption
|
|
79
|
+
billed_to: str = "" # who paid: "copilot", "anthropic:api.anthropic.com", ...
|
|
80
|
+
|
|
81
|
+
def tokens(self) -> dict[str, int]:
|
|
82
|
+
pairs = {
|
|
83
|
+
"input": self.input_tokens, "output": self.output_tokens, "cache_read": self.cache_read_tokens,
|
|
84
|
+
"cache_write": self.cache_write_tokens, "reasoning": self.reasoning_tokens,
|
|
85
|
+
} # fmt: skip
|
|
86
|
+
return {k: v for k, v in pairs.items() if v is not None}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass
|
|
90
|
+
class Conversation:
|
|
91
|
+
"""What a runtime needs to open a conversation about one PR."""
|
|
92
|
+
|
|
93
|
+
key: str # stable per PR, so a runtime that persists conversations can resume this one
|
|
94
|
+
system: str
|
|
95
|
+
tools: list[ToolSpec]
|
|
96
|
+
working_directory: str
|
|
97
|
+
model: str | None = None # the repo's own choice; None means the runtime's configured default
|
|
98
|
+
resume: bool = True # whether an existing conversation under ``key`` should be continued
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Session(Protocol):
|
|
102
|
+
"""An open conversation. ``send`` yields events until the turn is done or fails."""
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def fresh(self) -> bool: ... # True when this is a new conversation (the assistant then sends context)
|
|
106
|
+
|
|
107
|
+
def send(self, prompt: str) -> AsyncIterator[Event]: ...
|
|
108
|
+
async def close(self) -> None: ...
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Runtime(Protocol):
|
|
112
|
+
name: str # the registry name, which the study log records as ``runtime`` on what the model writes
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def model(self) -> str | None: ... # the configured model, or None when the provider picks (Copilot's default)
|
|
116
|
+
|
|
117
|
+
async def open(self, conversation: Conversation) -> Session: ...
|
|
118
|
+
async def stop(self) -> None: ...
|
|
119
|
+
def describe(self) -> str: ... # for doctor: engine and payer, never a secret
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
RuntimeFactory = Callable[[Any], Runtime]
|
|
123
|
+
RUNTIMES: Registry[RuntimeFactory] = Registry("model runtime")
|
|
124
|
+
AUTO_ORDER = ("copilot", "anthropic", "openai")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def available(name: str) -> tuple[bool, str]:
|
|
128
|
+
"""Whether a runtime can run here, and why not."""
|
|
129
|
+
if name == "copilot":
|
|
130
|
+
try:
|
|
131
|
+
import copilot # noqa: F401
|
|
132
|
+
except ImportError:
|
|
133
|
+
return False, "the copilot runtime needs the Copilot SDK: install readthrough with the [study] extra"
|
|
134
|
+
return True, ""
|
|
135
|
+
if name in ("anthropic", "openai"):
|
|
136
|
+
plugin = RUNTIMES.get(name)
|
|
137
|
+
env = plugin.options.api_key_env # type: ignore[attr-defined] - both option classes declare it
|
|
138
|
+
if not os.environ.get(env, "").strip() and not getattr(plugin.options, "entra", False):
|
|
139
|
+
return False, f"the {name} runtime needs an API key in {env}"
|
|
140
|
+
return True, ""
|
|
141
|
+
RUNTIMES.get(name)
|
|
142
|
+
return True, ""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def resolve(name: str, options: dict[str, Any] | None = None) -> tuple[str, bool, str]:
|
|
146
|
+
"""Which runtime ``name`` means: itself, or for ``auto`` the first that can run. Returns (name, ok, reason)."""
|
|
147
|
+
if name != "auto":
|
|
148
|
+
ok, why = _available_with(name, options)
|
|
149
|
+
return name, ok, why
|
|
150
|
+
for candidate in AUTO_ORDER:
|
|
151
|
+
ok, _ = _available_with(candidate, options)
|
|
152
|
+
if ok:
|
|
153
|
+
return candidate, True, ""
|
|
154
|
+
return AUTO_ORDER[0], False, "no model runtime is available: install the [study] extra, or set an API key"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _available_with(name: str, options: dict[str, Any] | None) -> tuple[bool, str]:
|
|
158
|
+
opts = (options or {}).get(name)
|
|
159
|
+
if opts is not None and hasattr(opts, "can_run"):
|
|
160
|
+
return opts.can_run()
|
|
161
|
+
return available(name)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def make(name: str, options: dict[str, Any] | None = None) -> Runtime:
|
|
165
|
+
"""Build the configured runtime. ``options`` maps runtime names to validated options objects."""
|
|
166
|
+
resolved, ok, why = resolve(name, options)
|
|
167
|
+
if not ok:
|
|
168
|
+
raise RuntimeError(why)
|
|
169
|
+
factory = RUNTIMES.get(resolved)
|
|
170
|
+
opts = (options or {}).get(resolved) or RUNTIMES.defaults_for(resolved)
|
|
171
|
+
return factory.impl(opts)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def tool_schema(spec: ToolSpec) -> dict[str, Any]:
|
|
175
|
+
"""The JSON schema a wire format wants: an object with the tool's properties, nothing extra."""
|
|
176
|
+
schema = dict(spec.schema)
|
|
177
|
+
schema.setdefault("type", "object")
|
|
178
|
+
schema.setdefault("properties", {})
|
|
179
|
+
return schema
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
RETRY_STATUSES = frozenset({408, 409, 429, 500, 502, 503, 504, 529}) # 529 is Anthropic's "overloaded"
|
|
183
|
+
RETRY_ATTEMPTS = 4
|
|
184
|
+
RETRY_BACKOFF_SECONDS = 2.0
|
|
185
|
+
RETRY_MAX_WAIT_SECONDS = 30.0
|
|
186
|
+
JITTER_MAX = 0.25
|
|
187
|
+
jitter = random.Random() # noqa: S311 - timing jitter, not security; its own generator so tests can seed it
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def retry_wait(attempt: int, retry_after: str | None, rng: random.Random | None = None) -> float:
|
|
191
|
+
"""Seconds before retry ``attempt`` (from 1): what the provider asked for in ``Retry-After`` when it did,
|
|
192
|
+
else exponential with jitter; never more than ``RETRY_MAX_WAIT_SECONDS``, so a turn can't stall on a bad
|
|
193
|
+
header."""
|
|
194
|
+
if retry_after:
|
|
195
|
+
try:
|
|
196
|
+
return min(RETRY_MAX_WAIT_SECONDS, max(0.0, float(retry_after)))
|
|
197
|
+
except ValueError:
|
|
198
|
+
pass # an HTTP-date: fall back to backoff rather than parse clocks
|
|
199
|
+
base = RETRY_BACKOFF_SECONDS * 2 ** (attempt - 1)
|
|
200
|
+
return min(RETRY_MAX_WAIT_SECONDS, base * (1 + (rng or jitter).uniform(0, JITTER_MAX)))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def with_retries(
|
|
204
|
+
what: str, call: Callable[[], Any], *, sleep: Callable[[float], None] | None = None, attempts: int = RETRY_ATTEMPTS
|
|
205
|
+
) -> Any:
|
|
206
|
+
"""Run one HTTP call, retrying the failures a provider says are temporary: rate limits, overload, gateway
|
|
207
|
+
errors, and a dropped connection. Anything else (a bad key, a bad request) is raised at once; so is the
|
|
208
|
+
last attempt, as the ``Retryable`` the caller turns into a message."""
|
|
209
|
+
for attempt in range(1, attempts + 1):
|
|
210
|
+
try:
|
|
211
|
+
return call()
|
|
212
|
+
except Retryable as exc:
|
|
213
|
+
if attempt == attempts:
|
|
214
|
+
raise
|
|
215
|
+
wait = retry_wait(attempt, exc.retry_after)
|
|
216
|
+
log.info("%s: %s; retrying in %.1fs (%d/%d)", what, exc, wait, attempt, attempts - 1)
|
|
217
|
+
(sleep or time.sleep)(wait)
|
|
218
|
+
raise AssertionError("unreachable")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class Retryable(RuntimeError):
|
|
222
|
+
"""A provider answered in a way that says "try again": the status and any ``Retry-After`` it sent."""
|
|
223
|
+
|
|
224
|
+
def __init__(self, message: str, *, retry_after: str | None = None) -> None:
|
|
225
|
+
super().__init__(message)
|
|
226
|
+
self.retry_after = retry_after
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def parse_arguments(raw: Any) -> dict[str, Any]:
|
|
230
|
+
"""Tool arguments as a dict, whether the provider sent an object or a JSON string."""
|
|
231
|
+
if isinstance(raw, dict):
|
|
232
|
+
return raw
|
|
233
|
+
if isinstance(raw, str) and raw.strip():
|
|
234
|
+
try:
|
|
235
|
+
parsed = json.loads(raw)
|
|
236
|
+
except ValueError:
|
|
237
|
+
return {}
|
|
238
|
+
return parsed if isinstance(parsed, dict) else {}
|
|
239
|
+
return {}
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def check_arguments(spec: ToolSpec, args: dict[str, Any]) -> dict[str, Any]:
|
|
243
|
+
"""The arguments a model sent, held to the tool's schema before a handler sees them.
|
|
244
|
+
|
|
245
|
+
The model is the other side of a trust boundary: what it reads (a PR's text) can tell it what to send. Unknown
|
|
246
|
+
properties are dropped, each value is coerced to its declared type or refused (a TypeError for the wrong
|
|
247
|
+
shape, a ValueError for the wrong value), and a missing required argument is refused. The Copilot SDK does
|
|
248
|
+
the same through pydantic; the REST runtimes do it here.
|
|
249
|
+
"""
|
|
250
|
+
properties = spec.schema.get("properties") or {}
|
|
251
|
+
required = set(spec.schema.get("required") or [])
|
|
252
|
+
out: dict[str, Any] = {}
|
|
253
|
+
for name, prop in properties.items():
|
|
254
|
+
if name not in args or args[name] is None:
|
|
255
|
+
if name in required:
|
|
256
|
+
raise ValueError(f"{spec.name}: missing required argument {name!r}")
|
|
257
|
+
continue
|
|
258
|
+
out[name] = _coerce(args[name], prop, f"{spec.name}.{name}")
|
|
259
|
+
return out
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _coerce(value: Any, prop: dict[str, Any], where: str) -> Any:
|
|
263
|
+
kind = prop.get("type", "string")
|
|
264
|
+
if kind == "array":
|
|
265
|
+
if not isinstance(value, list):
|
|
266
|
+
raise TypeError(f"{where} must be a list")
|
|
267
|
+
item = prop.get("items") or {"type": "string"}
|
|
268
|
+
return [_coerce(v, item, f"{where}[]") for v in value]
|
|
269
|
+
if kind == "integer":
|
|
270
|
+
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
|
|
271
|
+
raise TypeError(f"{where} must be an integer")
|
|
272
|
+
try:
|
|
273
|
+
number = float(value)
|
|
274
|
+
except ValueError:
|
|
275
|
+
raise ValueError(f"{where} must be an integer") from None
|
|
276
|
+
if not number.is_integer():
|
|
277
|
+
raise ValueError(f"{where} must be an integer")
|
|
278
|
+
return int(number)
|
|
279
|
+
if kind == "number":
|
|
280
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
281
|
+
raise TypeError(f"{where} must be a number")
|
|
282
|
+
return float(value)
|
|
283
|
+
if kind == "boolean":
|
|
284
|
+
if not isinstance(value, bool):
|
|
285
|
+
raise TypeError(f"{where} must be true or false")
|
|
286
|
+
return value
|
|
287
|
+
if not isinstance(value, (str, int, float, bool)):
|
|
288
|
+
raise TypeError(f"{where} must be a string")
|
|
289
|
+
return str(value)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _register_builtin() -> None:
|
|
293
|
+
# Imported here so each runtime module can import this one.
|
|
294
|
+
from readthrough.runtimes import anthropic, copilot, openai # noqa: F401
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
_register_builtin()
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Anthropic's Messages API as a runtime: Claude, with nothing installed but an API key.
|
|
2
|
+
|
|
3
|
+
The tool loop lives here. A turn is a sequence of calls: the model answers with text and ``tool_use``
|
|
4
|
+
blocks; each tool runs and its result goes back as a ``tool_result``; this repeats until the model stops,
|
|
5
|
+
a terminal tool (asking a quiz question) is called, or the call cap is hit. Responses stream, so text
|
|
6
|
+
reaches the page as it is written. The conversation is kept in memory for the process's lifetime (the
|
|
7
|
+
assistant resends the brief on a fresh one, and the study log is the record either way).
|
|
8
|
+
|
|
9
|
+
Prompt caching: the system message and the tools are marked cacheable, since they repeat on every call.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.request
|
|
20
|
+
from collections.abc import AsyncIterator
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any
|
|
23
|
+
from urllib.parse import urlsplit
|
|
24
|
+
|
|
25
|
+
from readthrough.process import Secret, redact, remember
|
|
26
|
+
from readthrough.runtimes import (
|
|
27
|
+
RETRY_ATTEMPTS,
|
|
28
|
+
RETRY_STATUSES,
|
|
29
|
+
RUNTIMES,
|
|
30
|
+
Conversation,
|
|
31
|
+
Event,
|
|
32
|
+
Retryable,
|
|
33
|
+
Usage,
|
|
34
|
+
check_arguments,
|
|
35
|
+
parse_arguments,
|
|
36
|
+
tool_schema,
|
|
37
|
+
with_retries,
|
|
38
|
+
)
|
|
39
|
+
from readthrough.tuning import default_tuning
|
|
40
|
+
|
|
41
|
+
log = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
API_VERSION = "2023-06-01"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class AnthropicOptions:
|
|
48
|
+
model: str = "claude-sonnet-5-5"
|
|
49
|
+
base_url: str = "https://api.anthropic.com"
|
|
50
|
+
api_key_env: str = "ANTHROPIC_API_KEY"
|
|
51
|
+
max_tokens: int = 4096
|
|
52
|
+
max_calls_per_turn: int = 12 # a turn is one prompt; each tool round is one more model call
|
|
53
|
+
|
|
54
|
+
def can_run(self) -> tuple[bool, str]:
|
|
55
|
+
if not os.environ.get(self.api_key_env, "").strip():
|
|
56
|
+
return False, f"the anthropic runtime needs an API key in {self.api_key_env}"
|
|
57
|
+
return True, ""
|
|
58
|
+
|
|
59
|
+
def key(self) -> Secret:
|
|
60
|
+
value = os.environ.get(self.api_key_env, "").strip()
|
|
61
|
+
if not value:
|
|
62
|
+
raise RuntimeError(f"The anthropic runtime needs an API key in {self.api_key_env} (never in config.toml).")
|
|
63
|
+
return remember(Secret(value))
|
|
64
|
+
|
|
65
|
+
def billed_to(self) -> str:
|
|
66
|
+
return f"anthropic:{urlsplit(self.base_url).hostname or self.base_url}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class AnthropicRuntime:
|
|
70
|
+
name = "anthropic"
|
|
71
|
+
|
|
72
|
+
def __init__(self, options: Any) -> None:
|
|
73
|
+
self.options: AnthropicOptions = options if isinstance(options, AnthropicOptions) else AnthropicOptions()
|
|
74
|
+
self._conversations: dict[str, AnthropicSession] = {}
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def model(self) -> str | None:
|
|
78
|
+
return self.options.model
|
|
79
|
+
|
|
80
|
+
def describe(self) -> str:
|
|
81
|
+
return f"Anthropic Messages API at {self.options.base_url} ({self.options.model})"
|
|
82
|
+
|
|
83
|
+
async def open(self, conversation: Conversation) -> AnthropicSession:
|
|
84
|
+
if conversation.resume and conversation.key in self._conversations:
|
|
85
|
+
return self._conversations[conversation.key]
|
|
86
|
+
session = AnthropicSession(self.options, conversation)
|
|
87
|
+
self._conversations[conversation.key] = session
|
|
88
|
+
return session
|
|
89
|
+
|
|
90
|
+
async def stop(self) -> None:
|
|
91
|
+
self._conversations.clear()
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class AnthropicSession:
|
|
95
|
+
def __init__(self, options: AnthropicOptions, conversation: Conversation) -> None:
|
|
96
|
+
self.options = options
|
|
97
|
+
self.conversation = conversation
|
|
98
|
+
self.model = conversation.model or options.model
|
|
99
|
+
self.messages: list[dict[str, Any]] = [] # the transcript, in the API's shape
|
|
100
|
+
self._tools = {t.name: t for t in conversation.tools}
|
|
101
|
+
self._fresh = True
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def fresh(self) -> bool:
|
|
105
|
+
return self._fresh
|
|
106
|
+
|
|
107
|
+
async def close(self) -> None:
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
def _request_body(self) -> dict[str, Any]:
|
|
111
|
+
tools = [
|
|
112
|
+
{"name": t.name, "description": t.description, "input_schema": tool_schema(t)}
|
|
113
|
+
for t in self.conversation.tools
|
|
114
|
+
]
|
|
115
|
+
if tools:
|
|
116
|
+
tools[-1]["cache_control"] = {"type": "ephemeral"}
|
|
117
|
+
return {
|
|
118
|
+
"model": self.model,
|
|
119
|
+
"max_tokens": self.options.max_tokens,
|
|
120
|
+
"system": [{"type": "text", "text": self.conversation.system, "cache_control": {"type": "ephemeral"}}],
|
|
121
|
+
"tools": tools,
|
|
122
|
+
"messages": self.messages,
|
|
123
|
+
"stream": True,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async def send(self, prompt: str) -> AsyncIterator[Event]:
|
|
127
|
+
self._fresh = False
|
|
128
|
+
self.messages.append({"role": "user", "content": [{"type": "text", "text": prompt}]})
|
|
129
|
+
reply: list[str] = []
|
|
130
|
+
for _ in range(self.options.max_calls_per_turn):
|
|
131
|
+
try:
|
|
132
|
+
result = await asyncio.to_thread(self._call)
|
|
133
|
+
except RuntimeError as exc:
|
|
134
|
+
yield Event("error", text=str(exc))
|
|
135
|
+
return
|
|
136
|
+
text, tool_uses, used = result
|
|
137
|
+
if text:
|
|
138
|
+
reply.append(text)
|
|
139
|
+
yield Event("text", text=text)
|
|
140
|
+
yield Event("usage", usage=used)
|
|
141
|
+
content: list[dict[str, Any]] = []
|
|
142
|
+
if text:
|
|
143
|
+
content.append({"type": "text", "text": text})
|
|
144
|
+
content += [{"type": "tool_use", "id": u["id"], "name": u["name"], "input": u["input"]} for u in tool_uses]
|
|
145
|
+
self.messages.append({"role": "assistant", "content": content})
|
|
146
|
+
if not tool_uses:
|
|
147
|
+
yield Event("done", text="".join(reply))
|
|
148
|
+
return
|
|
149
|
+
results: list[dict[str, Any]] = []
|
|
150
|
+
terminal = False
|
|
151
|
+
for use in tool_uses:
|
|
152
|
+
spec = self._tools.get(use["name"])
|
|
153
|
+
yield Event("tool", name=use["name"])
|
|
154
|
+
if spec is None:
|
|
155
|
+
output = f"Unknown tool {use['name']!r}."
|
|
156
|
+
else:
|
|
157
|
+
try:
|
|
158
|
+
output = await spec.handler(check_arguments(spec, parse_arguments(use["input"])))
|
|
159
|
+
except Exception as exc: # noqa: BLE001 - the model gets the error as a result, like any tool runner
|
|
160
|
+
output = f"Tool failed: {exc}"
|
|
161
|
+
terminal = terminal or spec.terminal
|
|
162
|
+
results.append({"type": "tool_result", "tool_use_id": use["id"], "content": output})
|
|
163
|
+
self.messages.append({"role": "user", "content": results})
|
|
164
|
+
if terminal:
|
|
165
|
+
yield Event("done", text="".join(reply))
|
|
166
|
+
return
|
|
167
|
+
if reply and not reply[-1].endswith("\n"):
|
|
168
|
+
reply.append("\n\n")
|
|
169
|
+
yield Event("error", text=f"the model made more than {self.options.max_calls_per_turn} calls in one turn")
|
|
170
|
+
|
|
171
|
+
def _call(self) -> tuple[str, list[dict[str, Any]], Usage]:
|
|
172
|
+
"""One streamed Messages call. Returns (text, tool uses, usage)."""
|
|
173
|
+
body = json.dumps(self._request_body()).encode("utf-8")
|
|
174
|
+
req = urllib.request.Request( # noqa: S310 - an https API URL from config
|
|
175
|
+
self.options.base_url.rstrip("/") + "/v1/messages",
|
|
176
|
+
data=body,
|
|
177
|
+
method="POST",
|
|
178
|
+
headers={
|
|
179
|
+
"content-type": "application/json",
|
|
180
|
+
"anthropic-version": API_VERSION,
|
|
181
|
+
"accept": "text/event-stream",
|
|
182
|
+
"user-agent": "readthrough",
|
|
183
|
+
},
|
|
184
|
+
)
|
|
185
|
+
req.add_unredirected_header("x-api-key", self.options.key().reveal())
|
|
186
|
+
timeout = default_tuning().study.turn_timeout_seconds
|
|
187
|
+
|
|
188
|
+
def once() -> tuple[str, list[dict[str, Any]], Usage]:
|
|
189
|
+
try:
|
|
190
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
|
|
191
|
+
request_id = resp.headers.get("request-id")
|
|
192
|
+
return self._read_stream(resp, request_id)
|
|
193
|
+
except urllib.error.HTTPError as exc:
|
|
194
|
+
text = redact(exc.read().decode("utf-8", "replace"))
|
|
195
|
+
message = f"Anthropic refused the call: {_error_message(text) or f'HTTP {exc.code}'}"
|
|
196
|
+
if exc.code in RETRY_STATUSES:
|
|
197
|
+
raise Retryable(message, retry_after=exc.headers.get("retry-after")) from exc
|
|
198
|
+
raise RuntimeError(message) from exc
|
|
199
|
+
except urllib.error.URLError as exc:
|
|
200
|
+
raise Retryable(f"couldn't reach {self.options.base_url}: {exc.reason}") from exc
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
return with_retries("Anthropic", once)
|
|
204
|
+
except Retryable as exc:
|
|
205
|
+
raise RuntimeError(f"{exc} (gave up after {RETRY_ATTEMPTS} attempts)") from exc
|
|
206
|
+
|
|
207
|
+
def _read_stream(self, resp: Any, request_id: str | None) -> tuple[str, list[dict[str, Any]], Usage]:
|
|
208
|
+
text: list[str] = []
|
|
209
|
+
blocks: dict[int, dict[str, Any]] = {} # index -> tool_use block being assembled
|
|
210
|
+
partial: dict[int, list[str]] = {}
|
|
211
|
+
model = self.model
|
|
212
|
+
message_id = None
|
|
213
|
+
usage: dict[str, Any] = {}
|
|
214
|
+
for raw in resp:
|
|
215
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
216
|
+
if not line.startswith("data:"):
|
|
217
|
+
continue
|
|
218
|
+
event = json.loads(line[5:].strip())
|
|
219
|
+
kind = event.get("type")
|
|
220
|
+
if kind == "message_start":
|
|
221
|
+
message = event.get("message") or {}
|
|
222
|
+
model = message.get("model") or model
|
|
223
|
+
message_id = message.get("id")
|
|
224
|
+
usage.update(message.get("usage") or {})
|
|
225
|
+
elif kind == "content_block_start":
|
|
226
|
+
block = event.get("content_block") or {}
|
|
227
|
+
if block.get("type") == "tool_use":
|
|
228
|
+
blocks[event["index"]] = {"id": block.get("id"), "name": block.get("name"), "input": {}}
|
|
229
|
+
partial[event["index"]] = []
|
|
230
|
+
elif kind == "content_block_delta":
|
|
231
|
+
delta = event.get("delta") or {}
|
|
232
|
+
if delta.get("type") == "text_delta":
|
|
233
|
+
text.append(delta.get("text") or "")
|
|
234
|
+
elif delta.get("type") == "input_json_delta":
|
|
235
|
+
partial.setdefault(event["index"], []).append(delta.get("partial_json") or "")
|
|
236
|
+
elif kind == "message_delta":
|
|
237
|
+
usage.update(event.get("usage") or {}) # output_tokens here is cumulative
|
|
238
|
+
elif kind == "error":
|
|
239
|
+
error = event.get("error") or {}
|
|
240
|
+
raise RuntimeError(
|
|
241
|
+
f"Anthropic reported an error mid-stream: {error.get('message') or error.get('type')}"
|
|
242
|
+
)
|
|
243
|
+
tool_uses = []
|
|
244
|
+
for index, block in blocks.items():
|
|
245
|
+
block["input"] = parse_arguments("".join(partial.get(index) or []))
|
|
246
|
+
tool_uses.append(block)
|
|
247
|
+
used = Usage(
|
|
248
|
+
call_id=request_id or message_id,
|
|
249
|
+
model=model,
|
|
250
|
+
input_tokens=usage.get("input_tokens"),
|
|
251
|
+
output_tokens=usage.get("output_tokens"),
|
|
252
|
+
cache_read_tokens=usage.get("cache_read_input_tokens"),
|
|
253
|
+
cache_write_tokens=usage.get("cache_creation_input_tokens"),
|
|
254
|
+
billed_to=self.options.billed_to(),
|
|
255
|
+
)
|
|
256
|
+
return "".join(text), tool_uses, used
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _error_message(text: str) -> str | None:
|
|
260
|
+
try:
|
|
261
|
+
data = json.loads(text)
|
|
262
|
+
except ValueError:
|
|
263
|
+
return text.strip()[:200] or None
|
|
264
|
+
error = data.get("error") if isinstance(data, dict) else None
|
|
265
|
+
if isinstance(error, dict):
|
|
266
|
+
return f"{error.get('type') or 'error'}: {error.get('message') or ''}".strip(": ")
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
async def asyncio_to_thread(fn: Any) -> Any:
|
|
271
|
+
import asyncio
|
|
272
|
+
|
|
273
|
+
return await asyncio.to_thread(fn)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
RUNTIMES.add("anthropic", "Claude through Anthropic's Messages API; needs only an API key", options=AnthropicOptions)(
|
|
277
|
+
AnthropicRuntime
|
|
278
|
+
)
|