Coverage for app / inference / engines / model.py: 93%
71 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"""
2ModelEngine — direct LLM call without tool-calling or graph execution.
4Handles ExecuteRequest(type="model") for both batch and streaming paths.
5"""
7from __future__ import annotations
9import time
10from typing import AsyncIterator
12from app.inference.context import InferenceContext
13from app.services import model_errors, reply_formats, token_budget
14from app.inference.engine import InferenceEngine, _sse
15from app.models.spec import ExecuteResponse, ModelConfig
16from app.services import llm as llm_service
17from app.util.logger import get_logger
18from app.util.observability import LLMSpan
19from app import prompts
21logger = get_logger(__name__)
23#: Output formats a model writes as prose, where the reply's format may add
24#: its contract; json / yaml / csv / xml answers are the data alone.
25_PROSE_FORMATS = (None, "", "markdown", "text")
28def _answer(
29 reader: reply_formats.Reader, output: str, config: ModelConfig
30) -> reply_formats.Reply:
31 """The answer in ``output``. A JSON reply that parses whole is the data
32 itself and passes as it is: a reader that cleans prose (gpt-oss's seam)
33 could cut a string value at a sentence boundary. Anything else — prose,
34 or JSON after a model's working — is read through the model's format."""
35 if config.output_format == "json":
36 whole = reply_formats.whole_json(output)
37 if whole is not None:
38 return whole
39 return reader.answer(output)
42def _prepared(
43 config: ModelConfig, messages: list[dict] | None
44) -> tuple[ModelConfig, list[dict] | None, reply_formats.Reader]:
45 """The call as this model is sent it, and the reader its reply is read
46 through (``reply_formats``, by the catalogue identity: the LiteLLM path
47 holds no LangChain client). A model whose reasoning can arrive as text is
48 told where its reply goes, and sees its earlier answers that way."""
49 reader = reply_formats.of_route(config.provider, config.model)
50 system = prompts.build_metadata_context() + "\n\n" + (config.system_prompt or "")
51 if reader.contract() and config.output_format in _PROSE_FORMATS:
52 system = system + "\n\n" + reader.contract()
53 replayed = None
54 if messages:
55 replayed = [
56 {**m, "content": reader.wrap_history(m["content"])}
57 if m.get("role") == "assistant" and isinstance(m.get("content"), str)
58 else m
59 for m in messages
60 ]
61 return config.model_copy(update={"system_prompt": system}), replayed, reader
64class ModelEngine(InferenceEngine):
65 """Direct LiteLLM call — no tool-calling, no graph.
67 The reply is read through the model's format (``reply_formats``), batch
68 and stream alike: LiteLLM keeps typed reasoning out of ``content``, and
69 gpt-oss's analysis written as text is left out like anywhere else.
71 The conversation's documents come before the person's words
72 (``attachments.render_for_model``), within the share of this model's
73 window they may take."""
75 def _attachment_window(self, ctx: InferenceContext) -> int | None:
76 config: ModelConfig = ctx.request.spec # type: ignore[assignment]
77 try:
78 return token_budget.limits_for_model(
79 config.provider, config.model
80 ).context_window
81 except Exception: # noqa: BLE001 — the default budget stands
82 return None
84 async def _do_infer(self, ctx: InferenceContext) -> ExecuteResponse:
85 config: ModelConfig = ctx.request.spec # type: ignore[assignment]
86 config, messages, reader = _prepared(config, ctx.request.messages or None)
88 t0 = time.monotonic()
89 output, usage = await llm_service.run_model(
90 config, ctx.filtered_input, messages
91 )
92 found = _answer(reader, output or "", config)
93 reply_formats.log_reply("model", reader, found)
94 output = found.answer
95 latency_ms = int((time.monotonic() - t0) * 1000)
97 LLMSpan(
98 agent="model",
99 model=f"{config.provider}/{config.model}",
100 latency_ms=latency_ms,
101 prompt_tokens=usage.get("prompt_tokens", 0),
102 completion_tokens=usage.get("completion_tokens", 0),
103 cost_usd=usage.get("estimated_cost_usd"),
104 ).log(logger)
106 self.monitor.add_usage_dict(usage)
108 return ExecuteResponse(
109 output=output,
110 usage=usage,
111 session_id=ctx.request.session_id,
112 )
114 async def _do_infer_stream(self, ctx: InferenceContext) -> AsyncIterator[str]:
115 from app.inference.engines.graph_based import stream_frames
117 config: ModelConfig = ctx.request.spec # type: ignore[assignment]
118 config, messages, reader = _prepared(config, ctx.request.messages or None)
119 stream = reader.stream()
121 t0 = time.monotonic()
122 raw_output = ""
123 try:
124 async for token, usage in llm_service.stream_model(
125 config=config,
126 input=ctx.filtered_input,
127 messages=messages,
128 ):
129 if usage is not None:
130 found = _answer(reader, raw_output, config)
131 reply_formats.log_reply("model", reader, found)
132 full_output = found.answer
133 for frame in stream_frames(stream.end(None, continues=False), None):
134 yield _sse(frame)
135 self.monitor.add_usage_dict(usage)
136 LLMSpan(
137 agent="model",
138 model=f"{config.provider}/{config.model}",
139 latency_ms=int((time.monotonic() - t0) * 1000),
140 prompt_tokens=usage.get("prompt_tokens", 0),
141 completion_tokens=usage.get("completion_tokens", 0),
142 cost_usd=usage.get("estimated_cost_usd"),
143 ).log(logger)
144 yield _sse({"type": "done", "output": full_output, "usage": usage})
145 else:
146 raw_output += token
147 for frame in stream_frames(stream.feed(token), None):
148 yield _sse(frame)
149 except Exception as exc:
150 LLMSpan(
151 agent="model",
152 model=f"{config.provider}/{config.model}",
153 latency_ms=int((time.monotonic() - t0) * 1000),
154 error=str(exc),
155 ).log(logger)
156 # Never the exception text: a provider error carries its response
157 # body. Classified failures say what an administrator must fix.
158 yield _sse({"type": "error", "message": model_errors.user_message(exc)})