python2rust 0.1.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.
- python2rust/__init__.py +8 -0
- python2rust/__main__.py +5 -0
- python2rust/_core.py +44 -0
- python2rust/agent/__init__.py +0 -0
- python2rust/agent/agents.py +333 -0
- python2rust/agent/apply.py +516 -0
- python2rust/agent/finish.py +295 -0
- python2rust/agent/fixers.py +229 -0
- python2rust/agent/loop.py +441 -0
- python2rust/agent/patches.py +1165 -0
- python2rust/agent/port.py +579 -0
- python2rust/agent/prompts/judge_v2.md +96 -0
- python2rust/agent/review.py +34 -0
- python2rust/agent/rustlex.py +232 -0
- python2rust/cli/__init__.py +0 -0
- python2rust/cli/doctor.py +62 -0
- python2rust/cli/inputs.py +105 -0
- python2rust/cli/main.py +1162 -0
- python2rust/cli/ops.py +642 -0
- python2rust/cli/workflow.py +178 -0
- python2rust/core/__init__.py +38 -0
- python2rust/core/config.py +263 -0
- python2rust/core/constructs.py +124 -0
- python2rust/core/diagnostics.py +280 -0
- python2rust/core/emit/__init__.py +5 -0
- python2rust/core/emit/crates.py +51 -0
- python2rust/core/emit/render.py +561 -0
- python2rust/core/emit/schema.py +168 -0
- python2rust/core/emit/translate.py +304 -0
- python2rust/core/frontend/__init__.py +1 -0
- python2rust/core/frontend/module.py +896 -0
- python2rust/core/frontend/names.py +129 -0
- python2rust/core/frontend/project.py +277 -0
- python2rust/core/frontend/project_imports.py +173 -0
- python2rust/core/frontend/symbols.py +132 -0
- python2rust/core/frontend/walrus.py +59 -0
- python2rust/core/ir/__init__.py +1 -0
- python2rust/core/ir/nodes.py +675 -0
- python2rust/core/ir/rtypes.py +122 -0
- python2rust/core/ir/types.py +326 -0
- python2rust/core/lower/__init__.py +1 -0
- python2rust/core/lower/calls.py +1125 -0
- python2rust/core/lower/context.py +223 -0
- python2rust/core/lower/exceptions.py +317 -0
- python2rust/core/lower/exprs.py +845 -0
- python2rust/core/lower/fstrings.py +141 -0
- python2rust/core/lower/funcs.py +276 -0
- python2rust/core/lower/lowerer.py +366 -0
- python2rust/core/lower/modelcalls.py +195 -0
- python2rust/core/lower/models.py +645 -0
- python2rust/core/lower/stmts.py +722 -0
- python2rust/core/lower/testing.py +601 -0
- python2rust/core/lower/validation.py +253 -0
- python2rust/core/passes/__init__.py +1 -0
- python2rust/core/passes/aliasing.py +311 -0
- python2rust/core/passes/analysis.py +207 -0
- python2rust/core/passes/devirt.py +329 -0
- python2rust/core/passes/ownership.py +259 -0
- python2rust/core/passes/raises.py +275 -0
- python2rust/core/rt_lib.rs +2071 -0
- python2rust/data/README.md +81 -0
- python2rust/data/py2many_builtins.toml +4744 -0
- python2rust/errors.py +28 -0
- python2rust/py.typed +0 -0
- python2rust/report/__init__.py +0 -0
- python2rust/report/constructs.py +31 -0
- python2rust/report/contract.py +688 -0
- python2rust/report/corpus.py +323 -0
- python2rust/report/explain.py +168 -0
- python2rust/report/schemas.py +914 -0
- python2rust/server/__init__.py +0 -0
- python2rust/server/mcp_server.py +289 -0
- python2rust/server/mcp_workflow.py +100 -0
- python2rust/skill/SKILL.md +214 -0
- python2rust/verify/__init__.py +0 -0
- python2rust/verify/check.py +1135 -0
- python2rust/verify/equiv/__init__.py +1264 -0
- python2rust/verify/equiv/compare.py +455 -0
- python2rust/verify/equiv/harness.py +505 -0
- python2rust/verify/equiv/judge.py +358 -0
- python2rust/verify/equiv/procs.py +255 -0
- python2rust/verify/equiv/runner.py +248 -0
- python2rust/verify/equiv/types.py +543 -0
- python2rust/verify/keystore.py +76 -0
- python2rust/verify/ladder.py +396 -0
- python2rust/verify/sandbox.py +370 -0
- python2rust/verify/testrun.py +280 -0
- python2rust/workflow/__init__.py +0 -0
- python2rust/workflow/brief.py +312 -0
- python2rust/workflow/interview.py +366 -0
- python2rust/workflow/layout.py +103 -0
- python2rust/workflow/planner.py +409 -0
- python2rust/workflow/project.py +134 -0
- python2rust/workflow/schemas.py +265 -0
- python2rust/workflow/state.py +392 -0
- python2rust/workflow/staticscan.py +209 -0
- python2rust-0.1.0.dist-info/METADATA +395 -0
- python2rust-0.1.0.dist-info/RECORD +102 -0
- python2rust-0.1.0.dist-info/WHEEL +4 -0
- python2rust-0.1.0.dist-info/entry_points.txt +4 -0
- python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
- python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
python2rust/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""python2rust: a typed-Python to Rust transpiler built to be driven by AI agents.
|
|
2
|
+
|
|
3
|
+
Importing this package is deliberately cheap. The translator core (`python2rust.core`)
|
|
4
|
+
and the optional MCP SDK are imported lazily by the commands that need them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = ["__version__"]
|
python2rust/__main__.py
ADDED
python2rust/_core.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Lazy access to the translator core.
|
|
2
|
+
|
|
3
|
+
The CLI and the MCP server only ever talk to the core through `get_core()`. A missing
|
|
4
|
+
`python2rust.core` is a hard error (exit 3): silently translating with a placeholder would produce
|
|
5
|
+
output that looks like a translation and is not. There is no stand-in in the package; tests that
|
|
6
|
+
need one install it with `set_core()`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
from types import ModuleType
|
|
13
|
+
|
|
14
|
+
from python2rust.errors import InternalError
|
|
15
|
+
|
|
16
|
+
_core: ModuleType | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_core() -> ModuleType:
|
|
20
|
+
"""Return `python2rust.core`; raise InternalError(kind="missing_core") if it is absent."""
|
|
21
|
+
global _core
|
|
22
|
+
if _core is None:
|
|
23
|
+
try:
|
|
24
|
+
_core = importlib.import_module("python2rust.core")
|
|
25
|
+
except ModuleNotFoundError as exc:
|
|
26
|
+
if exc.name != "python2rust.core":
|
|
27
|
+
raise # a real import error inside the core must not be hidden
|
|
28
|
+
raise InternalError(
|
|
29
|
+
"the translator core (python2rust.core) is not installed, so there is "
|
|
30
|
+
"nothing to translate with; reinstall python2rust from a complete wheel",
|
|
31
|
+
kind="missing_core",
|
|
32
|
+
) from None
|
|
33
|
+
return _core
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def set_core(module: ModuleType | None) -> None:
|
|
37
|
+
"""Override the core (tests); `None` resets to automatic discovery."""
|
|
38
|
+
global _core
|
|
39
|
+
_core = module
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def core_name() -> str:
|
|
43
|
+
"""Name of the active core module; raises like get_core()."""
|
|
44
|
+
return get_core().__name__
|
|
File without changes
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""Agent backends shared by `port` (repairing Rust) and the equivalence judge.
|
|
2
|
+
|
|
3
|
+
A backend turns one request into text. Nothing leaves the machine unless the user chose a backend
|
|
4
|
+
explicitly (`--agent cmd|anthropic|openai|azure`); the default is no backend. Standard library only:
|
|
5
|
+
|
|
6
|
+
* `cmd`: any command (`--agent-cmd "claude -p"`). It receives ONE JSON object on stdin
|
|
7
|
+
(`{"kind", "task", "system", "user", "prompt"}`; `prompt` is system + user as plain text, which is
|
|
8
|
+
what chat CLIs read) and prints the answer on stdout: JSON for the documented contracts, or free
|
|
9
|
+
text containing a fenced block, which `parse_*` tolerate.
|
|
10
|
+
* `anthropic`: the Messages API (`ANTHROPIC_API_KEY`, `--base-url` / `ANTHROPIC_BASE_URL`).
|
|
11
|
+
* `openai`: any OpenAI-compatible endpoint, chat completions or responses (`OPENAI_API_KEY`,
|
|
12
|
+
`--base-url` / `OPENAI_BASE_URL`, `--openai-api chat|responses`).
|
|
13
|
+
* `azure`: an Azure-style OpenAI deployment; `--base-url` is the full endpoint URL
|
|
14
|
+
(`AZURE_OPENAI_API_KEY` is sent as `api-key`).
|
|
15
|
+
|
|
16
|
+
Keys come from the environment only and are never logged or put in errors. Prompts are printed only
|
|
17
|
+
with `--verbose`. Timeouts and bounded retries (429 / 5xx / network) apply to the HTTP backends.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shlex
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
import urllib.error
|
|
30
|
+
import urllib.request
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Any, Protocol
|
|
33
|
+
|
|
34
|
+
from python2rust.errors import UsageError
|
|
35
|
+
|
|
36
|
+
BACKENDS = ("none", "cmd", "anthropic", "openai", "azure")
|
|
37
|
+
ANTHROPIC_VERSION = "2023-06-01"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Completion:
|
|
42
|
+
text: str
|
|
43
|
+
tokens: int = 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Backend(Protocol):
|
|
47
|
+
name: str
|
|
48
|
+
|
|
49
|
+
def complete(
|
|
50
|
+
self,
|
|
51
|
+
kind: str,
|
|
52
|
+
payload: dict[str, Any],
|
|
53
|
+
system: str,
|
|
54
|
+
user: str,
|
|
55
|
+
*,
|
|
56
|
+
temperature: float = 0.0,
|
|
57
|
+
max_tokens: int = 4096,
|
|
58
|
+
) -> Completion: ...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class BackendError(Exception):
|
|
62
|
+
"""A backend call failed (after retries); the message never contains a key."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# --- output parsing -----------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
_FENCE = re.compile(r"```[A-Za-z0-9_+-]*[ \t]*\n(.*?)```", re.S)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def extract_code(text: str) -> str:
|
|
71
|
+
"""The first fenced code block of `text`, else `text` itself (stripped)."""
|
|
72
|
+
m = _FENCE.search(text)
|
|
73
|
+
return (m.group(1) if m else text).strip("\n")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def extract_json_object(text: str) -> dict[str, Any] | None:
|
|
77
|
+
"""The first JSON object in `text` (bare, fenced, or embedded in prose), else None."""
|
|
78
|
+
candidates = [text.strip(), *(m.group(1) for m in _FENCE.finditer(text))]
|
|
79
|
+
for cand in candidates:
|
|
80
|
+
try:
|
|
81
|
+
data = json.loads(cand)
|
|
82
|
+
except ValueError:
|
|
83
|
+
continue
|
|
84
|
+
if isinstance(data, dict):
|
|
85
|
+
return data
|
|
86
|
+
dec = json.JSONDecoder()
|
|
87
|
+
for m in re.finditer(r"\{", text):
|
|
88
|
+
try:
|
|
89
|
+
data, _ = dec.raw_decode(text[m.start() :])
|
|
90
|
+
except ValueError:
|
|
91
|
+
continue
|
|
92
|
+
if isinstance(data, dict):
|
|
93
|
+
return data
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def parse_patch(text: str) -> str | None:
|
|
98
|
+
"""The replacement function body from an agent answer: JSON `{"replacement"}`, else a fenced
|
|
99
|
+
block, else the whole text. None when the answer is empty."""
|
|
100
|
+
obj = extract_json_object(text)
|
|
101
|
+
if obj is not None and isinstance(obj.get("replacement"), str):
|
|
102
|
+
body = obj["replacement"]
|
|
103
|
+
else:
|
|
104
|
+
body = extract_code(text)
|
|
105
|
+
body = extract_code(body) if body.lstrip().startswith("```") else body
|
|
106
|
+
return body.strip("\n") if body.strip() else None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# --- backends -----------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class CmdBackend:
|
|
113
|
+
name = "cmd"
|
|
114
|
+
|
|
115
|
+
def __init__(self, command: str, timeout: float = 600, verbose: bool = False):
|
|
116
|
+
self.argv = shlex.split(command)
|
|
117
|
+
if not self.argv:
|
|
118
|
+
raise UsageError("--agent-cmd is empty")
|
|
119
|
+
self.timeout, self.verbose = timeout, verbose
|
|
120
|
+
|
|
121
|
+
def complete(
|
|
122
|
+
self,
|
|
123
|
+
kind: str,
|
|
124
|
+
payload: dict[str, Any],
|
|
125
|
+
system: str,
|
|
126
|
+
user: str,
|
|
127
|
+
*,
|
|
128
|
+
temperature: float = 0.0,
|
|
129
|
+
max_tokens: int = 4096,
|
|
130
|
+
) -> Completion:
|
|
131
|
+
body = {
|
|
132
|
+
"schema_version": 1,
|
|
133
|
+
"kind": kind,
|
|
134
|
+
"task": payload,
|
|
135
|
+
"system": system,
|
|
136
|
+
"user": user,
|
|
137
|
+
"prompt": f"{system}\n\n{user}",
|
|
138
|
+
}
|
|
139
|
+
if self.verbose:
|
|
140
|
+
print(
|
|
141
|
+
f"[agent cmd] {' '.join(self.argv)} <- {kind} ({len(user)} chars)", file=sys.stderr
|
|
142
|
+
)
|
|
143
|
+
try:
|
|
144
|
+
proc = subprocess.run(
|
|
145
|
+
self.argv,
|
|
146
|
+
input=json.dumps(body),
|
|
147
|
+
capture_output=True,
|
|
148
|
+
text=True,
|
|
149
|
+
timeout=self.timeout,
|
|
150
|
+
)
|
|
151
|
+
except FileNotFoundError as exc:
|
|
152
|
+
raise BackendError(f"cannot run {self.argv[0]}: {exc}") from exc
|
|
153
|
+
except subprocess.TimeoutExpired:
|
|
154
|
+
raise BackendError(f"{self.argv[0]} timed out after {self.timeout:g}s") from None
|
|
155
|
+
if proc.returncode != 0:
|
|
156
|
+
tail = " ".join(proc.stderr.strip().splitlines()[-3:])
|
|
157
|
+
raise BackendError(f"{self.argv[0]} exited {proc.returncode}: {tail}")
|
|
158
|
+
obj = extract_json_object(proc.stdout)
|
|
159
|
+
tokens = int(obj["tokens"]) if obj and isinstance(obj.get("tokens"), int) else 0
|
|
160
|
+
return Completion(proc.stdout, tokens)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class HttpBackend:
|
|
164
|
+
"""Anthropic Messages, OpenAI-compatible chat/responses, or an Azure-style deployment."""
|
|
165
|
+
|
|
166
|
+
def __init__(
|
|
167
|
+
self,
|
|
168
|
+
provider: str,
|
|
169
|
+
model: str,
|
|
170
|
+
*,
|
|
171
|
+
base_url: str | None = None,
|
|
172
|
+
openai_api: str = "chat",
|
|
173
|
+
timeout: float = 120,
|
|
174
|
+
retries: int = 3,
|
|
175
|
+
verbose: bool = False,
|
|
176
|
+
sleep: Any = time.sleep,
|
|
177
|
+
):
|
|
178
|
+
if not model:
|
|
179
|
+
raise UsageError(f"--model is required for --agent {provider}")
|
|
180
|
+
self.name, self.provider, self.model = provider, provider, model
|
|
181
|
+
self.api, self.timeout, self.retries, self.verbose, self.sleep = (
|
|
182
|
+
openai_api,
|
|
183
|
+
timeout,
|
|
184
|
+
retries,
|
|
185
|
+
verbose,
|
|
186
|
+
sleep,
|
|
187
|
+
)
|
|
188
|
+
env = {
|
|
189
|
+
"anthropic": (
|
|
190
|
+
"ANTHROPIC_API_KEY",
|
|
191
|
+
"ANTHROPIC_BASE_URL",
|
|
192
|
+
"https://api.anthropic.com/v1",
|
|
193
|
+
),
|
|
194
|
+
"openai": ("OPENAI_API_KEY", "OPENAI_BASE_URL", "https://api.openai.com/v1"),
|
|
195
|
+
"azure": ("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT", ""),
|
|
196
|
+
}[provider]
|
|
197
|
+
self.key = os.environ.get(env[0], "")
|
|
198
|
+
if not self.key:
|
|
199
|
+
raise UsageError(
|
|
200
|
+
f"--agent {provider} needs the API key in the environment variable {env[0]}"
|
|
201
|
+
)
|
|
202
|
+
url = base_url or os.environ.get(env[1]) or env[2]
|
|
203
|
+
if not url:
|
|
204
|
+
raise UsageError(
|
|
205
|
+
"--agent azure needs --base-url (the full endpoint URL of the deployment)"
|
|
206
|
+
)
|
|
207
|
+
if provider == "anthropic":
|
|
208
|
+
url = url.rstrip("/") + "/messages"
|
|
209
|
+
elif provider == "openai":
|
|
210
|
+
url = url.rstrip("/") + (
|
|
211
|
+
"/responses" if openai_api == "responses" else "/chat/completions"
|
|
212
|
+
)
|
|
213
|
+
if not url.startswith(("https://", "http://")):
|
|
214
|
+
raise UsageError(
|
|
215
|
+
"the endpoint URL must start with https:// (or http:// for a local server)"
|
|
216
|
+
)
|
|
217
|
+
self.url = url
|
|
218
|
+
|
|
219
|
+
def _request(
|
|
220
|
+
self, system: str, user: str, temperature: float, max_tokens: int
|
|
221
|
+
) -> urllib.request.Request:
|
|
222
|
+
if self.provider == "anthropic":
|
|
223
|
+
body: dict[str, Any] = {
|
|
224
|
+
"model": self.model, "max_tokens": max_tokens, "temperature": temperature,
|
|
225
|
+
"system": system, "messages": [{"role": "user", "content": user}],
|
|
226
|
+
} # fmt: skip
|
|
227
|
+
headers = {"x-api-key": self.key, "anthropic-version": ANTHROPIC_VERSION}
|
|
228
|
+
else:
|
|
229
|
+
if self.provider == "openai" and self.api == "responses":
|
|
230
|
+
body = {
|
|
231
|
+
"model": self.model,
|
|
232
|
+
"instructions": system,
|
|
233
|
+
"input": user,
|
|
234
|
+
"temperature": temperature,
|
|
235
|
+
"max_output_tokens": max_tokens,
|
|
236
|
+
}
|
|
237
|
+
else:
|
|
238
|
+
body = {
|
|
239
|
+
"model": self.model, "temperature": temperature, "max_tokens": max_tokens,
|
|
240
|
+
"messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
|
|
241
|
+
} # fmt: skip
|
|
242
|
+
headers = (
|
|
243
|
+
{"api-key": self.key}
|
|
244
|
+
if self.provider == "azure"
|
|
245
|
+
else {"Authorization": f"Bearer {self.key}"}
|
|
246
|
+
)
|
|
247
|
+
headers["Content-Type"] = "application/json"
|
|
248
|
+
return urllib.request.Request(self.url, json.dumps(body).encode(), headers, method="POST")
|
|
249
|
+
|
|
250
|
+
def _parse(self, data: dict[str, Any]) -> Completion:
|
|
251
|
+
usage = data.get("usage") or {}
|
|
252
|
+
if self.provider == "anthropic":
|
|
253
|
+
text = "".join(
|
|
254
|
+
b.get("text", "") for b in data.get("content", []) if isinstance(b, dict)
|
|
255
|
+
)
|
|
256
|
+
return Completion(
|
|
257
|
+
text, int(usage.get("input_tokens", 0)) + int(usage.get("output_tokens", 0))
|
|
258
|
+
)
|
|
259
|
+
if self.provider == "openai" and self.api == "responses":
|
|
260
|
+
text = data.get("output_text") or "".join(
|
|
261
|
+
c.get("text", "")
|
|
262
|
+
for item in data.get("output", [])
|
|
263
|
+
if isinstance(item, dict)
|
|
264
|
+
for c in item.get("content", [])
|
|
265
|
+
if isinstance(c, dict)
|
|
266
|
+
)
|
|
267
|
+
return Completion(text, int(usage.get("total_tokens", 0)))
|
|
268
|
+
text = (data.get("choices") or [{}])[0].get("message", {}).get("content") or ""
|
|
269
|
+
return Completion(text, int(usage.get("total_tokens", 0)))
|
|
270
|
+
|
|
271
|
+
def complete(
|
|
272
|
+
self,
|
|
273
|
+
kind: str,
|
|
274
|
+
payload: dict[str, Any],
|
|
275
|
+
system: str,
|
|
276
|
+
user: str,
|
|
277
|
+
*,
|
|
278
|
+
temperature: float = 0.0,
|
|
279
|
+
max_tokens: int = 4096,
|
|
280
|
+
) -> Completion:
|
|
281
|
+
if self.verbose:
|
|
282
|
+
print(
|
|
283
|
+
f"[agent {self.provider}] {self.model} <- {kind}\n{system}\n---\n{user}",
|
|
284
|
+
file=sys.stderr,
|
|
285
|
+
)
|
|
286
|
+
last = "unknown error"
|
|
287
|
+
for attempt in range(self.retries + 1):
|
|
288
|
+
req = self._request(system, user, temperature, max_tokens)
|
|
289
|
+
try:
|
|
290
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
291
|
+
return self._parse(json.loads(resp.read()))
|
|
292
|
+
except urllib.error.HTTPError as exc:
|
|
293
|
+
last = f"HTTP {exc.code}"
|
|
294
|
+
if exc.code not in (408, 409, 429) and exc.code < 500:
|
|
295
|
+
raise BackendError(f"{self.provider} request rejected: {last}") from None
|
|
296
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
|
|
297
|
+
last = type(exc).__name__
|
|
298
|
+
except ValueError:
|
|
299
|
+
raise BackendError(f"{self.provider} returned a non-JSON response") from None
|
|
300
|
+
if attempt < self.retries:
|
|
301
|
+
self.sleep(min(2.0**attempt, 20.0))
|
|
302
|
+
raise BackendError(
|
|
303
|
+
f"{self.provider} request failed after {self.retries + 1} attempts ({last})"
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def make_backend(
|
|
308
|
+
name: str,
|
|
309
|
+
*,
|
|
310
|
+
command: str | None = None,
|
|
311
|
+
model: str | None = None,
|
|
312
|
+
base_url: str | None = None,
|
|
313
|
+
openai_api: str = "chat",
|
|
314
|
+
timeout: float = 600,
|
|
315
|
+
verbose: bool = False,
|
|
316
|
+
) -> Backend | None:
|
|
317
|
+
"""Build the chosen backend; `none` returns None (nothing is ever sent)."""
|
|
318
|
+
if name == "none":
|
|
319
|
+
return None
|
|
320
|
+
if name == "cmd":
|
|
321
|
+
if not command:
|
|
322
|
+
raise UsageError("--agent cmd needs --agent-cmd")
|
|
323
|
+
return CmdBackend(command, timeout, verbose)
|
|
324
|
+
if name in ("anthropic", "openai", "azure"):
|
|
325
|
+
return HttpBackend(
|
|
326
|
+
name,
|
|
327
|
+
model or "",
|
|
328
|
+
base_url=base_url,
|
|
329
|
+
openai_api=openai_api,
|
|
330
|
+
timeout=min(timeout, 300),
|
|
331
|
+
verbose=verbose,
|
|
332
|
+
)
|
|
333
|
+
raise UsageError(f"unknown agent {name!r}; choose from {', '.join(BACKENDS)}")
|