Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_ai.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_ai.py · 48.9 KB · 1150 lines
1"""Provider-neutral AI chat with MCP tool calling.
2
3This is the shell's brain: one conversation turn goes to an AI provider
4using the caller's own stored service key, the model may call a small,
5caller-chosen subset of the server's MCP tools, and every tool call is
6dispatched back through the server's own routing so permission checks
7and audit apply exactly as if the caller made the request directly.
8
9Models are named ``service:model`` (``anthropic:claude-haiku-5-5``,
10``openai:gpt-5-mini``). Handing the model only a few named tools keeps
11the context small enough for fast, inexpensive models — the tool subset
12is configuration, not code.
13
14The module is pure: HTTP is injected by the caller, so tests run without
15a network and the server owns timeouts and threading.
16"""
17
18from __future__ import annotations
19
20import json
21import re
22from typing import Any, Callable, Iterable, Iterator, Mapping
23
24DEFAULT_MAX_ROUNDS = 6
25MAX_ROUNDS_LIMIT = 12
26
27# Output budget per provider round. 1024 was too low once models think
28# before answering (thinking counts against max_tokens) and once builder
29# mode writes whole objects: a create_object call whose source is cut off
30# mid-function arrives as a truncated tool call. Conversation keeps a
31# smaller default; builder mode (a tool subset that can write object
32# source) gets more. A caller may ask for any value up to the cap.
33DEFAULT_MAX_TOKENS = 4096
34BUILDER_MAX_TOKENS = 8192
35# Non-streaming requests hold one HTTP response open until the whole
36# answer exists, so their cap is lower than a streamed request's, whose
37# bytes start arriving at once. An operator can set its own cap
38# (DBBASIC_AI_MAX_TOKENS_CAP), which then bounds both.
39MAX_TOKENS_CAP = 8192
40STREAM_MAX_TOKENS_CAP = 16384
41
42# A tool subset containing any of these can write object source: that is
43# "builder mode", which gets a larger output budget and more effort.
44BUILDER_TOOLS = frozenset({"create_object", "update_object_source"})
45
46EFFORT_LEVELS = ("low", "medium", "high", "xhigh", "max")
47DEFAULT_CONVERSATION_EFFORT = "low"
48DEFAULT_BUILDER_EFFORT = "high"
49
50ANTHROPIC_URL = "https://api.anthropic.com/v1/messages"
51ANTHROPIC_VERSION = "2023-06-01"
52OPENAI_URL = "https://api.openai.com/v1/chat/completions"
53
54SUPPORTED_SERVICES = ("anthropic", "openai")
55
56# The gpt-5.6 family defaults to a non-"none" reasoning_effort that OpenAI's
57# /v1/chat/completions rejects outright when tools are also present ("Function
58# tools with reasoning_effort are not supported ... set reasoning_effort to
59# 'none'" -- their error, not ours). Older models (gpt-5, gpt-5-mini, ...)
60# already work fine with tools under their own default, so this is scoped to
61# the specific family that needs it rather than applied to every OpenAI call.
62_REASONING_EFFORT_NONE_MODELS = ("gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol")
63
64# send_http(url, headers, body_bytes) -> (status, response_bytes)
65SendHttp = Callable[[str, Mapping[str, str], bytes], tuple[int, bytes]]
66# send_http_stream(url, headers, body_bytes) -> (status, iterable of byte
67# lines). The server owns the connection; the iterable is read once, in
68# order, and the module never holds more than one event in memory.
69SendHttpStream = Callable[[str, Mapping[str, str], bytes], tuple[int, Iterable[bytes]]]
70# on_event(kind, data): "text" {"text": delta} as the model writes, and
71# "tool_call" (the tool log entry) after each tool runs.
72OnEvent = Callable[[str, dict[str, Any]], None]
73# dispatch_tool(name, arguments) -> {"http_status": int, "response": Any}
74DispatchTool = Callable[[str, dict[str, Any]], dict[str, Any]]
75
76
77class AIProviderError(RuntimeError):
78 """Raised when the provider returns an unusable response."""
79
80
81class InvalidChatRequestError(ValueError):
82 """Raised when a chat request payload is not usable."""
83
84
85def chat_mode(tool_names: list[str] | None) -> str:
86 """"builder" when the tool subset can write object source, else
87 "conversation"."""
88 return "builder" if BUILDER_TOOLS.intersection(tool_names or ()) else "conversation"
89
90
91_CLAUDE_ID = re.compile(r"^claude-(?:opus|sonnet|haiku)-(\d+)(?:-(\d+))?$")
92
93
94def claude_version(model: str) -> tuple[int, int] | None:
95 """(major, minor) of a current-style Claude id, or None.
96
97 ``claude-haiku-5-5`` -> (5, 5); ``claude-sonnet-5`` -> (5, 0). Anything
98 else -- an older naming scheme, a dated snapshot id, a typo -- is None,
99 and callers treat None as "do not send newer request fields".
100 """
101 match = _CLAUDE_ID.match(model or "")
102 if not match:
103 return None
104 return int(match.group(1)), int(match.group(2) or 0)
105
106
107def model_supports_effort(service: str, model: str) -> bool:
108 """Whether to send ``output_config.effort`` (and strict tools).
109
110 The Claude 4.6+ family accepts both; claude-haiku-4-5 and older do
111 not, and OpenAI has its own, different knob (reasoning_effort, which
112 this module only touches for the gpt-5.6 tool-use case). An id this
113 function cannot read gets neither: an unknown field is a 400 that
114 fails the whole turn, and leaving it out only means the model uses
115 its own default.
116 """
117 if service != "anthropic":
118 return False
119 version = claude_version(model)
120 return version is not None and version >= (4, 6)
121
122
123def model_supports_strict_tools(service: str, model: str) -> bool:
124 """Whether to mark eligible tools ``strict``. Same family gate as
125 effort, for the same reason: an id this module cannot place gets the
126 request shape it always got."""
127 return model_supports_effort(service, model)
128
129
130# Strict tool use makes the provider guarantee that a tool call's input
131# matches the tool's input_schema, which needs a CLOSED schema: every
132# object lists its properties, sets additionalProperties: false and has a
133# required list. MCP catalog schemas are written for humans and agents and
134# several take a free-form object (create_record's ``record``,
135# update_record's ``changes``, list_records' ``where``, execute_object's
136# ``payload``, update_schema's ``schema``) -- those cannot be closed
137# without rejecting the very fields the tool exists to carry, so those
138# tools stay non-strict. A closed copy is made only from the keywords
139# below; anything else in a schema leaves its tool non-strict rather than
140# risk a request the provider refuses. ``default`` is dropped from the
141# copy (the server's tool routing applies its own defaults when an
142# optional field is absent) and kept, readable, in the description.
143_STRICT_KEYWORDS = frozenset({"type", "description", "properties", "required", "enum",
144 "items", "default", "additionalProperties"})
145
146
147def strict_input_schema(schema: Any) -> dict[str, Any] | None:
148 """A strict-ready copy of a tool input schema, or None if it cannot be
149 closed without changing what the tool accepts."""
150 if not isinstance(schema, dict) or set(schema) - _STRICT_KEYWORDS:
151 return None
152 if schema.get("additionalProperties") not in (None, False):
153 return None
154 kind = schema.get("type")
155 out: dict[str, Any] = {key: schema[key] for key in ("type", "enum") if key in schema}
156 description = schema.get("description")
157 if "default" in schema:
158 note = f"Default: {json.dumps(schema['default'])}."
159 if not description or "default" not in description.lower():
160 description = f"{description.rstrip('.')}. {note}" if description else note
161 if description:
162 out["description"] = description
163 if kind == "object":
164 properties = schema.get("properties")
165 if not isinstance(properties, dict):
166 return None # a free-form object cannot be closed
167 closed = {}
168 for name, prop in properties.items():
169 sub = strict_input_schema(prop)
170 if sub is None:
171 return None
172 closed[name] = sub
173 required = schema.get("required") or []
174 if not isinstance(required, list) or any(name not in properties for name in required):
175 return None
176 out["properties"] = closed
177 out["required"] = list(required)
178 out["additionalProperties"] = False
179 elif kind == "array":
180 items = strict_input_schema(schema.get("items"))
181 if items is None:
182 return None
183 out["items"] = items
184 elif kind not in ("string", "integer", "number", "boolean"):
185 return None
186 return out
187
188
189# The provider refuses a request that marks more than this many tools strict
190# (HTTP 400 "Too many strict tools"), so a large tool subset keeps strict on
191# the tools where a malformed call costs most and sends the rest unmarked.
192MAX_STRICT_TOOLS = 20
193_STRICT_FIRST_PREFIXES = ("create_", "update_", "delete_", "rollback_", "setup_", "start_", "stop_")
194
195
196def with_strict_tools(tools: list[dict[str, Any]],
197 limit: int | None = MAX_STRICT_TOOLS) -> list[dict[str, Any]]:
198 """Anthropic tool definitions with ``strict: true`` on tools whose input
199 schema can be closed (strict_input_schema); the rest unchanged.
200
201 At most ``limit`` tools are marked (the provider's cap). When more could
202 be, tools that change something are marked first, then the others in the
203 order given. ``limit=None`` marks every closable tool."""
204 closed = {index: schema for index, tool in enumerate(tools)
205 if (schema := strict_input_schema(tool.get("input_schema"))) is not None}
206 chosen = sorted(closed, key=lambda index: (
207 not str(tools[index].get("name", "")).startswith(_STRICT_FIRST_PREFIXES), index))
208 if limit is not None:
209 chosen = chosen[:max(0, limit)]
210 marked = set(chosen)
211 return [{**tool, "input_schema": closed[index], "strict": True} if index in marked else tool
212 for index, tool in enumerate(tools)]
213
214
215def resolve_max_tokens(
216 requested: Any = None,
217 *,
218 mode: str = "conversation",
219 stream: bool = False,
220 cap: int | None = None,
221) -> int:
222 """The max_tokens to send: the caller's ask, or the mode's default,
223 never above the cap."""
224 limit = STREAM_MAX_TOKENS_CAP if stream else MAX_TOKENS_CAP
225 if cap is not None:
226 limit = cap
227 if requested is None:
228 default = BUILDER_MAX_TOKENS if mode == "builder" else DEFAULT_MAX_TOKENS
229 if stream and mode == "builder":
230 default = STREAM_MAX_TOKENS_CAP
231 return min(default, limit)
232 if isinstance(requested, bool) or not isinstance(requested, int) or requested < 1:
233 raise InvalidChatRequestError("max_tokens must be a positive integer")
234 return min(requested, limit)
235
236
237def resolve_effort(requested: Any = None, *, mode: str = "conversation",
238 conversation_default: str = DEFAULT_CONVERSATION_EFFORT,
239 builder_default: str = DEFAULT_BUILDER_EFFORT) -> str:
240 """The effort level for this turn: the caller's ask, else the mode's
241 default. Whether it is SENT depends on the model (run_chat decides)."""
242 if requested is None:
243 return builder_default if mode == "builder" else conversation_default
244 if requested not in EFFORT_LEVELS:
245 raise InvalidChatRequestError(f"effort must be one of: {', '.join(EFFORT_LEVELS)}")
246 return requested
247
248
249def split_model(model: str) -> tuple[str, str]:
250 """Split 'service:model' and validate the service."""
251 if not isinstance(model, str) or ":" not in model:
252 raise InvalidChatRequestError(
253 "model must be 'service:model', like anthropic:claude-haiku-5-5"
254 )
255 service, _, name = model.partition(":")
256 if service not in SUPPORTED_SERVICES or not name:
257 supported = ", ".join(SUPPORTED_SERVICES)
258 raise InvalidChatRequestError(f"model service must be one of: {supported}")
259 return service, name
260
261
262def mcp_tools_as_provider_tools(
263 tool_names: list[str],
264 catalog: list[dict[str, Any]],
265 *,
266 service: str,
267) -> list[dict[str, Any]]:
268 """Convert named MCP catalog entries into the provider's tool format."""
269 by_name = {tool["name"]: tool for tool in catalog}
270 unknown = [name for name in tool_names if name not in by_name]
271 if unknown:
272 raise InvalidChatRequestError(f"Unknown tools: {', '.join(sorted(unknown))}")
273
274 tools = []
275 for name in tool_names:
276 tool = by_name[name]
277 if service == "anthropic":
278 tools.append(
279 {
280 "name": tool["name"],
281 "description": tool.get("description", ""),
282 "input_schema": tool.get("inputSchema", {"type": "object"}),
283 }
284 )
285 else:
286 tools.append(
287 {
288 "type": "function",
289 "function": {
290 "name": tool["name"],
291 "description": tool.get("description", ""),
292 "parameters": tool.get("inputSchema", {"type": "object"}),
293 },
294 }
295 )
296 return tools
297
298
299# read_page's real links (with real hrefs) are exactly the kind of precise
300# fact a model's own restated prose loses -- conversation history only ever
301# carries the model's text, never a tool's actual result, so "go to that
302# story" on a LATER turn had nothing but the model's own possibly-vague
303# summary to resolve against. Caught live: a real Talk session fetched
304# Techmeme, summarized it in prose with no link numbers at all (voice
305# mode's "keep it short" instruction won against "cite link numbers" on a
306# link-heavy page), and the very next turn had no way back to the actual
307# article. Echoing the real link list back to the caller here -- capped,
308# so a link-heavy page can't balloon every subsequent turn's context size
309# once a caller starts re-injecting it -- lets a later turn ground a
310# reference in real hrefs instead of the model's own memory of what it
311# said. Scoped to read_page only: most tools' results are either already
312# small (a single record) or not the kind of thing a later turn needs to
313# resolve a vague reference against.
314READER_LINKS_ECHO_CAP = 40
315
316
317def _tool_result_summary(name: str, response: Any) -> dict[str, Any] | None:
318 """A bounded, caller-facing echo of read_page's real result, or None
319 for every other tool (including a read_page call that returned no
320 usable links). Not persisted server-side -- the caller (Talk) owns
321 carrying this forward on later turns, the same way it already owns
322 aiHistory; the server stays stateless about chats either way.
323 """
324 if name != "read_page" or not isinstance(response, dict):
325 return None
326 links = response.get("links")
327 if not isinstance(links, list) or not links:
328 return None
329 return {
330 "final_url": response.get("final_url"),
331 "title": response.get("title"),
332 "links": links[:READER_LINKS_ECHO_CAP],
333 }
334
335
336def run_chat(
337 *,
338 send_http: SendHttp,
339 dispatch_tool: DispatchTool,
340 service: str,
341 model: str,
342 key: str,
343 message: str,
344 system: str | None = None,
345 tools: list[dict[str, Any]] | None = None,
346 history: list[dict[str, str]] | None = None,
347 attachments: list[dict[str, Any]] | None = None,
348 max_rounds: int = DEFAULT_MAX_ROUNDS,
349 max_tokens: int = DEFAULT_MAX_TOKENS,
350 context: str | None = None,
351 cache: bool = True,
352 effort: str | None = None,
353 stream: bool = False,
354 send_http_stream: SendHttpStream | None = None,
355 on_event: OnEvent | None = None,
356) -> dict[str, Any]:
357 """Run one chat turn, looping through tool calls until a final reply.
358
359 ``history`` is prior conversation turns ({"role": "user"|"assistant",
360 "content": ...}) so a caller can resume a conversation it logged —
361 the server itself stays stateless about chats.
362
363 ``system`` is the stable instruction text; ``context`` is per-request
364 system text that changes every turn (the local time, the last page
365 read). They are kept apart so the stable part can be cached: see
366 _AnthropicProvider.request.
367
368 ``effort`` is sent as ``output_config.effort`` only to models that
369 accept it (model_supports_effort); for any other model it is dropped,
370 never sent and refused.
371
372 ``stream`` asks Anthropic for server-sent events through
373 ``send_http_stream`` and reports text to ``on_event`` as it arrives.
374 Everything else -- the round loop, tool dispatch, stop handling, the
375 returned dict -- is the same code as a non-streamed turn. OpenAI turns
376 are not streamed from the provider: the whole reply is reported as one
377 text event when its round finishes.
378
379 Text events are a preview. A round that ends in refusal may already
380 have streamed words; the returned ``reply`` is the authoritative
381 answer and a caller shows it once the turn ends.
382 """
383 if not isinstance(message, str) or not message.strip():
384 raise InvalidChatRequestError("message is required")
385 if attachments and len(attachments) > MAX_ATTACHMENTS_PER_TURN:
386 raise InvalidChatRequestError(
387 f"{len(attachments)} attachments; the limit is "
388 f"{MAX_ATTACHMENTS_PER_TURN} per message."
389 )
390 rounds = max(1, min(int(max_rounds), MAX_ROUNDS_LIMIT))
391 if stream and service == "anthropic" and send_http_stream is None:
392 raise ValueError("stream=True needs send_http_stream")
393
394 def emit(kind: str, data: dict[str, Any]) -> None:
395 if on_event is not None:
396 on_event(kind, data)
397
398 if service == "anthropic":
399 if tools and model_supports_strict_tools(service, model):
400 tools = with_strict_tools(tools)
401 provider = _AnthropicProvider(
402 key, model, system, tools or [], max_tokens, context=context, cache=cache,
403 effort=effort if effort and model_supports_effort(service, model) else None,
404 )
405 else:
406 provider = _OpenAIProvider(key, model, _join_system(system, context),
407 tools or [], max_tokens)
408
409 for turn in normalize_history(history):
410 provider.messages.append(turn)
411 provider.start(message.strip(), attachments or None)
412 tool_log: list[dict[str, Any]] = []
413 usage = new_usage()
414
415 def finish(parsed, rounds_used, reply, **extra):
416 result = {
417 "reply": reply,
418 "rounds": rounds_used,
419 "tool_calls": tool_log,
420 "usage": usage,
421 "stop_reason": parsed.get("stop_reason"),
422 }
423 result.update(extra)
424 return result
425
426 streaming_provider = stream and service == "anthropic"
427 for round_index in range(rounds):
428 if streaming_provider:
429 status, lines = send_http_stream(*provider.request(stream=True))
430 parsed = provider.parse_stream(status, lines,
431 lambda text: emit("text", {"text": text}))
432 else:
433 status, body = send_http(*provider.request())
434 parsed = provider.parse(status, body)
435 if stream and parsed["text"]:
436 emit("text", {"text": parsed["text"]})
437 add_usage(usage, parsed["usage"])
438
439 # stop_reason is read BEFORE the content. A refusal's content is
440 # not an answer, and a max_tokens stop can end inside a tool call
441 # whose input is incomplete -- running that tool would act on
442 # arguments the model never finished writing.
443 stop_reason = parsed.get("stop_reason")
444 if stop_reason == "refusal":
445 details = parsed.get("stop_details") or {}
446 refusal = {"category": details.get("category"),
447 "explanation": details.get("explanation")}
448 return finish(parsed, round_index + 1, refusal_message(refusal), refusal=refusal)
449 if stop_reason == "max_tokens":
450 return finish(parsed, round_index + 1,
451 cut_off_message(parsed["text"], provider.max_tokens), cut_off=True)
452 if stop_reason == "pause_turn":
453 # The provider paused a long turn and expects the paused
454 # content sent back as-is to resume it. No tool runs here;
455 # the resumed round may still ask for tools.
456 provider.resume_paused(parsed)
457 continue
458
459 if not parsed["tool_calls"]:
460 return finish(parsed, round_index + 1, parsed["text"])
461
462 results = []
463 for call in parsed["tool_calls"]:
464 if call.get("invalid"):
465 # Streamed input that did not assemble into a JSON object.
466 # Never dispatched: the model gets an error result naming
467 # the problem and may retry in the next round.
468 result = {"http_status": 400, "is_error": True,
469 "response": {"error": f"Tool input was not usable: {call['invalid']}"}}
470 else:
471 result = dispatch_tool(call["name"], call["arguments"])
472 entry = {
473 "name": call["name"],
474 "arguments": call["arguments"],
475 "http_status": result.get("http_status"),
476 }
477 if call.get("invalid"):
478 entry["error"] = "invalid_arguments"
479 summary = _tool_result_summary(call["name"], result.get("response"))
480 if summary is not None:
481 entry["result"] = summary
482 tool_log.append(entry)
483 emit("tool_call", entry)
484 results.append((call, result))
485 provider.add_tool_results(parsed, results)
486
487 if parsed.get("stop_reason") == "pause_turn":
488 reply = (parsed["text"] + "\n\n" if parsed["text"] else "") + PAUSED_AT_LIMIT_NOTE
489 else:
490 reply = parsed["text"] or "(stopped after reaching the tool-call round limit)"
491 return finish(parsed, rounds, reply, truncated=True)
492
493
494PAUSED_AT_LIMIT_NOTE = (
495 "(The model paused a long-running turn and the round limit was reached "
496 "before it finished. Ask it to continue.)"
497)
498
499
500def refusal_message(refusal: dict[str, Any]) -> str:
501 """What the user reads when the model declines. Names the provider's
502 category and explanation when it gave them, so "it said no" is not
503 mistaken for "it broke"."""
504 message = "The model declined to answer this request"
505 category = refusal.get("category")
506 explanation = refusal.get("explanation")
507 if category:
508 message += f" ({category})"
509 if explanation:
510 return f"{message}: {explanation}"
511 return message + "."
512
513
514def cut_off_message(text: str, max_tokens: int) -> str:
515 """The partial answer plus a plain note that it was cut, so a reply
516 that stops mid-sentence is never taken for a complete one."""
517 note = (f"(The answer was cut off at the {max_tokens}-token output limit. "
518 "Ask for the rest, or for a shorter answer.)")
519 return f"{text}\n\n{note}" if text else note
520
521
522def iter_sse(lines: Iterable[bytes]) -> Iterator[tuple[str, str]]:
523 """(event, data) pairs from server-sent-event byte lines.
524
525 Framing per the SSE format: ``event:`` and ``data:`` fields, multiple
526 data lines joined by newlines, a blank line ends an event, and lines
527 starting with ``:`` are comments. Bytes are decoded per line; a line
528 split across reads is the transport's job to deliver whole (urllib's
529 response iterator does).
530 """
531 event = ""
532 data: list[str] = []
533 for raw in lines:
534 line = raw.decode("utf-8").rstrip("\r\n")
535 if not line:
536 if data:
537 yield event or "message", "\n".join(data)
538 event, data = "", []
539 continue
540 if line.startswith(":"):
541 continue
542 field, _, value = line.partition(":")
543 if value.startswith(" "):
544 value = value[1:]
545 if field == "event":
546 event = value
547 elif field == "data":
548 data.append(value)
549 if data:
550 yield event or "message", "\n".join(data)
551
552
553def _tool_input_from_json(raw: str) -> tuple[dict[str, Any], str | None]:
554 """A finished tool block's assembled JSON -> (input, problem)."""
555 if not raw.strip():
556 return {}, None # a tool with no arguments streams no fragments
557 try:
558 value = json.loads(raw)
559 except json.JSONDecodeError:
560 return {}, "the streamed arguments were not valid JSON"
561 if not isinstance(value, dict):
562 return {}, "the streamed arguments were not a JSON object"
563 return value, None
564
565
566USAGE_TOKEN_KEYS = (
567 "input_tokens",
568 "output_tokens",
569 "cache_creation_input_tokens",
570 "cache_read_input_tokens",
571)
572
573
574def new_usage() -> dict[str, int]:
575 """A turn's running token totals, summed over its provider rounds.
576
577 Anthropic reports cached prompt tokens BESIDE ``input_tokens``, not
578 inside it: ``input_tokens`` is only the uncached part, so a turn that
579 hits the cache reports a small ``input_tokens`` and a large
580 ``cache_read_input_tokens``. Summing only the first two keys (all this
581 did before prompt caching) would make a cached turn look nearly free.
582
583 ``largest_prompt_tokens`` is the biggest single round's whole prompt
584 (uncached + cache read + cache write). It is not a sum: a price that
585 changes above a prompt size applies per request, so it is the largest
586 request, not the turn's total, that decides whether a turn crossed it.
587 """
588 usage = {key: 0 for key in USAGE_TOKEN_KEYS}
589 usage["largest_prompt_tokens"] = 0
590 return usage
591
592
593def add_usage(total: dict[str, int], round_usage: dict[str, Any]) -> None:
594 values = {key: int(round_usage.get(key) or 0) for key in USAGE_TOKEN_KEYS}
595 for key, value in values.items():
596 total[key] += value
597 prompt = (values["input_tokens"] + values["cache_creation_input_tokens"]
598 + values["cache_read_input_tokens"])
599 total["largest_prompt_tokens"] = max(total["largest_prompt_tokens"], prompt)
600
601
602MAX_HISTORY_TURNS = 40
603
604
605def normalize_history(history: list[dict[str, str]] | None) -> list[dict[str, str]]:
606 """Validate and trim prior turns to plain user/assistant text messages."""
607 if history is None:
608 return []
609 if not isinstance(history, list):
610 raise InvalidChatRequestError("history must be a list of {role, content} turns")
611 turns = []
612 for item in history:
613 if not isinstance(item, dict):
614 raise InvalidChatRequestError("history turns must be objects")
615 role = item.get("role")
616 content = item.get("content")
617 if role not in ("user", "assistant") or not isinstance(content, str) or not content.strip():
618 raise InvalidChatRequestError(
619 "history turns need role user|assistant and non-empty content"
620 )
621 turns.append({"role": role, "content": content.strip()})
622 return turns[-MAX_HISTORY_TURNS:]
623
624
625# === chat attachments ========================================================
626#
627# A dropped file becomes a provider-neutral PART here, and the split of
628# labour is the point: the SERVER resolves file ids to bytes (permissions,
629# ownership, reading the blob -- all I/O), while this module classifies and
630# formats -- pure, testable without a data directory, like everything else
631# in it. run_chat then renders parts per provider, because Anthropic wants
632# a content array with base64 image blocks and OpenAI wants data: URLs,
633# and neither difference belongs anywhere near the caller.
634
635MAX_ATTACHMENTS_PER_TURN = 8
636MAX_IMAGE_BYTES = 5 * 1024 * 1024 # both providers cap around here
637MAX_TEXT_BYTES = 200 * 1024 # ~50k tokens of context is plenty
638
639IMAGE_MEDIA_TYPES = ("image/png", "image/jpeg", "image/gif", "image/webp")
640TEXTUAL_CONTENT_TYPES = (
641 "application/json", "application/xml", "application/x-yaml",
642 "application/csv", "application/javascript", "application/sql",
643)
644
645
646def attachment_part(filename: str, content_type: str, data: bytes) -> dict[str, Any]:
647 """Classify one file's bytes into a chat part, or refuse by name.
648
649 Images pass through as base64 for the provider's vision input; anything
650 that reads as text is inlined as text. Everything else is refused with
651 a message that says what IS supported -- a binary the model cannot see
652 must fail here, loudly, rather than arrive as mojibake the model
653 hallucinates an interpretation of. That silent path is the whole
654 reason this function exists as a gate rather than a best-effort
655 decoder.
656 """
657 import base64
658
659 name = str(filename or "file")
660 ctype = str(content_type or "").split(";")[0].strip().lower()
661
662 if ctype in IMAGE_MEDIA_TYPES:
663 if len(data) > MAX_IMAGE_BYTES:
664 raise InvalidChatRequestError(
665 f"{name}: image is {len(data) // 1024}KB; the limit is "
666 f"{MAX_IMAGE_BYTES // 1024}KB. Resize it before attaching."
667 )
668 return {"kind": "image", "name": name, "media_type": ctype,
669 "data_b64": base64.b64encode(data).decode("ascii")}
670
671 looks_textual = (
672 ctype.startswith("text/")
673 or ctype in TEXTUAL_CONTENT_TYPES
674 or ctype.endswith("+json") or ctype.endswith("+xml")
675 )
676 if not looks_textual:
677 try:
678 data.decode("utf-8")
679 looks_textual = True # honest text under a lazy MIME type
680 except UnicodeDecodeError:
681 looks_textual = False
682 if looks_textual:
683 if len(data) > MAX_TEXT_BYTES:
684 raise InvalidChatRequestError(
685 f"{name}: text file is {len(data) // 1024}KB; the limit is "
686 f"{MAX_TEXT_BYTES // 1024}KB. Attach an excerpt instead."
687 )
688 try:
689 text = data.decode("utf-8")
690 except UnicodeDecodeError as exc:
691 raise InvalidChatRequestError(
692 f"{name}: declared {ctype or 'text'} but is not valid UTF-8."
693 ) from exc
694 return {"kind": "text", "name": name, "text": text}
695
696 raise InvalidChatRequestError(
697 f"{name}: cannot attach {ctype or 'unknown'} to a chat. Supported: "
698 f"images ({', '.join(IMAGE_MEDIA_TYPES)}) and text-like files "
699 f"(anything UTF-8). PDFs and other binaries need their text "
700 f"extracted first."
701 )
702
703
704def _content_with_parts_anthropic(message: str, parts: list[dict[str, Any]]):
705 content: list[dict[str, Any]] = []
706 for part in parts:
707 if part["kind"] == "image":
708 content.append({"type": "image", "source": {
709 "type": "base64", "media_type": part["media_type"],
710 "data": part["data_b64"]}})
711 else:
712 content.append({"type": "text",
713 "text": f"[file: {part['name']}]\n{part['text']}"})
714 content.append({"type": "text", "text": message})
715 return content
716
717
718def _content_with_parts_openai(message: str, parts: list[dict[str, Any]]):
719 content: list[dict[str, Any]] = []
720 for part in parts:
721 if part["kind"] == "image":
722 content.append({"type": "image_url", "image_url": {
723 "url": f"data:{part['media_type']};base64,{part['data_b64']}"}})
724 else:
725 content.append({"type": "text",
726 "text": f"[file: {part['name']}]\n{part['text']}"})
727 content.append({"type": "text", "text": message})
728 return content
729
730
731def _join_system(system: str | None, context: str | None) -> str | None:
732 joined = "\n\n".join(part for part in (system, context) if part)
733 return joined or None
734
735
736# Prompt caching. A request renders as tools -> system -> messages, and a
737# cache entry is a PREFIX of that: anything that differs between two
738# requests ends the shared prefix at that point. So the breakpoints go on
739# the parts that are the same turn after turn -- the last tool definition
740# and the stable system text -- and the volatile per-request text
741# (``context``: the local time, the last page read) is a separate system
742# block AFTER the cached one. Before this, the shell put the current time
743# at the end of its system string, which would have made every request's
744# system text unique and every cache write a wasted 25% surcharge.
745#
746# Why explicit breakpoints and not the simpler top-level cache_control
747# (which caches up to the last cacheable block): the last block of a turn
748# is the new user message, and the next turn's history carries that
749# message as plain text without its context, so the prefix written at the
750# end of one turn is not the prefix the next turn sends. Every turn would
751# pay a cache write over the whole conversation and rarely read it back.
752# tools + system is the part that IS identical every turn.
753#
754# A prefix shorter than the model's minimum cacheable length is simply not
755# cached -- no error, cache token counts stay 0.
756CACHE_CONTROL = {"type": "ephemeral"}
757
758
759class _AnthropicProvider:
760 def __init__(self, key, model, system, tools, max_tokens, *, context=None, cache=True,
761 effort=None):
762 self.key = key
763 self.effort = effort
764 self.model = model
765 self.system = system
766 self.context = context
767 self.cache = cache
768 self.tools = tools
769 self.max_tokens = max_tokens
770 self.messages: list[dict[str, Any]] = []
771
772 def _system_blocks(self) -> list[dict[str, Any]]:
773 blocks: list[dict[str, Any]] = []
774 if self.system:
775 block: dict[str, Any] = {"type": "text", "text": self.system}
776 if self.cache:
777 block["cache_control"] = dict(CACHE_CONTROL)
778 blocks.append(block)
779 if self.context:
780 blocks.append({"type": "text", "text": self.context})
781 return blocks
782
783 def _tool_definitions(self) -> list[dict[str, Any]]:
784 tools = [dict(tool) for tool in self.tools]
785 if tools and self.cache:
786 tools[-1]["cache_control"] = dict(CACHE_CONTROL)
787 return tools
788
789 def start(self, message: str, parts: list[dict[str, Any]] | None = None) -> None:
790 # A plain string when there are no parts, so a text-only chat's
791 # outbound payload is byte-identical to what it always was.
792 content = (_content_with_parts_anthropic(message, parts)
793 if parts else message)
794 self.messages.append({"role": "user", "content": content})
795
796 def request(self, stream: bool = False) -> tuple[str, dict[str, str], bytes]:
797 payload: dict[str, Any] = {
798 "model": self.model,
799 "max_tokens": self.max_tokens,
800 "messages": self.messages,
801 }
802 if stream:
803 payload["stream"] = True
804 # Inside output_config, not top level. Temperature, top_p, top_k
805 # and a thinking budget are never sent: current models think
806 # adaptively by default and refuse those fields when not default.
807 if self.effort:
808 payload["output_config"] = {"effort": self.effort}
809 system_blocks = self._system_blocks()
810 if system_blocks:
811 payload["system"] = system_blocks
812 if self.tools:
813 payload["tools"] = self._tool_definitions()
814 headers = {
815 "x-api-key": self.key,
816 "anthropic-version": ANTHROPIC_VERSION,
817 "content-type": "application/json",
818 }
819 return ANTHROPIC_URL, headers, json.dumps(payload).encode("utf-8")
820
821 def parse(self, status: int, body: bytes) -> dict[str, Any]:
822 return self._parsed(_json_or_error(status, body), invalid={})
823
824 def parse_stream(self, status: int, lines: Iterable[bytes],
825 on_text: Callable[[str], None]) -> dict[str, Any]:
826 """Assemble a streamed message into the same dict parse() returns.
827
828 Text deltas go to ``on_text`` as they arrive. Tool input arrives
829 as partial JSON fragments and is parsed only when its block stops:
830 a fragment is not JSON on its own, and a tool must never run on
831 arguments the model has not finished writing. Input that does not
832 parse into an object marks the call invalid instead of guessing.
833 Thinking blocks are rebuilt with their signature, because they are
834 sent back unchanged with the next round's tool results.
835 """
836 if status >= 400:
837 _json_or_error(status, b"".join(lines)) # raises with the provider's message
838 raise AIProviderError(f"Provider error (HTTP {status})")
839 message: dict[str, Any] = {"content": [], "usage": {}}
840 blocks: dict[int, dict[str, Any]] = {}
841 partial_json: dict[int, list[str]] = {}
842 invalid: dict[str, str] = {}
843 finished = False
844 for event, data in iter_sse(lines):
845 try:
846 payload = json.loads(data)
847 except json.JSONDecodeError as exc:
848 raise AIProviderError("Provider stream sent an unreadable event") from exc
849 kind = payload.get("type") or event
850 if kind == "message_start":
851 started = payload.get("message") or {}
852 message["usage"] = dict(started.get("usage") or {})
853 elif kind == "content_block_start":
854 index = payload.get("index", len(blocks))
855 block = dict(payload.get("content_block") or {})
856 blocks[index] = block
857 if block.get("type") == "tool_use":
858 partial_json[index] = []
859 elif block.get("type") == "text" and block.get("text"):
860 on_text(block["text"])
861 elif kind == "content_block_delta":
862 index = payload.get("index")
863 block = blocks.get(index)
864 delta = payload.get("delta") or {}
865 if block is None:
866 continue
867 delta_type = delta.get("type")
868 if delta_type == "text_delta":
869 piece = delta.get("text") or ""
870 block["text"] = (block.get("text") or "") + piece
871 if piece:
872 on_text(piece)
873 elif delta_type == "input_json_delta":
874 partial_json.setdefault(index, []).append(delta.get("partial_json") or "")
875 elif delta_type == "thinking_delta":
876 block["thinking"] = (block.get("thinking") or "") + (delta.get("thinking") or "")
877 elif delta_type == "signature_delta":
878 block["signature"] = delta.get("signature")
879 elif kind == "content_block_stop":
880 index = payload.get("index")
881 block = blocks.get(index)
882 if block is not None and block.get("type") == "tool_use":
883 raw = "".join(partial_json.pop(index, []))
884 block["input"], problem = _tool_input_from_json(raw)
885 if problem:
886 invalid[str(block.get("id"))] = problem
887 elif kind == "message_delta":
888 delta = payload.get("delta") or {}
889 if "stop_reason" in delta:
890 message["stop_reason"] = delta.get("stop_reason")
891 if delta.get("stop_details") is not None:
892 message["stop_details"] = delta.get("stop_details")
893 if payload.get("stop_details") is not None:
894 message["stop_details"] = payload.get("stop_details")
895 # message_delta usage values are cumulative for the
896 # message, so they replace message_start's, not add to them.
897 message["usage"].update(payload.get("usage") or {})
898 elif kind == "message_stop":
899 finished = True
900 break
901 elif kind == "error":
902 detail = payload.get("error") or {}
903 if isinstance(detail, dict):
904 detail = detail.get("message") or json.dumps(detail)
905 raise AIProviderError(f"Provider error (stream): {str(detail)[:300]}")
906 if not finished:
907 raise AIProviderError("Provider stream ended before the message was complete")
908 # A block still open at the end never stopped; its input is unfinished.
909 for index in list(partial_json):
910 block = blocks[index]
911 block["input"] = {}
912 invalid[str(block.get("id"))] = "the stream ended before the input was complete"
913 message["content"] = [blocks[index] for index in sorted(blocks)]
914 return self._parsed(message, invalid=invalid)
915
916 def _parsed(self, payload: dict[str, Any], *, invalid: dict[str, str]) -> dict[str, Any]:
917 content = payload.get("content") or []
918 text_parts = [item.get("text", "") for item in content if item.get("type") == "text"]
919 tool_calls = []
920 for item in content:
921 if item.get("type") != "tool_use":
922 continue
923 call = {
924 "id": item.get("id"),
925 "name": item.get("name"),
926 "arguments": item.get("input") or {},
927 }
928 if str(item.get("id")) in invalid:
929 call["invalid"] = invalid[str(item.get("id"))]
930 tool_calls.append(call)
931 raw_usage = payload.get("usage") or {}
932 self._last_content = content
933 return {
934 "stop_reason": payload.get("stop_reason"),
935 "stop_details": payload.get("stop_details"),
936 "text": "\n".join(part for part in text_parts if part),
937 "tool_calls": tool_calls,
938 "usage": {
939 "input_tokens": raw_usage.get("input_tokens") or 0,
940 "output_tokens": raw_usage.get("output_tokens") or 0,
941 "cache_creation_input_tokens":
942 raw_usage.get("cache_creation_input_tokens") or 0,
943 "cache_read_input_tokens": raw_usage.get("cache_read_input_tokens") or 0,
944 },
945 }
946
947 def resume_paused(self, parsed) -> None:
948 self.messages.append({"role": "assistant", "content": self._last_content})
949
950 def add_tool_results(self, parsed, results) -> None:
951 self.messages.append({"role": "assistant", "content": self._last_content})
952 result_blocks = []
953 for call, result in results:
954 block = {
955 "type": "tool_result",
956 "tool_use_id": call["id"],
957 "content": json.dumps(result.get("response"), default=str)[:8000],
958 }
959 if result.get("is_error"):
960 block["is_error"] = True
961 result_blocks.append(block)
962 self.messages.append({"role": "user", "content": result_blocks})
963
964
965class _OpenAIProvider:
966 def __init__(self, key, model, system, tools, max_tokens):
967 self.key = key
968 self.model = model
969 self.tools = tools
970 self.max_tokens = max_tokens
971 self.messages: list[dict[str, Any]] = []
972 if system:
973 self.messages.append({"role": "system", "content": system})
974
975 def start(self, message: str, parts: list[dict[str, Any]] | None = None) -> None:
976 content = (_content_with_parts_openai(message, parts)
977 if parts else message)
978 self.messages.append({"role": "user", "content": content})
979
980 def request(self) -> tuple[str, dict[str, str], bytes]:
981 payload: dict[str, Any] = {
982 "model": self.model,
983 "messages": self.messages,
984 "max_completion_tokens": self.max_tokens,
985 }
986 if self.tools:
987 payload["tools"] = self.tools
988 if self.model in _REASONING_EFFORT_NONE_MODELS:
989 payload["reasoning_effort"] = "none"
990 headers = {
991 "authorization": f"Bearer {self.key}",
992 "content-type": "application/json",
993 }
994 return OPENAI_URL, headers, json.dumps(payload).encode("utf-8")
995
996 def parse(self, status: int, body: bytes) -> dict[str, Any]:
997 payload = _json_or_error(status, body)
998 choices = payload.get("choices") or []
999 if not choices:
1000 raise AIProviderError("Provider returned no choices")
1001 message = choices[0].get("message") or {}
1002 finish_reason = choices[0].get("finish_reason")
1003 raw_calls = message.get("tool_calls") or []
1004 tool_calls = []
1005 for item in raw_calls:
1006 function = item.get("function") or {}
1007 try:
1008 arguments = json.loads(function.get("arguments") or "{}")
1009 except json.JSONDecodeError:
1010 arguments = {}
1011 tool_calls.append(
1012 {"id": item.get("id"), "name": function.get("name"), "arguments": arguments}
1013 )
1014 raw_usage = payload.get("usage") or {}
1015 self._last_message = message
1016 return {
1017 # "length" is OpenAI's name for running out of output tokens;
1018 # mapped so the shared loop gives both providers the same
1019 # cut-off handling.
1020 "stop_reason": "max_tokens" if finish_reason == "length" else finish_reason,
1021 "text": message.get("content") or "",
1022 "tool_calls": tool_calls,
1023 "usage": {
1024 "input_tokens": raw_usage.get("prompt_tokens", 0),
1025 "output_tokens": raw_usage.get("completion_tokens", 0),
1026 },
1027 }
1028
1029 def add_tool_results(self, parsed, results) -> None:
1030 self.messages.append(self._last_message)
1031 for call, result in results:
1032 self.messages.append(
1033 {
1034 "role": "tool",
1035 "tool_call_id": call["id"],
1036 "content": json.dumps(result.get("response"), default=str)[:8000],
1037 }
1038 )
1039
1040
1041def select_price_row(
1042 rows: list[dict[str, Any]], *, provider: str, model: str
1043) -> dict[str, Any] | None:
1044 """Pick the most recent ai_prices row for (provider, model), or None.
1045
1046 "Most recent" is the matching row with the greatest ``effective_date``
1047 (ISO 8601 strings sort lexicographically). Prices are ordinary records —
1048 editable live, never hardcoded — so a missing row is expected, not an
1049 error; the caller decides what that means (it records tokens with a
1050 null cost rather than failing the chat).
1051 """
1052 candidates = [
1053 row for row in rows if row.get("provider") == provider and row.get("model") == model
1054 ]
1055 if not candidates:
1056 return None
1057 return max(candidates, key=lambda row: row.get("effective_date") or "")
1058
1059
1060def _optional_rate(price_row: dict[str, Any], field: str) -> int | None:
1061 """A per-million rate from a price row, or None when the cell is blank.
1062
1063 Blank means "not known", never zero: a cache price nobody has entered
1064 must not price cache tokens as free.
1065 """
1066 raw = price_row.get(field)
1067 if raw is None or str(raw).strip() == "":
1068 return None
1069 return int(raw)
1070
1071
1072def compute_cost_cents(
1073 tokens_in: int,
1074 tokens_out: int,
1075 price_row: dict[str, Any] | None,
1076 *,
1077 cache_read_tokens: int = 0,
1078 cache_write_tokens: int = 0,
1079 largest_prompt_tokens: int = 0,
1080) -> int | None:
1081 """Integer-cent cost for a turn, or None when it cannot be priced.
1082
1083 Money math stays in integer cents throughout: sum the raw
1084 tokens*per_million_cents products for every kind of token first, then
1085 floor once -- never a float division on money. Flooring each side
1086 separately before summing (the previous approach) silently
1087 undercounts cheap models: e.g. gpt-5-mini at 25c/M input, 200c/M
1088 output floors a 36,428-token call to 0+0=0c even though the combined
1089 cost is a real ~1c.
1090
1091 None (cost unknown; the caller still records the tokens) when:
1092
1093 - there is no price row for the model;
1094 - the turn read or wrote prompt cache and the row's matching cache
1095 rate is blank. Cache tokens are billed at their own rates, and a
1096 guessed rate is a wrong number stamped as a fact;
1097 - the row sets ``price_max_prompt_tokens`` and one round's whole
1098 prompt went over it. Some models charge a higher rate above a
1099 prompt size (Claude Haiku 5.5 above 100K tokens); this table holds
1100 one rate per row, so a turn past the line is unpriced rather than
1101 priced at the lower rate.
1102 """
1103 if price_row is None:
1104 return None
1105 input_rate = int(price_row.get("input_per_million_cents") or 0)
1106 output_rate = int(price_row.get("output_per_million_cents") or 0)
1107 total = tokens_in * input_rate + tokens_out * output_rate
1108 for tokens, field in (
1109 (cache_read_tokens, "cache_read_per_million_cents"),
1110 (cache_write_tokens, "cache_write_per_million_cents"),
1111 ):
1112 if not tokens:
1113 continue
1114 rate = _optional_rate(price_row, field)
1115 if rate is None:
1116 return None
1117 total += tokens * rate
1118 prompt_limit = _optional_rate(price_row, "price_max_prompt_tokens")
1119 if prompt_limit is not None and largest_prompt_tokens > prompt_limit:
1120 return None
1121 return total // 1_000_000
1122
1123
1124def cost_cents_for_usage(
1125 usage: dict[str, Any], price_row: dict[str, Any] | None
1126) -> int | None:
1127 """compute_cost_cents for a run_chat ``usage`` dict."""
1128 return compute_cost_cents(
1129 int(usage.get("input_tokens") or 0),
1130 int(usage.get("output_tokens") or 0),
1131 price_row,
1132 cache_read_tokens=int(usage.get("cache_read_input_tokens") or 0),
1133 cache_write_tokens=int(usage.get("cache_creation_input_tokens") or 0),
1134 largest_prompt_tokens=int(usage.get("largest_prompt_tokens") or 0),
1135 )
1136
1137
1138def _json_or_error(status: int, body: bytes) -> dict[str, Any]:
1139 try:
1140 payload = json.loads(body.decode("utf-8"))
1141 except (UnicodeDecodeError, json.JSONDecodeError) as exc:
1142 raise AIProviderError(f"Provider returned unreadable response (HTTP {status})") from exc
1143 if status >= 400:
1144 detail = payload.get("error")
1145 if isinstance(detail, dict):
1146 detail = detail.get("message") or json.dumps(detail)
1147 raise AIProviderError(f"Provider error (HTTP {status}): {str(detail)[:300]}")
1148 if not isinstance(payload, dict):
1149 raise AIProviderError("Provider returned a non-object response")
1150 return payload