ombro 0.2.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.
- ombro/__init__.py +9 -0
- ombro/__main__.py +3 -0
- ombro/anthropic_client.py +452 -0
- ombro/apitool.py +608 -0
- ombro/appimage.py +29 -0
- ombro/approvals_cmd.py +585 -0
- ombro/attachments.py +333 -0
- ombro/browser.py +1420 -0
- ombro/carry.py +237 -0
- ombro/chat.py +2669 -0
- ombro/chatgpt.py +534 -0
- ombro/cli.py +1837 -0
- ombro/client.py +481 -0
- ombro/coderun.py +274 -0
- ombro/commands.py +95 -0
- ombro/composio.py +764 -0
- ombro/contract.py +134 -0
- ombro/cron.py +300 -0
- ombro/engine.py +1692 -0
- ombro/fake.py +247 -0
- ombro/fake_mcp.py +196 -0
- ombro/flows.py +679 -0
- ombro/folders.py +586 -0
- ombro/folders_cmd.py +190 -0
- ombro/gate.py +263 -0
- ombro/home.py +802 -0
- ombro/init_cmd.py +549 -0
- ombro/interview.py +676 -0
- ombro/interviews.py +1089 -0
- ombro/jobs.py +430 -0
- ombro/journal.py +92 -0
- ombro/keys.py +236 -0
- ombro/livejob.py +280 -0
- ombro/material.py +104 -0
- ombro/mcp.py +774 -0
- ombro/mcp_servers.py +466 -0
- ombro/mdfile.py +94 -0
- ombro/memory.py +673 -0
- ombro/models.py +651 -0
- ombro/native.py +771 -0
- ombro/oauth.py +689 -0
- ombro/outbox.py +902 -0
- ombro/outward.py +687 -0
- ombro/pairing.py +285 -0
- ombro/prompts.py +1450 -0
- ombro/providers/__init__.py +64 -0
- ombro/providers/addresses.py +88 -0
- ombro/providers/duckduckgo.py +115 -0
- ombro/providers/fake.py +69 -0
- ombro/providers/firecrawl.py +120 -0
- ombro/proxy.py +298 -0
- ombro/removing.py +168 -0
- ombro/report.py +1076 -0
- ombro/responses_client.py +366 -0
- ombro/role_edit.py +156 -0
- ombro/roles.py +168 -0
- ombro/sandbox.py +436 -0
- ombro/schedule_cmd.py +395 -0
- ombro/scheduler.py +301 -0
- ombro/schedules.py +675 -0
- ombro/serve/__init__.py +275 -0
- ombro/serve/__main__.py +3 -0
- ombro/serve/app.py +898 -0
- ombro/serve/files.py +192 -0
- ombro/serve/live.py +389 -0
- ombro/serve/protocol.py +206 -0
- ombro/serve/settings_routes.py +731 -0
- ombro/service.py +346 -0
- ombro/session.py +657 -0
- ombro/settings.py +844 -0
- ombro/signin_page.py +57 -0
- ombro/skills.py +617 -0
- ombro/skills_cmd.py +303 -0
- ombro/slots.py +86 -0
- ombro/thinking.py +154 -0
- ombro/tool_cmd.py +417 -0
- ombro/tools.py +253 -0
- ombro/tui/__init__.py +10 -0
- ombro/tui/app.py +1074 -0
- ombro/tui/commands.py +237 -0
- ombro/tui/detect.py +84 -0
- ombro/tui/look.py +274 -0
- ombro/ui.py +616 -0
- ombro/views.py +743 -0
- ombro/viewtypes.py +415 -0
- ombro-0.2.0.dist-info/METADATA +1469 -0
- ombro-0.2.0.dist-info/RECORD +90 -0
- ombro-0.2.0.dist-info/WHEEL +4 -0
- ombro-0.2.0.dist-info/entry_points.txt +2 -0
- ombro-0.2.0.dist-info/licenses/LICENSE +661 -0
ombro/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""Ombro: a small local harness for briefing a crew of AI roles.
|
|
2
|
+
|
|
3
|
+
Copyright © 2026 Heliotrope Atelier Ltd. Licensed under the GNU Affero General Public License,
|
|
4
|
+
version 3 only (AGPL-3.0-only).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# The one version for the core, the server and the app. gui/package.json, gui/src-tauri/Cargo.toml
|
|
8
|
+
# and gui/src-tauri/tauri.conf.json carry copies, which tests/test_version.py keeps in step.
|
|
9
|
+
__version__ = "0.2.0"
|
ombro/__main__.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"""Anthropic's own API (the Messages API), for Claude models.
|
|
2
|
+
|
|
3
|
+
Ombro keeps messages in the OpenAI shape; this client turns them into Anthropic's on the way out
|
|
4
|
+
and the reply back on the way in, so the rest of Ombro doesn't know the difference. What it adds
|
|
5
|
+
over Anthropic's OpenAI-compatible endpoint:
|
|
6
|
+
|
|
7
|
+
- Prompt caching. The system prompt is marked as a cache point (tools come before it, so they
|
|
8
|
+
are cached with it), and the request asks Anthropic to cache the conversation so far as well,
|
|
9
|
+
so each step of a job reads the earlier steps from the cache. Usage shows it as cached input.
|
|
10
|
+
- Thinking. A Claude reply can carry thinking blocks; they go back exactly as they came, kept on
|
|
11
|
+
the message under "_blocks", so the model keeps its reasoning between tool calls.
|
|
12
|
+
- The model list, every page of it, as the key can use it.
|
|
13
|
+
|
|
14
|
+
Calls are not streamed: Ombro waits for whole replies everywhere. The key is fetched on every
|
|
15
|
+
call and never logged; any error text is scrubbed of it.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import time
|
|
22
|
+
from contextlib import nullcontext
|
|
23
|
+
from typing import Any, Callable
|
|
24
|
+
from urllib.parse import urlparse
|
|
25
|
+
|
|
26
|
+
import httpx
|
|
27
|
+
|
|
28
|
+
from ombro.client import (
|
|
29
|
+
RETRYABLE,
|
|
30
|
+
BUSY_RETRIES,
|
|
31
|
+
ModelError,
|
|
32
|
+
ModelReply,
|
|
33
|
+
ToolCall,
|
|
34
|
+
Usage,
|
|
35
|
+
allowed_max_tokens,
|
|
36
|
+
busy_pause,
|
|
37
|
+
busy_wait,
|
|
38
|
+
no_slot_error,
|
|
39
|
+
)
|
|
40
|
+
from ombro.slots import NoSlot
|
|
41
|
+
|
|
42
|
+
API_VERSION = "2026-10-21"
|
|
43
|
+
FALLBACK_BETA = "server-side-fallback-2026-07-01"
|
|
44
|
+
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
|
45
|
+
_EFFORT_ALIASES = {"minimal": "low"} # OpenAI's words for the same idea
|
|
46
|
+
_FINISH = {
|
|
47
|
+
"end_turn": "stop",
|
|
48
|
+
"stop_sequence": "stop",
|
|
49
|
+
"max_tokens": "length",
|
|
50
|
+
"tool_use": "tool_calls",
|
|
51
|
+
"pause_turn": "stop",
|
|
52
|
+
"refusal": "refusal",
|
|
53
|
+
}
|
|
54
|
+
_THINKING = ("thinking", "redacted_thinking")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class AnthropicClient:
|
|
58
|
+
"""POSTs to {endpoint}/messages, where the endpoint is https://api.anthropic.com/v1."""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
endpoint: str,
|
|
63
|
+
model: str,
|
|
64
|
+
key_getter: Callable[[], str | None],
|
|
65
|
+
*,
|
|
66
|
+
transport: httpx.BaseTransport | None = None,
|
|
67
|
+
retries: int = 2,
|
|
68
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
69
|
+
effort: str | None = None,
|
|
70
|
+
slots=None,
|
|
71
|
+
thinking: str | None = None,
|
|
72
|
+
):
|
|
73
|
+
self.slots = slots # ombro.slots.ProviderSlots: how many calls may be in flight to Anthropic at once
|
|
74
|
+
self.base = endpoint.rstrip("/")
|
|
75
|
+
self.url = self.base + "/messages"
|
|
76
|
+
self.host = urlparse(endpoint).netloc or endpoint
|
|
77
|
+
self.model = model
|
|
78
|
+
self.key_getter = key_getter
|
|
79
|
+
self.transport = transport
|
|
80
|
+
self.retries = retries
|
|
81
|
+
self.sleep = sleep
|
|
82
|
+
self.learned_max: int | None = None # the most the model allows per reply, learned from its refusal
|
|
83
|
+
effort = _EFFORT_ALIASES.get((effort or "").lower(), (effort or "").lower())
|
|
84
|
+
self.effort = effort if effort in EFFORTS else None # "none" and unknown words: the model's default
|
|
85
|
+
self.effort_refused = False
|
|
86
|
+
self.thinking = thinking # a level (ombro.thinking) when models.md gives no effort word of its own
|
|
87
|
+
self.thinking_refused = False
|
|
88
|
+
self.fallback_refused = False # a model or account that doesn't take server-side fallbacks
|
|
89
|
+
self.stale_thinking: set[str] = set() # signatures of thinking blocks Anthropic no longer accepts
|
|
90
|
+
|
|
91
|
+
# -- calls ---------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
def _headers(self, key: str | None, beta: bool = False) -> dict[str, str]:
|
|
94
|
+
h = {"Content-Type": "application/json", "anthropic-version": API_VERSION}
|
|
95
|
+
if key:
|
|
96
|
+
h["x-api-key"] = key
|
|
97
|
+
if beta:
|
|
98
|
+
h["anthropic-beta"] = FALLBACK_BETA
|
|
99
|
+
return h
|
|
100
|
+
|
|
101
|
+
def complete(self, messages, *, tools=None, max_output_tokens, timeout) -> ModelReply:
|
|
102
|
+
key = self.key_getter()
|
|
103
|
+
if not key:
|
|
104
|
+
raise ModelError("no API key is set for this model; run `ombro init` or set it with `ombro keys set`")
|
|
105
|
+
if self.learned_max:
|
|
106
|
+
max_output_tokens = min(int(max_output_tokens), self.learned_max)
|
|
107
|
+
system, converted = to_anthropic(messages, self.stale_thinking)
|
|
108
|
+
body: dict[str, Any] = {
|
|
109
|
+
"model": self.model,
|
|
110
|
+
"max_tokens": int(max_output_tokens),
|
|
111
|
+
"messages": converted,
|
|
112
|
+
# Cache the conversation so far too: each step reads the steps before it.
|
|
113
|
+
"cache_control": {"type": "ephemeral"},
|
|
114
|
+
}
|
|
115
|
+
if system:
|
|
116
|
+
# The stable part: tools and the system prompt, cached together (tools come first).
|
|
117
|
+
body["system"] = [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}]
|
|
118
|
+
if tools:
|
|
119
|
+
body["tools"] = to_anthropic_tools(tools)
|
|
120
|
+
if self.effort and not self.effort_refused:
|
|
121
|
+
body["output_config"] = {"effort": self.effort}
|
|
122
|
+
elif self.thinking and not self.effort:
|
|
123
|
+
from ombro.thinking import anthropic_fields
|
|
124
|
+
|
|
125
|
+
fields = anthropic_fields(self.thinking, self.model, int(body["max_tokens"]))
|
|
126
|
+
if self.thinking_refused:
|
|
127
|
+
fields.pop("thinking", None)
|
|
128
|
+
if self.effort_refused:
|
|
129
|
+
fields.pop("output_config", None)
|
|
130
|
+
body.update(fields)
|
|
131
|
+
if not self.fallback_refused:
|
|
132
|
+
# If Claude's safety checks decline a request, Anthropic tries another Claude model.
|
|
133
|
+
body["fallbacks"] = "default"
|
|
134
|
+
|
|
135
|
+
deadline = time.monotonic() + timeout
|
|
136
|
+
attempt = 0
|
|
137
|
+
busy = 0
|
|
138
|
+
lost = 0
|
|
139
|
+
stripped = False
|
|
140
|
+
while True:
|
|
141
|
+
remaining = deadline - time.monotonic()
|
|
142
|
+
if remaining <= 0:
|
|
143
|
+
err = ModelError("the model call ran out of time", timed_out=True)
|
|
144
|
+
err.lost_attempts = lost
|
|
145
|
+
raise err
|
|
146
|
+
retryable = False
|
|
147
|
+
try:
|
|
148
|
+
with (
|
|
149
|
+
self.slots.hold(deadline) if self.slots else nullcontext(),
|
|
150
|
+
httpx.Client(
|
|
151
|
+
transport=self.transport,
|
|
152
|
+
timeout=httpx.Timeout(max(0.1, deadline - time.monotonic()), connect=min(remaining, 15.0)),
|
|
153
|
+
) as http,
|
|
154
|
+
):
|
|
155
|
+
resp = http.post(self.url, json=body, headers=self._headers(key, "fallbacks" in body))
|
|
156
|
+
except NoSlot:
|
|
157
|
+
err = no_slot_error(self.host)
|
|
158
|
+
err.lost_attempts = lost
|
|
159
|
+
raise err from None
|
|
160
|
+
except httpx.TimeoutException:
|
|
161
|
+
err = ModelError("the model call ran out of time", timed_out=True)
|
|
162
|
+
retryable = True
|
|
163
|
+
lost += 1 # it may have reached the model and been billed, with no usage to show
|
|
164
|
+
except httpx.HTTPError as e:
|
|
165
|
+
err = ModelError(f"could not reach {self.host}: {type(e).__name__}")
|
|
166
|
+
retryable = True
|
|
167
|
+
else:
|
|
168
|
+
if resp.status_code == 200:
|
|
169
|
+
reply = self._parse(resp)
|
|
170
|
+
reply.lost_attempts = lost
|
|
171
|
+
return reply
|
|
172
|
+
detail = _error_text(resp, key)
|
|
173
|
+
low = detail.lower()
|
|
174
|
+
if resp.status_code == 400:
|
|
175
|
+
if "fallback" in low and "fallbacks" in body:
|
|
176
|
+
self.fallback_refused = True # this model doesn't take them: carry on without
|
|
177
|
+
del body["fallbacks"]
|
|
178
|
+
continue
|
|
179
|
+
if "thinking" in low and "thinking" in body and "signature" not in low:
|
|
180
|
+
self.thinking_refused = True # this model doesn't take that thinking setting
|
|
181
|
+
del body["thinking"]
|
|
182
|
+
continue
|
|
183
|
+
if "effort" in low and "output_config" in body:
|
|
184
|
+
self.effort_refused = True
|
|
185
|
+
del body["output_config"]
|
|
186
|
+
continue
|
|
187
|
+
if "thinking" in low and "signature" in low and not stripped:
|
|
188
|
+
# Ombro changed earlier turns (a long chat trimmed, say), so Anthropic won't take
|
|
189
|
+
# the thinking that came with them. Send them without it, once, and from now on.
|
|
190
|
+
stripped = True
|
|
191
|
+
self.stale_thinking |= _signatures(converted)
|
|
192
|
+
_, converted = to_anthropic(messages, self.stale_thinking, strip_all=True)
|
|
193
|
+
body["messages"] = converted
|
|
194
|
+
continue
|
|
195
|
+
allowed = allowed_max_tokens(detail) if resp.status_code == 400 else None
|
|
196
|
+
if allowed and allowed < body["max_tokens"] and not self.learned_max:
|
|
197
|
+
self.learned_max = allowed
|
|
198
|
+
body["max_tokens"] = allowed
|
|
199
|
+
continue
|
|
200
|
+
err = ModelError(f"{self.host} returned HTTP {resp.status_code}: {detail}", status=resp.status_code)
|
|
201
|
+
wait = busy_wait(resp, detail)
|
|
202
|
+
if wait is not None and busy < BUSY_RETRIES:
|
|
203
|
+
busy += 1
|
|
204
|
+
pause = busy_pause(wait, busy)
|
|
205
|
+
if pause < deadline - time.monotonic() - 1:
|
|
206
|
+
self.sleep(pause)
|
|
207
|
+
continue
|
|
208
|
+
retryable = resp.status_code in RETRYABLE and wait is None
|
|
209
|
+
if not retryable or attempt >= self.retries:
|
|
210
|
+
err.lost_attempts = lost
|
|
211
|
+
raise err
|
|
212
|
+
attempt += 1
|
|
213
|
+
pause = min(2.0**attempt, max(0.0, deadline - time.monotonic() - 1))
|
|
214
|
+
if pause > 0:
|
|
215
|
+
self.sleep(pause)
|
|
216
|
+
|
|
217
|
+
def list_models(self, timeout: float = 20.0) -> list[str]:
|
|
218
|
+
"""Every model this key can use (GET {endpoint}/models, page by page), sorted.
|
|
219
|
+
Raises ModelError if the endpoint does not say."""
|
|
220
|
+
key = self.key_getter()
|
|
221
|
+
ids: set[str] = set()
|
|
222
|
+
after: str | None = None
|
|
223
|
+
with httpx.Client(transport=self.transport, timeout=httpx.Timeout(timeout)) as http:
|
|
224
|
+
for _ in range(50): # pages of 1,000: far more than Anthropic has
|
|
225
|
+
params = {"limit": "1000", **({"after_id": after} if after else {})}
|
|
226
|
+
try:
|
|
227
|
+
resp = http.get(self.base + "/models", params=params, headers=self._headers(key))
|
|
228
|
+
except httpx.HTTPError as e:
|
|
229
|
+
raise ModelError(f"could not reach {self.host}: {type(e).__name__}") from None
|
|
230
|
+
if resp.status_code != 200:
|
|
231
|
+
raise ModelError(
|
|
232
|
+
f"{self.host} returned HTTP {resp.status_code}: {_error_text(resp, key)}",
|
|
233
|
+
status=resp.status_code,
|
|
234
|
+
)
|
|
235
|
+
try:
|
|
236
|
+
data = resp.json()
|
|
237
|
+
page = [str(m["id"]) for m in data["data"] if isinstance(m, dict) and m.get("id")]
|
|
238
|
+
except (ValueError, KeyError, TypeError):
|
|
239
|
+
raise ModelError(f"{self.host} sent a model list Ombro could not read") from None
|
|
240
|
+
ids.update(page)
|
|
241
|
+
after = data.get("last_id") or (page[-1] if page else None)
|
|
242
|
+
if not data.get("has_more") or not page or not after:
|
|
243
|
+
break
|
|
244
|
+
if not ids:
|
|
245
|
+
raise ModelError(f"{self.host} listed no models")
|
|
246
|
+
return sorted(ids)
|
|
247
|
+
|
|
248
|
+
# -- the reply -----------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
def _parse(self, resp: httpx.Response) -> ModelReply:
|
|
251
|
+
try:
|
|
252
|
+
data = resp.json()
|
|
253
|
+
content = data["content"]
|
|
254
|
+
if not isinstance(content, list):
|
|
255
|
+
raise TypeError
|
|
256
|
+
except (ValueError, KeyError, TypeError):
|
|
257
|
+
raise ModelError(f"{self.host} sent a reply Ombro could not read") from None
|
|
258
|
+
texts: list[str] = []
|
|
259
|
+
calls: list[ToolCall] = []
|
|
260
|
+
for i, block in enumerate(content):
|
|
261
|
+
if not isinstance(block, dict):
|
|
262
|
+
continue
|
|
263
|
+
if block.get("type") == "text":
|
|
264
|
+
texts.append(str(block.get("text") or ""))
|
|
265
|
+
elif block.get("type") == "tool_use":
|
|
266
|
+
args = block.get("input")
|
|
267
|
+
calls.append(
|
|
268
|
+
ToolCall(
|
|
269
|
+
id=str(block.get("id") or f"call_{i}"),
|
|
270
|
+
name=str(block.get("name") or ""),
|
|
271
|
+
arguments=args if isinstance(args, dict) else None,
|
|
272
|
+
raw_arguments=json.dumps(args if args is not None else {}, ensure_ascii=False),
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
stop = data.get("stop_reason")
|
|
276
|
+
text = "".join(texts) or None
|
|
277
|
+
if stop == "refusal" and not text and not calls:
|
|
278
|
+
details = data.get("stop_details") or {}
|
|
279
|
+
why = details.get("explanation") if isinstance(details, dict) else None
|
|
280
|
+
text = "The model declined this request" + (f": {why}" if why else ".")
|
|
281
|
+
usage = data.get("usage") or {}
|
|
282
|
+
if usage.get("input_tokens") is not None:
|
|
283
|
+
read = int(usage.get("cache_read_input_tokens") or 0)
|
|
284
|
+
written = int(usage.get("cache_creation_input_tokens") or 0)
|
|
285
|
+
# Anthropic counts cached and newly cached input apart from input_tokens; Ombro counts all of it.
|
|
286
|
+
u = Usage(
|
|
287
|
+
int(usage.get("input_tokens") or 0) + read + written,
|
|
288
|
+
int(usage.get("output_tokens") or 0),
|
|
289
|
+
cached_input=read,
|
|
290
|
+
)
|
|
291
|
+
else:
|
|
292
|
+
out_chars = len(text or "") + sum(len(c.raw_arguments) for c in calls)
|
|
293
|
+
u = Usage(0, out_chars // 3 + 1, estimated=True)
|
|
294
|
+
# Thinking (and a fallback's marker) must go back exactly as sent; plain text and tool calls rebuild.
|
|
295
|
+
exact = any(isinstance(b, dict) and b.get("type") not in ("text", "tool_use") for b in content)
|
|
296
|
+
return ModelReply(
|
|
297
|
+
content=text,
|
|
298
|
+
tool_calls=calls,
|
|
299
|
+
usage=u,
|
|
300
|
+
finish_reason=_FINISH.get(stop, stop),
|
|
301
|
+
blocks=content if exact else None,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# -- turning Ombro's messages into Anthropic's ---------------------------------
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def to_anthropic_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
309
|
+
"""OpenAI function tools as Anthropic tools, in the same order (so they cache)."""
|
|
310
|
+
out = []
|
|
311
|
+
for t in tools:
|
|
312
|
+
fn = t.get("function") if isinstance(t.get("function"), dict) else t
|
|
313
|
+
schema = fn.get("parameters") or fn.get("input_schema") or {}
|
|
314
|
+
if not isinstance(schema, dict) or schema.get("type") != "object":
|
|
315
|
+
schema = {"type": "object", "properties": {}}
|
|
316
|
+
tool: dict[str, Any] = {"name": str(fn.get("name") or ""), "input_schema": schema}
|
|
317
|
+
if fn.get("description"):
|
|
318
|
+
tool["description"] = str(fn["description"])
|
|
319
|
+
out.append(tool)
|
|
320
|
+
return out
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _text_of(content: Any) -> str:
|
|
324
|
+
if isinstance(content, str):
|
|
325
|
+
return content
|
|
326
|
+
if isinstance(content, list):
|
|
327
|
+
return "".join(str(p.get("text") or "") for p in content if isinstance(p, dict) and p.get("type") == "text")
|
|
328
|
+
return "" if content is None else str(content)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _images(content: Any) -> list[dict[str, Any]]:
|
|
332
|
+
"""Image parts in a user's message (OpenAI's form, data URLs) as Anthropic's image blocks."""
|
|
333
|
+
out = []
|
|
334
|
+
for p in content if isinstance(content, list) else []:
|
|
335
|
+
url = str(((p or {}).get("image_url") or {}).get("url") or "") if isinstance(p, dict) else ""
|
|
336
|
+
if p.get("type") == "image_url" and url.startswith("data:") and ";base64," in url:
|
|
337
|
+
head, data = url[5:].split(";base64,", 1)
|
|
338
|
+
out.append({"type": "image", "source": {"type": "base64", "media_type": head, "data": data}})
|
|
339
|
+
return out
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _signatures(messages: list[dict[str, Any]]) -> set[str]:
|
|
343
|
+
return {
|
|
344
|
+
str(b.get("signature") or b.get("data"))
|
|
345
|
+
for m in messages
|
|
346
|
+
if isinstance(m.get("content"), list)
|
|
347
|
+
for b in m["content"]
|
|
348
|
+
if isinstance(b, dict) and b.get("type") in _THINKING
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _assistant_blocks(m: dict[str, Any], stale: set[str], strip_all: bool) -> list[dict[str, Any]]:
|
|
353
|
+
raw = m.get("_blocks")
|
|
354
|
+
if isinstance(raw, list) and raw:
|
|
355
|
+
return [
|
|
356
|
+
b
|
|
357
|
+
for b in raw
|
|
358
|
+
if isinstance(b, dict)
|
|
359
|
+
and not (b.get("type") in _THINKING and (strip_all or str(b.get("signature") or b.get("data")) in stale))
|
|
360
|
+
]
|
|
361
|
+
blocks: list[dict[str, Any]] = []
|
|
362
|
+
text = _text_of(m.get("content"))
|
|
363
|
+
if text.strip():
|
|
364
|
+
blocks.append({"type": "text", "text": text})
|
|
365
|
+
for i, tc in enumerate(m.get("tool_calls") or []):
|
|
366
|
+
fn = tc.get("function") or {}
|
|
367
|
+
raw_args = fn.get("arguments")
|
|
368
|
+
try:
|
|
369
|
+
args = raw_args if isinstance(raw_args, dict) else json.loads(raw_args or "{}")
|
|
370
|
+
except (TypeError, ValueError):
|
|
371
|
+
args = {}
|
|
372
|
+
blocks.append(
|
|
373
|
+
{
|
|
374
|
+
"type": "tool_use",
|
|
375
|
+
"id": str(tc.get("id") or f"call_{i}"),
|
|
376
|
+
"name": str(fn.get("name") or ""),
|
|
377
|
+
"input": args if isinstance(args, dict) else {},
|
|
378
|
+
}
|
|
379
|
+
)
|
|
380
|
+
return blocks
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def to_anthropic(
|
|
384
|
+
messages: list[dict[str, Any]], stale: set[str] | None = None, *, strip_all: bool = False
|
|
385
|
+
) -> tuple[str, list[dict[str, Any]]]:
|
|
386
|
+
"""(system, messages) for the Messages API. The system messages at the start become the
|
|
387
|
+
system prompt; a later one goes in as the user's note. Tool results join one user turn, ahead
|
|
388
|
+
of any text, and turns of the same role are joined."""
|
|
389
|
+
stale = stale or set()
|
|
390
|
+
system_parts: list[str] = []
|
|
391
|
+
out: list[dict[str, Any]] = []
|
|
392
|
+
start = True
|
|
393
|
+
|
|
394
|
+
def add(role: str, blocks: list[dict[str, Any]]) -> None:
|
|
395
|
+
if not blocks:
|
|
396
|
+
return
|
|
397
|
+
if out and out[-1]["role"] == role:
|
|
398
|
+
prev = out[-1]["content"]
|
|
399
|
+
if role == "user" and blocks[0].get("type") == "tool_result":
|
|
400
|
+
# tool results first in the turn, as Anthropic asks
|
|
401
|
+
results = [b for b in prev if b.get("type") == "tool_result"]
|
|
402
|
+
rest = [b for b in prev if b.get("type") != "tool_result"]
|
|
403
|
+
out[-1]["content"] = results + blocks + rest
|
|
404
|
+
else:
|
|
405
|
+
prev.extend(blocks)
|
|
406
|
+
else:
|
|
407
|
+
out.append({"role": role, "content": list(blocks)})
|
|
408
|
+
|
|
409
|
+
for m in messages:
|
|
410
|
+
role = m.get("role")
|
|
411
|
+
if role == "system" and start:
|
|
412
|
+
system_parts.append(_text_of(m.get("content")))
|
|
413
|
+
continue
|
|
414
|
+
start = False
|
|
415
|
+
if role == "system":
|
|
416
|
+
text = _text_of(m.get("content"))
|
|
417
|
+
if text.strip():
|
|
418
|
+
add("user", [{"type": "text", "text": f"<system-note>\n{text}\n</system-note>"}])
|
|
419
|
+
elif role == "assistant":
|
|
420
|
+
add("assistant", _assistant_blocks(m, stale, strip_all))
|
|
421
|
+
elif role == "tool":
|
|
422
|
+
add(
|
|
423
|
+
"user",
|
|
424
|
+
[
|
|
425
|
+
{
|
|
426
|
+
"type": "tool_result",
|
|
427
|
+
"tool_use_id": str(m.get("tool_call_id") or ""),
|
|
428
|
+
"content": _text_of(m.get("content")) or "(no output)",
|
|
429
|
+
}
|
|
430
|
+
],
|
|
431
|
+
)
|
|
432
|
+
else:
|
|
433
|
+
images = _images(m.get("content"))
|
|
434
|
+
text = _text_of(m.get("content"))
|
|
435
|
+
if text.strip() or images:
|
|
436
|
+
add("user", [*images, *([{"type": "text", "text": text}] if text.strip() else [])])
|
|
437
|
+
if not out or out[0]["role"] != "user":
|
|
438
|
+
out.insert(0, {"role": "user", "content": [{"type": "text", "text": "Begin."}]})
|
|
439
|
+
return "\n\n".join(p for p in system_parts if p), out
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _error_text(resp: httpx.Response, key: str | None) -> str:
|
|
443
|
+
try:
|
|
444
|
+
data = resp.json()
|
|
445
|
+
err = data.get("error", data) if isinstance(data, dict) else data
|
|
446
|
+
msg = err.get("message") if isinstance(err, dict) else str(err)
|
|
447
|
+
except ValueError:
|
|
448
|
+
msg = resp.text
|
|
449
|
+
text = str(msg or "no detail")
|
|
450
|
+
if key:
|
|
451
|
+
text = text.replace(key, "***")
|
|
452
|
+
return text[:300]
|