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.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,313 @@
1
+ """The Copilot SDK as a runtime: GitHub Copilot through its sign-in, or a model provider of your own.
2
+
3
+ The SDK drives the Copilot CLI as an engine. By default it talks to GitHub Copilot as whoever the CLI is
4
+ signed in as; with ``provider`` set it talks to that provider instead (the SDK's "bring your own key"),
5
+ and the client is built so it never falls back to a GitHub login. Conversations persist in the CLI's
6
+ session store, so a PR's study conversation resumes across server restarts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ import os
14
+ import uuid
15
+ from collections.abc import AsyncIterator
16
+ from dataclasses import dataclass
17
+ from typing import Any
18
+ from urllib.parse import urlsplit
19
+
20
+ from readthrough.process import quiet_output
21
+ from readthrough.runtimes import RUNTIMES, Conversation, Event, ToolSpec, Usage
22
+ from readthrough.tuning import default_tuning
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ PROVIDER_TYPES = ("openai", "azure", "anthropic")
27
+ COGNITIVE_SERVICES = "https://cognitiveservices.azure.com"
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class CopilotOptions:
32
+ """Where the model comes from: GitHub Copilot by default, else a provider of your own (no GitHub sign-in).
33
+ The key is read from ``api_key_env``, never from the config file."""
34
+
35
+ provider: str | None = None # openai | azure | anthropic; unset means GitHub Copilot
36
+ base_url: str | None = None # the provider's endpoint, e.g. https://api.anthropic.com or an Azure resource
37
+ model: str | None = None # the provider's model name; a repo's `study_model` still wins when set
38
+ api_key_env: str = "READTHROUGH_MODEL_API_KEY"
39
+ # azure only: sign in with `az` (an Entra token for Cognitive Services) instead of a key. Many Azure
40
+ # OpenAI resources have key auth disabled by policy, so this is often the only way in.
41
+ entra: bool = False
42
+ wire_api: str | None = None # openai only: completions | responses (the SDK's default when unset)
43
+ azure_api_version: str | None = None # azure only
44
+
45
+ def __post_init__(self) -> None:
46
+ if self.provider is not None and self.provider not in PROVIDER_TYPES:
47
+ raise ValueError(f"provider must be one of {', '.join(PROVIDER_TYPES)}, not {self.provider!r}")
48
+ if self.provider is not None and not self.base_url:
49
+ raise ValueError("a provider needs base_url")
50
+ if self.provider is not None and not self.model:
51
+ raise ValueError("a provider needs model: the model name it serves")
52
+ if self.entra and self.provider != "azure":
53
+ raise ValueError("entra sign-in applies to the azure provider only")
54
+
55
+ @property
56
+ def byok(self) -> bool:
57
+ return self.provider is not None
58
+
59
+ def can_run(self) -> tuple[bool, str]:
60
+ try:
61
+ import copilot # noqa: F401
62
+ except ImportError:
63
+ return False, "the copilot runtime needs the Copilot SDK: install readthrough with the [study] extra"
64
+ if self.byok and not self.entra and not os.environ.get(self.api_key_env, "").strip():
65
+ return False, f"the copilot runtime is set to use {self.provider}, but {self.api_key_env} isn't set"
66
+ return True, ""
67
+
68
+ def provider_config(self) -> dict[str, Any] | None:
69
+ """The SDK's ``ProviderConfig``: the key from the environment, or for Azure with ``entra`` a callback that
70
+ fetches a fresh Entra token from ``az`` whenever the runtime asks."""
71
+ if self.provider is None:
72
+ return None
73
+ config: dict[str, Any] = {"type": self.provider, "base_url": self.base_url}
74
+ if self.entra:
75
+ config["bearer_token_provider"] = lambda _args: entra_token()
76
+ else:
77
+ key = os.environ.get(self.api_key_env, "").strip()
78
+ if not key:
79
+ raise RuntimeError(
80
+ f"The copilot runtime is set to use {self.provider} at {self.base_url}, but {self.api_key_env} "
81
+ "isn't set. Put the provider's API key in that variable (never in config.toml)."
82
+ )
83
+ config["api_key"] = key
84
+ if self.wire_api:
85
+ config["wire_api"] = self.wire_api
86
+ if self.provider == "azure" and self.azure_api_version:
87
+ config["azure"] = {"api_version": self.azure_api_version}
88
+ return config
89
+
90
+ def billed_to(self) -> str:
91
+ return f"{self.provider}:{urlsplit(self.base_url or '').hostname or self.base_url}" if self.byok else "copilot"
92
+
93
+
94
+ def entra_token() -> str:
95
+ """A bearer token for Azure OpenAI from a signed-in ``az``. Asked for on demand; az caches and refreshes."""
96
+ out, why = quiet_output(
97
+ ["az", "account", "get-access-token", "--resource", COGNITIVE_SERVICES, "--query", "accessToken", "-o", "tsv"],
98
+ with_failure=True,
99
+ )
100
+ if not out or not out.strip():
101
+ first = why.splitlines()[0][:160] if why else "not signed in"
102
+ raise RuntimeError(f"az has no token for Azure OpenAI ({first}); run az login")
103
+ return out.strip()
104
+
105
+
106
+ class CopilotRuntime:
107
+ name = "copilot"
108
+
109
+ def __init__(self, options: Any) -> None:
110
+ self.options: CopilotOptions = options if isinstance(options, CopilotOptions) else CopilotOptions()
111
+ self._client: Any = None
112
+ self._lock: asyncio.Lock | None = None
113
+ self._sessions: list[CopilotSession] = []
114
+
115
+ @property
116
+ def model(self) -> str | None:
117
+ return self.options.model # None for GitHub Copilot: the service picks its default
118
+
119
+ def describe(self) -> str:
120
+ o = self.options
121
+ return f"Copilot SDK, {o.provider} at {o.base_url} ({o.model})" if o.byok else "Copilot SDK, GitHub Copilot"
122
+
123
+ async def _ensure_client(self) -> Any:
124
+ from copilot import CopilotClient
125
+
126
+ if self._lock is None:
127
+ self._lock = asyncio.Lock()
128
+ async with self._lock:
129
+ if self._client is None:
130
+ # With a provider of our own, the runtime must not fall back to the Copilot CLI's GitHub sign-in.
131
+ client = CopilotClient(use_logged_in_user=False) if self.options.byok else CopilotClient()
132
+ await client.start()
133
+ self._client = client
134
+ return self._client
135
+
136
+ def session_options(self, conversation: Conversation) -> dict[str, Any]:
137
+ from copilot.generated.rpc import PermissionDecisionUserNotAvailable
138
+
139
+ tools = [_define(spec) for spec in conversation.tools]
140
+ options: dict[str, Any] = {
141
+ "tools": tools,
142
+ "available_tools": [t.name for t in tools],
143
+ "on_permission_request": lambda _req, _ctx: PermissionDecisionUserNotAvailable(),
144
+ "client_name": "readthrough",
145
+ "working_directory": conversation.working_directory,
146
+ "enable_skills": False,
147
+ "streaming": True,
148
+ "system_message": {"mode": "append", "content": conversation.system},
149
+ }
150
+ provider = self.options.provider_config()
151
+ if provider is not None:
152
+ options["provider"] = provider
153
+ model = conversation.model or self.options.model
154
+ if model:
155
+ options["model"] = model
156
+ return options
157
+
158
+ async def open(self, conversation: Conversation) -> CopilotSession:
159
+ client = await self._ensure_client()
160
+ options = self.session_options(conversation)
161
+ session_id = str(uuid.uuid5(uuid.NAMESPACE_URL, conversation.key))
162
+ exists = conversation.resume and _session_exists(session_id)
163
+ sdk_session, fresh = await open_study_session(client, session_id, options, resume=exists)
164
+ session = CopilotSession(sdk_session, fresh, self.options.billed_to())
165
+ self._sessions.append(session)
166
+ return session
167
+
168
+ async def stop(self) -> None:
169
+ for session in self._sessions:
170
+ await session.close()
171
+ self._sessions.clear()
172
+ if self._client is not None:
173
+ await self._client.stop()
174
+ self._client = None
175
+
176
+
177
+ class CopilotSession:
178
+ def __init__(self, sdk_session: Any, fresh: bool, billed_to: str) -> None:
179
+ self.sdk = sdk_session
180
+ self._fresh = fresh
181
+ self.billed_to = billed_to
182
+ self._closed = False
183
+
184
+ @property
185
+ def fresh(self) -> bool:
186
+ return self._fresh
187
+
188
+ async def send(self, prompt: str) -> AsyncIterator[Event]:
189
+ """Forward the SDK's event stream as runtime events. Tool handlers run inside the SDK's dispatch."""
190
+ loop = asyncio.get_running_loop()
191
+ queue: asyncio.Queue[Event | None] = asyncio.Queue()
192
+ parts: list[str] = []
193
+
194
+ def put(event: Event | None) -> None:
195
+ loop.call_soon_threadsafe(queue.put_nowait, event)
196
+
197
+ def on_event(event: Any) -> None:
198
+ kind = getattr(event.type, "value", str(event.type))
199
+ data = event.data
200
+ if kind == "assistant.usage":
201
+ put(Event("usage", usage=_usage(data, self.billed_to)))
202
+ elif kind == "assistant.message_delta":
203
+ delta = getattr(data, "delta_content", None) or ""
204
+ parts.append(delta)
205
+ put(Event("text", text=delta))
206
+ elif kind == "assistant.message" and parts and not parts[-1].endswith("\n"):
207
+ parts.append("\n\n") # separate the text before and after a tool call
208
+ put(Event("text", text="\n\n"))
209
+ elif kind == "tool.execution_start":
210
+ put(Event("tool", name=getattr(data, "tool_name", "?")))
211
+ elif kind == "session.error":
212
+ put(Event("error", text=getattr(data, "message", None) or "the model runtime reported an error"))
213
+ put(None)
214
+ elif kind == "session.idle":
215
+ put(Event("done", text="".join(parts)))
216
+ put(None)
217
+
218
+ unsubscribe = self.sdk.on(on_event)
219
+ try:
220
+ await self.sdk.send(prompt)
221
+ timeout = default_tuning().study.turn_timeout_seconds
222
+ while True:
223
+ event = await asyncio.wait_for(queue.get(), timeout=timeout)
224
+ if event is None:
225
+ return
226
+ yield event
227
+ finally:
228
+ unsubscribe()
229
+
230
+ async def close(self) -> None:
231
+ if not self._closed:
232
+ self._closed = True
233
+ await self.sdk.disconnect()
234
+
235
+
236
+ def _define(spec: ToolSpec) -> Any:
237
+ """A readthrough tool as the SDK wants it: a pydantic model for the arguments and an async handler."""
238
+ from copilot import define_tool
239
+ from pydantic import create_model
240
+
241
+ fields: dict[str, Any] = {}
242
+ required = set(spec.schema.get("required") or [])
243
+ for name, prop in (spec.schema.get("properties") or {}).items():
244
+ kind = _python_type(prop)
245
+ fields[name] = (kind, ...) if name in required else (kind | None, prop.get("default"))
246
+ params_model = create_model(f"{spec.name}_params", **fields)
247
+ handler = spec.handler
248
+
249
+ async def tool(params: Any, invocation: Any) -> str: # noqa: ARG001 - the SDK passes it
250
+ return await handler(params.model_dump(exclude_none=True))
251
+
252
+ return define_tool(
253
+ spec.name, description=spec.description, handler=tool, params_type=params_model, skip_permission=True,
254
+ is_terminal=spec.terminal,
255
+ ) # fmt: skip
256
+
257
+
258
+ def _python_type(prop: dict[str, Any]) -> Any:
259
+ kind = prop.get("type")
260
+ if kind == "array":
261
+ item: Any = _python_type(prop.get("items") or {"type": "string"})
262
+ return list.__class_getitem__(item)
263
+ return {"string": str, "integer": int, "number": float, "boolean": bool}.get(kind, str)
264
+
265
+
266
+ def _usage(data: Any, billed_to: str) -> Usage:
267
+ copilot_usage = getattr(data, "copilot_usage", None)
268
+ byok = bool(getattr(data, "is_byok", False))
269
+ return Usage(
270
+ call_id=getattr(data, "api_call_id", None) or getattr(data, "provider_call_id", None),
271
+ model=getattr(data, "model", None) or "?",
272
+ input_tokens=getattr(data, "input_tokens", None),
273
+ output_tokens=getattr(data, "output_tokens", None),
274
+ cache_read_tokens=getattr(data, "cache_read_tokens", None),
275
+ cache_write_tokens=getattr(data, "cache_write_tokens", None),
276
+ reasoning_tokens=getattr(data, "reasoning_tokens", None),
277
+ # The premium-request multiplier is Copilot's unit; the runtime sends 0 for a provider of your own,
278
+ # which would read as "free", so it is left out there.
279
+ multiplier=None if byok else getattr(data, "cost", None),
280
+ nano_aiu=getattr(copilot_usage, "total_nano_aiu", None) if copilot_usage is not None else None,
281
+ billed_to=billed_to,
282
+ )
283
+
284
+
285
+ def _session_exists(session_id: str) -> bool:
286
+ from readthrough.agents import Copilot
287
+
288
+ return Copilot().session_info(session_id).exists # the SDK shares the Copilot CLI's session store
289
+
290
+
291
+ async def open_study_session(
292
+ client: Any, session_id: str, options: dict[str, Any], *, resume: bool
293
+ ) -> tuple[Any, bool]:
294
+ """Resume the conversation, or start one. Returns (session, whether it's new).
295
+
296
+ A session whose history the CLI can't read back (say its folder was half-deleted) would otherwise break
297
+ the Study tab for that PR for good. Fall back to a fresh session: the study log, not the chat history,
298
+ is the record, and a new session is handed the brief with the log at its end.
299
+ """
300
+ if resume:
301
+ try:
302
+ return await client.resume_session(session_id, **options), False
303
+ except Exception as exc: # noqa: BLE001 - SDK errors have no common type
304
+ log.warning("Couldn't resume study session %s (%s); starting a fresh one", session_id, str(exc)[:200])
305
+ session_id = str(uuid.uuid4())
306
+ return await client.create_session(session_id=session_id, **options), True
307
+
308
+
309
+ RUNTIMES.add(
310
+ "copilot",
311
+ "the Copilot SDK: GitHub Copilot through its sign-in, or a model provider of your own (needs [study])",
312
+ options=CopilotOptions,
313
+ )(CopilotRuntime)
@@ -0,0 +1,307 @@
1
+ """OpenAI's Responses API as a runtime: OpenAI itself, or Azure OpenAI / Foundry (with a key or an Entra sign-in).
2
+
3
+ The same wire format serves three hosts, so one runtime does. The conversation is continued through
4
+ ``previous_response_id``, which the API keeps server-side (``store`` on), so each call carries only what is
5
+ new. Tool calls come back as ``function_call`` items; their outputs go back as ``function_call_output``
6
+ items; the loop here repeats until the model stops, a terminal tool is called, or the call cap is hit.
7
+
8
+ On Azure, ``model`` is the deployment name, which may differ from the model's; an Entra token is for the
9
+ ``https://ai.azure.com/.default`` audience and comes from the signed-in ``az`` when ``entra`` is set.
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, quiet_output, 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
+ AZURE_AI_AUDIENCE = "https://ai.azure.com"
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class OpenAIOptions:
48
+ model: str = "gpt-5.5" # on Azure, the deployment name
49
+ base_url: str = "https://api.openai.com/v1" # or https://<resource>.openai.azure.com/openai/v1
50
+ api_key_env: str = "OPENAI_API_KEY"
51
+ # Azure only: an Entra token from `az` instead of a key. Many Azure OpenAI resources have key auth disabled.
52
+ entra: bool = False
53
+ max_output_tokens: int = 4096
54
+ max_calls_per_turn: int = 12
55
+
56
+ @property
57
+ def azure(self) -> bool:
58
+ host = urlsplit(self.base_url).hostname or ""
59
+ return host.endswith((".openai.azure.com", ".services.ai.azure.com", ".cognitiveservices.azure.com"))
60
+
61
+ def __post_init__(self) -> None:
62
+ if self.entra and not self.azure:
63
+ raise ValueError("entra sign-in applies to Azure endpoints only")
64
+
65
+ def can_run(self) -> tuple[bool, str]:
66
+ if self.entra:
67
+ return True, ""
68
+ if not os.environ.get(self.api_key_env, "").strip():
69
+ return False, f"the openai runtime needs an API key in {self.api_key_env}"
70
+ return True, ""
71
+
72
+ def key(self) -> Secret:
73
+ value = os.environ.get(self.api_key_env, "").strip()
74
+ if not value:
75
+ raise RuntimeError(f"The openai runtime needs an API key in {self.api_key_env} (never in config.toml).")
76
+ return remember(Secret(value))
77
+
78
+ def billed_to(self) -> str:
79
+ return f"{'azure' if self.azure else 'openai'}:{urlsplit(self.base_url).hostname or self.base_url}"
80
+
81
+
82
+ def entra_token() -> Secret:
83
+ """A bearer token for the Azure AI data plane from a signed-in ``az``. Asked for per call; az caches it."""
84
+ out, why = quiet_output(
85
+ ["az", "account", "get-access-token", "--resource", AZURE_AI_AUDIENCE, "--query", "accessToken", "-o", "tsv"],
86
+ with_failure=True,
87
+ )
88
+ if not out or not out.strip():
89
+ first = why.splitlines()[0][:160] if why else "not signed in"
90
+ raise RuntimeError(f"az has no token for Azure AI ({first}); run az login")
91
+ return remember(Secret(out.strip()))
92
+
93
+
94
+ class OpenAIRuntime:
95
+ name = "openai"
96
+
97
+ def __init__(self, options: Any) -> None:
98
+ self.options: OpenAIOptions = options if isinstance(options, OpenAIOptions) else OpenAIOptions()
99
+ self._conversations: dict[str, OpenAISession] = {}
100
+
101
+ @property
102
+ def model(self) -> str | None:
103
+ return self.options.model
104
+
105
+ def describe(self) -> str:
106
+ o = self.options
107
+ where = "Azure OpenAI" if o.azure else "OpenAI"
108
+ auth = ", Entra sign-in" if o.entra else ""
109
+ return f"{where} Responses API at {o.base_url} ({o.model}{auth})"
110
+
111
+ async def open(self, conversation: Conversation) -> OpenAISession:
112
+ if conversation.resume and conversation.key in self._conversations:
113
+ return self._conversations[conversation.key]
114
+ session = OpenAISession(self.options, conversation)
115
+ self._conversations[conversation.key] = session
116
+ return session
117
+
118
+ async def stop(self) -> None:
119
+ self._conversations.clear()
120
+
121
+
122
+ class OpenAISession:
123
+ def __init__(self, options: OpenAIOptions, conversation: Conversation) -> None:
124
+ self.options = options
125
+ self.conversation = conversation
126
+ self.model = conversation.model or options.model
127
+ self.previous_response_id: str | None = None
128
+ self._tools = {t.name: t for t in conversation.tools}
129
+ self._fresh = True
130
+
131
+ @property
132
+ def fresh(self) -> bool:
133
+ return self._fresh
134
+
135
+ async def close(self) -> None:
136
+ return None
137
+
138
+ def _request_body(self, items: list[dict[str, Any]]) -> dict[str, Any]:
139
+ body: dict[str, Any] = {
140
+ "model": self.model,
141
+ "instructions": self.conversation.system,
142
+ "input": items,
143
+ "tools": [
144
+ {
145
+ "type": "function",
146
+ "name": t.name,
147
+ "description": t.description,
148
+ "parameters": tool_schema(t),
149
+ "strict": False,
150
+ }
151
+ for t in self.conversation.tools
152
+ ],
153
+ "max_output_tokens": self.options.max_output_tokens,
154
+ "store": True,
155
+ "stream": True,
156
+ }
157
+ if self.previous_response_id:
158
+ body["previous_response_id"] = self.previous_response_id
159
+ return body
160
+
161
+ async def send(self, prompt: str) -> AsyncIterator[Event]:
162
+ self._fresh = False
163
+ items: list[dict[str, Any]] = [{"role": "user", "content": [{"type": "input_text", "text": prompt}]}]
164
+ reply: list[str] = []
165
+ for _ in range(self.options.max_calls_per_turn):
166
+ try:
167
+ text, calls, used, response_id = await asyncio.to_thread(self._call, items)
168
+ except RuntimeError as exc:
169
+ yield Event("error", text=str(exc))
170
+ return
171
+ self.previous_response_id = response_id or self.previous_response_id
172
+ if text:
173
+ reply.append(text)
174
+ yield Event("text", text=text)
175
+ yield Event("usage", usage=used)
176
+ if not calls:
177
+ yield Event("done", text="".join(reply))
178
+ return
179
+ items = []
180
+ terminal = False
181
+ for call in calls:
182
+ spec = self._tools.get(call["name"])
183
+ yield Event("tool", name=call["name"])
184
+ if spec is None:
185
+ output = f"Unknown tool {call['name']!r}."
186
+ else:
187
+ try:
188
+ output = await spec.handler(check_arguments(spec, parse_arguments(call["arguments"])))
189
+ except Exception as exc: # noqa: BLE001 - the model gets the error as a result, like any tool runner
190
+ output = f"Tool failed: {exc}"
191
+ terminal = terminal or spec.terminal
192
+ items.append({"type": "function_call_output", "call_id": call["call_id"], "output": output})
193
+ if terminal:
194
+ # The outputs still have to reach the conversation, or the next turn would start mid-call.
195
+ try:
196
+ *_, settled_id = await asyncio.to_thread(self._call, items, settle_only=True)
197
+ self.previous_response_id = settled_id or self.previous_response_id
198
+ except RuntimeError as exc:
199
+ log.warning("Couldn't settle the tool outputs after a terminal tool: %s", exc)
200
+ yield Event("done", text="".join(reply))
201
+ return
202
+ if reply and not reply[-1].endswith("\n"):
203
+ reply.append("\n\n")
204
+ yield Event("error", text=f"the model made more than {self.options.max_calls_per_turn} calls in one turn")
205
+
206
+ def _call(
207
+ self, items: list[dict[str, Any]], *, settle_only: bool = False
208
+ ) -> tuple[str, list[dict[str, Any]], Usage, str | None]:
209
+ """One streamed Responses call. Returns (text, function calls, usage, response id)."""
210
+ body = self._request_body(items)
211
+ if settle_only:
212
+ body["max_output_tokens"] = 16
213
+ body["tool_choice"] = "none"
214
+ req = urllib.request.Request( # noqa: S310 - an https API URL from config
215
+ self.options.base_url.rstrip("/") + "/responses",
216
+ data=json.dumps(body).encode("utf-8"),
217
+ method="POST",
218
+ headers={"content-type": "application/json", "accept": "text/event-stream", "user-agent": "readthrough"},
219
+ )
220
+ if self.options.entra:
221
+ req.add_unredirected_header("Authorization", f"Bearer {entra_token().reveal()}")
222
+ elif self.options.azure:
223
+ req.add_unredirected_header("api-key", self.options.key().reveal())
224
+ else:
225
+ req.add_unredirected_header("Authorization", f"Bearer {self.options.key().reveal()}")
226
+ timeout = default_tuning().study.turn_timeout_seconds
227
+
228
+ def once() -> tuple[str, list[dict[str, Any]], Usage, str | None]:
229
+ try:
230
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
231
+ return self._read_stream(resp)
232
+ except urllib.error.HTTPError as exc:
233
+ text = redact(exc.read().decode("utf-8", "replace"))
234
+ message = f"the model endpoint refused the call: {_error_message(text) or f'HTTP {exc.code}'}"
235
+ if exc.code in RETRY_STATUSES:
236
+ raise Retryable(message, retry_after=exc.headers.get("retry-after")) from exc
237
+ raise RuntimeError(message) from exc
238
+ except urllib.error.URLError as exc:
239
+ raise Retryable(f"couldn't reach {self.options.base_url}: {exc.reason}") from exc
240
+
241
+ try:
242
+ return with_retries("the model endpoint", once)
243
+ except Retryable as exc:
244
+ raise RuntimeError(f"{exc} (gave up after {RETRY_ATTEMPTS} attempts)") from exc
245
+
246
+ def _read_stream(self, resp: Any) -> tuple[str, list[dict[str, Any]], Usage, str | None]:
247
+ text: list[str] = []
248
+ calls: dict[str, dict[str, Any]] = {} # item id -> function call being assembled
249
+ arguments: dict[str, list[str]] = {}
250
+ final: dict[str, Any] | None = None
251
+ for raw in resp:
252
+ line = raw.decode("utf-8", "replace").rstrip("\r\n")
253
+ if not line.startswith("data:"):
254
+ continue
255
+ payload = line[5:].strip()
256
+ if payload == "[DONE]":
257
+ break
258
+ event = json.loads(payload)
259
+ kind = event.get("type")
260
+ if kind == "response.output_text.delta":
261
+ text.append(event.get("delta") or "")
262
+ elif kind == "response.output_item.added":
263
+ item = event.get("item") or {}
264
+ if item.get("type") == "function_call":
265
+ calls[item["id"]] = {"call_id": item.get("call_id"), "name": item.get("name"), "arguments": ""}
266
+ arguments[item["id"]] = [item.get("arguments") or ""]
267
+ elif kind == "response.function_call_arguments.delta":
268
+ arguments.setdefault(event.get("item_id", ""), []).append(event.get("delta") or "")
269
+ elif kind == "response.completed":
270
+ final = event.get("response") or {}
271
+ elif kind in ("response.failed", "error"):
272
+ error = (event.get("response") or {}).get("error") or event
273
+ raise RuntimeError(
274
+ f"the model reported an error mid-stream: {error.get('message') or error.get('code')}"
275
+ )
276
+ for item_id, call in calls.items():
277
+ call["arguments"] = "".join(arguments.get(item_id) or [])
278
+ usage = (final or {}).get("usage") or {}
279
+ used = Usage(
280
+ call_id=(final or {}).get("id"),
281
+ model=(final or {}).get("model") or self.model,
282
+ input_tokens=usage.get("input_tokens"),
283
+ output_tokens=usage.get("output_tokens"),
284
+ cache_read_tokens=(usage.get("input_tokens_details") or {}).get("cached_tokens"),
285
+ cache_write_tokens=(usage.get("input_tokens_details") or {}).get("cache_write_tokens"),
286
+ reasoning_tokens=(usage.get("output_tokens_details") or {}).get("reasoning_tokens"),
287
+ billed_to=self.options.billed_to(),
288
+ )
289
+ return "".join(text), list(calls.values()), used, (final or {}).get("id")
290
+
291
+
292
+ def _error_message(text: str) -> str | None:
293
+ try:
294
+ data = json.loads(text)
295
+ except ValueError:
296
+ return text.strip()[:200] or None
297
+ error = data.get("error") if isinstance(data, dict) else None
298
+ if isinstance(error, dict):
299
+ return f"{error.get('code') or error.get('type') or 'error'}: {error.get('message') or ''}".strip(": ")
300
+ return None
301
+
302
+
303
+ RUNTIMES.add(
304
+ "openai",
305
+ "OpenAI's Responses API: OpenAI, or Azure OpenAI / Foundry with a key or an Entra sign-in",
306
+ options=OpenAIOptions,
307
+ )(OpenAIRuntime)