Coverage for app / services / reply_formats / __init__.py: 96%
288 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""How each model's reply carries its answer — one class per wire behaviour.
3A model's reply can hold more than the answer the person should read:
5* typed reasoning blocks — Claude's ``thinking`` / ``redacted_thinking``,
6 Bedrock's ``reasoning_content``, OpenAI's ``reasoning`` items;
7* OpenAI Responses text in the ``commentary`` phase — the model's preamble
8 ("I'll look that up…"), as a ``text`` block like the answer's;
9* reasoning written inline between tags (``<think>…</think>``);
10* gpt-oss's analysis channel returned as ordinary text, run straight into the
11 answer ("…Now produce final answer.Here’s a quick roundup…") — what
12 Bedrock's Converse API sends for gpt-oss-120b;
13* DeepSeek's own tool-call markup left in a tool turn's text.
15Every place that reads a model's reply reads it through the reply's format,
16chosen from the model that wrote it (``ModelCapabilities.reply_format``, per
17route): the tool loop, an answer without tools, continuations, memory
18summaries, direct model chat, the trace, and the live stream
19(:meth:`ReplyFormat.stream`, whose filter applies the same rule as
20:meth:`ReplyFormat.answer`, so what streams is what is stored).
22Adding a wire behaviour is one class registered with :func:`register` and
23one ``reply_format`` value in ``model_capabilities``; ``tests/services/
24test_reply_formats.py`` fails on a key with no class.
25"""
27from __future__ import annotations
29from abc import ABC
30from dataclasses import dataclass, field
31from typing import Any, ClassVar, Iterable, get_args
33from app.services import model_capabilities
34from app.services.reply_formats import cleaning
35from app.util.logger import get_logger
37logger = get_logger(__name__)
39#: The block types whose text is the reply's (Chat Completions and Converse
40#: write ``text``; the Responses API ``output_text`` in its raw items).
41_TEXT_TYPES = frozenset({"text", "output_text"})
42#: The Responses API phase that holds the model's preamble, not its answer.
43COMMENTARY = "commentary"
45#: Tag on a model call whose text is the pipeline's, never the person's — a
46#: memory summary. ``graph_based._stream_graph`` streams none of its tokens,
47#: as it streams none of a structured call's (``STRUCTURED_OUTPUT_TAG``).
48UNSTREAMED_TAG = "chainr:unstreamed"
51# ---------------------------------------------------------------------------
52# What a read finds
53# ---------------------------------------------------------------------------
56@dataclass(frozen=True)
57class Reply:
58 """A reply read through its format."""
60 #: What the person reads.
61 answer: str
62 #: How it was told apart: ``text`` (nothing removed), ``harmony``,
63 #: ``envelope``, ``tags``, ``seam``, ``dsml`` (DeepSeek's tool-call
64 #: markup), ``commentary`` (a reply that was
65 #: all preamble, kept rather than delivering nothing) or ``json`` (a
66 #: reply asked for as JSON that parsed whole, passed as it is: the
67 #: model engine's ``_answer``).
68 path: str = "text"
69 #: Characters left out.
70 removed: int = 0
73@dataclass(frozen=True)
74class Emit:
75 """Stream this text."""
77 text: str
80@dataclass(frozen=True)
81class Reset:
82 """Take back what this node has streamed since it started or was last
83 reset (the ``token_reset`` frame)."""
86StreamOp = Emit | Reset
89@dataclass
90class _Parts:
91 """A reply's text so far, split by what it is: the answer's text and the
92 commentary-phase text. A streamed block names its phase only on its first
93 chunk (``response.output_item.added``), so the phase is kept per block
94 index."""
96 text: list[str] = field(default_factory=list)
97 commentary: list[str] = field(default_factory=list)
98 phases: dict[Any, str] = field(default_factory=dict)
100 def add(self, content: Any) -> None:
101 if isinstance(content, str):
102 self.text.append(content)
103 return
104 for block in content or []:
105 if isinstance(block, str):
106 self.text.append(block)
107 continue
108 if not isinstance(block, dict):
109 continue
110 index = block.get("index")
111 if block.get("phase"):
112 self.phases[index] = str(block["phase"])
113 kind = block.get("type")
114 if kind is not None and kind not in _TEXT_TYPES:
115 continue
116 text = block.get("text")
117 if not isinstance(text, str) or not text:
118 continue
119 phase = block.get("phase") or self.phases.get(index)
120 (self.commentary if phase == COMMENTARY else self.text).append(text)
122 def joined(self) -> str:
123 return "".join(self.text)
125 def preamble(self) -> str:
126 return "".join(self.commentary)
129def text_of(content: Any) -> str:
130 """The reply text in a message's ``content``: ``text`` blocks only,
131 joined as written (a provider splits one answer into adjacent blocks —
132 Claude around each citation — so a separator would land mid-sentence),
133 leaving out every reasoning block and commentary-phase text."""
134 parts = _Parts()
135 parts.add(content)
136 return parts.joined()
139def _parts_of(content: Any) -> _Parts:
140 parts = _Parts()
141 parts.add(content)
142 return parts
145# ---------------------------------------------------------------------------
146# Formats
147# ---------------------------------------------------------------------------
150class ReplyFormat(ABC):
151 """How one wire behaviour carries a reply's answer."""
153 key: ClassVar[str]
155 def answer(self, text: str) -> Reply:
156 """The answer in ``text``, a reply already reduced to its text."""
157 return Reply(text.strip())
159 def reply(self, message: Any) -> Reply:
160 """The answer in a whole message."""
161 parts = _parts_of(getattr(message, "content", message))
162 found = self.answer(parts.joined())
163 if found.answer or getattr(message, "tool_calls", None):
164 return found
165 preamble = parts.preamble().strip()
166 if not preamble:
167 return found
168 # A tool-free reply that is all commentary: delivering it beats
169 # delivering nothing, and it is said in the log.
170 logger.warning(
171 "[reply:%s] a final reply held only commentary-phase text; kept it",
172 self.key,
173 )
174 return Reply(self.answer(preamble).answer, "commentary", 0)
176 def contract(self) -> str:
177 """What the system prompt tells the model about where its reply goes;
178 empty for every format that needs nothing."""
179 return ""
181 def wrap_history(self, text: str) -> str:
182 """An earlier answer as it is replayed to the model."""
183 return text
185 def tool_turn_answer(self, tool_turns: list[str]) -> str:
186 """The answer when the last, tool-free message is empty, from the text
187 of the turns that called tools — a GPT-style model sometimes answers
188 beside its last tool call."""
189 return _join([self.answer(text).answer for text in tool_turns])
191 def stream(self, *, keeps_tool_turn_text: bool) -> StreamFilter:
192 return StreamFilter(self, keeps_tool_turn_text=keeps_tool_turn_text)
194 #: Tags this format reads: a reply that ends with the start of one holds
195 #: it back while streaming, until it is known to be one or not.
196 tags: ClassVar[tuple[str, ...]] = ()
198 #: Whether the model is told to write its reply in the envelope, so a
199 #: reply read without one is worth a warning.
200 expects_envelope: ClassVar[bool] = False
202 def visible(self, text: str) -> str:
203 """What may be shown of ``text`` while the reply is still arriving:
204 the answer so far."""
205 return self.hold_partial_tag(self.answer(text).answer)
207 def hold_partial_tag(self, text: str) -> str:
208 """``text`` less a trailing ``<…`` that could still become one of
209 :attr:`tags`; any other ``<`` (``x < y``) is shown."""
210 at = text.rfind("<")
211 if at < 0 or not self.tags:
212 return text
213 tail = "".join(text[at:].split()).lower()
214 if any(tag.startswith(tail) for tag in self.tags):
215 return text[:at]
216 return text
219def _join(parts: Iterable[str]) -> str:
220 return "\n\n".join(p for p in (part.strip() for part in parts) if p)
223_REGISTRY: dict[str, ReplyFormat] = {}
226def register(cls: type[ReplyFormat]) -> type[ReplyFormat]:
227 """Class decorator adding one format to the registry."""
228 instance = cls()
229 if instance.key in _REGISTRY:
230 raise RuntimeError(f"Reply format '{instance.key}' is already registered.")
231 _REGISTRY[instance.key] = instance
232 return cls
235@register
236class Typed(ReplyFormat):
237 """The answer is the reply's ``text`` blocks: Anthropic, OpenAI (Chat
238 Completions and Responses) and Claude on Bedrock. Reasoning arrives in
239 blocks of its own and commentary in its own phase, both left out by
240 :func:`text_of`. A *leading* complete think block is removed too — a
241 model that writes one writes it first, and a later one is content."""
243 key = "typed"
245 def answer(self, text: str) -> Reply:
246 cleaned = cleaning.strip_tags(text, leading_only=True)
247 found = cleaned.strip()
248 if cleaned == text:
249 return Reply(found)
250 return Reply(found, "tags", len(text.strip()) - len(found))
252 def visible(self, text: str) -> str:
253 # A think block can only lead; until it might, show the text whole.
254 return text
257@register
258class InlineTags(ReplyFormat):
259 """Reasoning inline between ``<think>`` / ``<thinking>`` / ``<reasoning>``
260 tags, anywhere in the reply: open-weight models on Bedrock other than
261 gpt-oss (Qwen), Groq, and local servers."""
263 key = "inline_tags"
264 tags = cleaning.tag_spellings()
266 def answer(self, text: str) -> Reply:
267 found = cleaning.answer(text, use_envelope=False, use_seam=False)
268 return Reply(found.text, found.path, found.removed)
270 def visible(self, text: str) -> str:
271 # A block still open hides everything after its opener.
272 return self.hold_partial_tag(cleaning.strip_tags_so_far(text).strip())
275@register
276class Dsml(InlineTags):
277 """DeepSeek on Bedrock: reasoning between tags like any open-weight
278 model's, and its own tool-call markup (``<|DSML|function_calls``),
279 which Converse leaves in a tool turn's text beside the tool call it
280 parsed from it (the reply probe, 31 October 2026). The markup, and
281 everything after it, is the call, never answer."""
283 key = "dsml"
284 tags = InlineTags.tags + (cleaning.DSML_MARKER.lower(),)
286 def answer(self, text: str) -> Reply:
287 head = cleaning.strip_dsml(text)
288 found = super().answer(head)
289 if head == text:
290 return found
291 return Reply(found.answer, "dsml", len(text.strip()) - len(found.answer))
293 def visible(self, text: str) -> str:
294 return super().visible(cleaning.strip_dsml(text))
297@register
298class GptOss(ReplyFormat):
299 """gpt-oss, whose analysis channel can arrive as answer text.
301 The model is told to write its reply in an envelope
302 (:meth:`contract`), and the answer is the envelope's content
303 (``cleaning.envelope``: the last opener, up to its closer or the end).
304 A reply without one is cleaned of harmony markers, tagged blocks and a
305 seam, as a last resort, with a warning in the log. Nothing is shown while
306 the reply streams until the envelope opens, so the analysis never is."""
308 key = "gpt_oss"
309 tags = (cleaning.ENVELOPE_OPEN, cleaning.ENVELOPE_CLOSE)
310 expects_envelope = True
312 def answer(self, text: str) -> Reply:
313 found = cleaning.answer(text, use_envelope=True, use_seam=True)
314 return Reply(found.text, found.path, found.removed)
316 def contract(self) -> str:
317 from app import prompts
319 return prompts.REPLY_ENVELOPE_CONTRACT
321 def wrap_history(self, text: str) -> str:
322 return f"{cleaning.ENVELOPE_OPEN}{text}{cleaning.ENVELOPE_CLOSE}"
324 def tool_turn_answer(self, tool_turns: list[str]) -> str:
325 # Its tool-turn text is analysis; only a reply it closed there counts.
326 for text in reversed(tool_turns):
327 found = cleaning.complete_envelope(text)
328 if found:
329 return found
330 return ""
332 def visible(self, text: str) -> str:
333 inside = cleaning.envelope(text)
334 return "" if inside is None else self.hold_partial_tag(inside)
337# ---------------------------------------------------------------------------
338# The live stream
339# ---------------------------------------------------------------------------
342class StreamFilter:
343 """What one node's model calls may show as they stream.
345 ``feed`` takes each chunk's content and returns what to send: new text to
346 show, or a reset when what was shown is no longer the answer so far.
347 ``end`` closes a call: a call that called tools takes back its text
348 unless the model's tool-turn text is answer (Claude); a call cut off at
349 the token cap (``continues``) carries on into its continuation; any other
350 call ends on exactly what :meth:`ReplyFormat.answer` makes of it.
351 """
353 def __init__(self, fmt: ReplyFormat, *, keeps_tool_turn_text: bool) -> None:
354 self._fmt = fmt
355 self._keeps_tool_turn_text = keeps_tool_turn_text
356 self._parts = _Parts()
357 self._shown = ""
359 def feed(self, content: Any) -> list[StreamOp]:
360 self._parts.add(content)
361 return self._show(self._fmt.visible(self._parts.joined()))
363 def end(self, message: Any, *, continues: bool) -> list[StreamOp]:
364 if continues:
365 return []
366 if getattr(message, "tool_calls", None):
367 ops: list[StreamOp] = []
368 if not self._keeps_tool_turn_text and self._shown:
369 ops = [Reset()]
370 self._restart()
371 return ops
372 text = self._parts.joined()
373 final = self._fmt.answer(text).answer
374 if not final and not text.strip():
375 final = self._fmt.reply(message).answer if message is not None else ""
376 ops = self._settle(final)
377 self._restart()
378 return ops
380 def _restart(self) -> None:
381 self._parts = _Parts()
382 self._shown = ""
384 def _show(self, visible: str) -> list[StreamOp]:
385 if visible == self._shown:
386 return []
387 if visible.startswith(self._shown):
388 delta = visible[len(self._shown) :]
389 self._shown = visible
390 return [Emit(delta)]
391 ops: list[StreamOp] = [Reset()] if self._shown else []
392 self._shown = visible
393 if visible:
394 ops.append(Emit(visible))
395 return ops
397 def _settle(self, final: str) -> list[StreamOp]:
398 if self._shown.strip() == final.strip():
399 return []
400 ops: list[StreamOp] = [Reset()] if self._shown else []
401 if final:
402 ops.append(Emit(final))
403 return ops
406# ---------------------------------------------------------------------------
407# Choosing the format
408# ---------------------------------------------------------------------------
411@dataclass(frozen=True)
412class Reader:
413 """A format bound to what the model does with its tool-turn text."""
415 format: ReplyFormat
416 #: Claude's tool-turn text is answer (``answer_prose_in_tool_turns``).
417 keeps_tool_turn_text: bool = False
419 @property
420 def key(self) -> str:
421 return self.format.key
423 def text_of(self, content: Any) -> str:
424 return text_of(content)
426 def answer(self, text: str) -> Reply:
427 return self.format.answer(text)
429 def reply(self, message: Any) -> Reply:
430 return self.format.reply(message)
432 def contract(self) -> str:
433 return self.format.contract()
435 def wrap_history(self, text: str) -> str:
436 return self.format.wrap_history(text)
438 def stream(self) -> StreamFilter:
439 return self.format.stream(keeps_tool_turn_text=self.keeps_tool_turn_text)
441 def tool_loop_answer(self, final: str, tool_turns: list[str]) -> Reply:
442 """What a tool loop delivers from its last, tool-free message's text
443 and the text of the turns that called tools.
445 A model whose tool-turn text is answer (Claude) delivers all of it,
446 in order. Any other model's tool-turn text is what it was about to
447 do, so only its last message is the answer, with
448 :meth:`ReplyFormat.tool_turn_answer` in its place when that is
449 empty. A render fence written in a tool turn is not lost either way:
450 the graph restores every fence a tool returned
451 (``graph._restore_missing_artifacts``).
452 """
453 found = self.format.answer(final)
454 if self.keeps_tool_turn_text:
455 texts = [self.format.answer(t).answer for t in tool_turns]
456 return Reply(_join([*texts, found.answer]), found.path, found.removed)
457 if found.answer:
458 return found
459 return Reply(
460 self.format.tool_turn_answer(tool_turns), found.path, found.removed
461 )
463 def trace(self, message: Any) -> Any:
464 """``message`` as the run's trace keeps it: never its reasoning — the
465 trace reaches skill-run steps and the batch API's ``messages``.
467 Reasoning blocks and commentary-phase text go; text the format reads
468 as reasoning goes; a turn that called tools keeps its text only when
469 that text is answer (Claude), and keeps its tool calls always. A
470 message with nothing to remove is returned as it is."""
471 if not hasattr(message, "model_copy") or getattr(message, "type", "") != "ai":
472 return message
473 content = message.content
474 drop_text = bool(getattr(message, "tool_calls", None)) and not (
475 self.keeps_tool_turn_text
476 )
477 cleaned: Any
478 if isinstance(content, str):
479 found = self.format.answer(content)
480 cleaned = (
481 ""
482 if drop_text
483 else (content if found.answer == content.strip() else found.answer)
484 )
485 else:
486 kept: list[Any] = []
487 for block in content or []:
488 if not isinstance(block, dict):
489 kept.append(block)
490 continue
491 kind = block.get("type")
492 if kind in _TOOL_BLOCK_TYPES:
493 kept.append(block)
494 elif (kind is None or kind in _TEXT_TYPES) and not (
495 drop_text or block.get("phase") == COMMENTARY
496 ):
497 kept.append(block)
498 # Every other block — thinking, reasoning — is left out.
499 text = text_of(kept)
500 found = self.format.answer(text)
501 if found.answer != text.strip():
502 # The format read reasoning in the text itself.
503 kept = [
504 b
505 for b in kept
506 if isinstance(b, dict) and b.get("type") in _TOOL_BLOCK_TYPES
507 ]
508 if found.answer:
509 kept.insert(0, {"type": "text", "text": found.answer})
510 cleaned = kept
511 if cleaned == content:
512 return message
513 return message.model_copy(update={"content": cleaned})
516#: Blocks that are a turn's tool calls, kept in the trace with it.
517_TOOL_BLOCK_TYPES = frozenset(
518 {"tool_use", "tool_call", "function_call", "server_tool_use"}
519)
522_DEFAULT_KEY = "typed"
525def _reader(caps: model_capabilities.ModelCapabilities) -> Reader:
526 fmt = _REGISTRY.get(caps.reply_format) or _REGISTRY[_DEFAULT_KEY]
527 return Reader(fmt, keeps_tool_turn_text=caps.answer_prose_in_tool_turns)
530def of_client(llm: Any) -> Reader:
531 """The reader for a built client (``model_capabilities.of_client``)."""
532 return _reader(model_capabilities.of_client(llm))
535def of_traced(provider: Any, model: Any) -> Reader:
536 """The reader for a call's traced identity — a stream event's
537 ``ls_provider`` / ``ls_model_name``."""
538 return _reader(model_capabilities.of_traced(provider, model))
541def of_route(provider: str, model: str) -> Reader:
542 """The reader for a catalogue identity (``capabilities_for``) — the
543 LiteLLM path, which holds no LangChain client."""
544 return _reader(model_capabilities.capabilities_for(provider, model))
547def registered() -> dict[str, ReplyFormat]:
548 return dict(_REGISTRY)
551def unregistered_keys() -> list[str]:
552 """Format keys ``model_capabilities`` can name that no class serves."""
553 return [
554 key
555 for key in get_args(model_capabilities.ReplyFormatKey)
556 if key not in _REGISTRY
557 ]
560def whole_json(text: str) -> Reply | None:
561 """``text`` as a reply asked for as JSON, when the whole of it parses —
562 passed as it is (``path`` ``json``): a reader that cleans prose
563 (gpt-oss's seam) could cut a string value at a sentence boundary. None
564 for anything else, which is read through the model's format."""
565 from app.util import safe_json
567 try:
568 safe_json.loads_exact(text)
569 except ValueError:
570 return None
571 return Reply(text.strip(), path="json")
574def log_reply(agent: str, reader: Reader, found: Reply) -> None:
575 """One line per delivered answer: which format read it and how — never
576 its text. A model told to use the envelope that did not is a warning:
577 its answer was found by the fallback (``cleaning.answer``)."""
578 # A JSON reply is never asked for the envelope (``engines/model.py``).
579 if reader.format.expects_envelope and found.path not in (
580 "envelope",
581 "harmony",
582 "json",
583 ):
584 if found.answer:
585 logger.warning(
586 "[reply:%s] %s answered without the %s envelope; read by %s, "
587 "%d characters left out",
588 reader.key,
589 agent,
590 cleaning.ENVELOPE_TAG,
591 found.path,
592 found.removed,
593 )
594 return
595 if found.removed or found.path != "text":
596 logger.info(
597 "[reply:%s] %s answer read by %s, %d characters left out",
598 reader.key,
599 agent,
600 found.path,
601 found.removed,
602 )