Coverage for app / services / conversation.py: 91%
185 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"""
2Handles persistence of conversation state after an LLM execution.
4All execution routers call `persist_execution` to record the conversation
5turn, chat messages, and invocation trace in the AI database.
7Every trace row takes the model calls the usage meter saw while it was being
8served (``metering.claim_calls``) and stores them as ``LLMInvocationCall``
9rows — provider, model, graph node, tokens, latency, outcome and cost per
10call — so which model did each piece of work is recorded, not inferred from
11the one model the request named. The row's own totals are the sum of its
12calls whenever any were metered.
14Tool invocations are recorded via `persist_tool_invocation`, called from the
15agent execution layer after every tool call completes (success or failure).
16"""
18import logging
19import time
20from collections.abc import Iterator
21from contextlib import contextmanager
22from decimal import Decimal
23from uuid import UUID
25from sqlalchemy.orm import Session
27from app.db.postgres.enums import InvocationEnum, ToolInvocationEnum
28from app.db.postgres.models import (
29 ChatMessage,
30 Conversation,
31 LLMInvocation,
32 LLMInvocationCall,
33 LLMModel,
34 Provider,
35 ToolCitation,
36 ToolInvocation,
37)
38from app.models.spec import ExecuteRequest, ExecuteResponse
39from app.common import invocation as invocation_context
40from app.common import workspace as workspace_context
41from app.services import metering
43logger = logging.getLogger(__name__)
46def requested_model(request: ExecuteRequest) -> tuple[str | None, str | None]:
47 """The ``(provider, model)`` an execution request names, if it names one.
49 A model prompt and an agent each name the model they run on; a skill,
50 graph or pipeline names none — its nodes choose.
51 """
52 if request.type == "model":
53 config = request.spec
54 elif request.type == "agent":
55 config = request.spec.model
56 else:
57 return None, None
58 return config.provider or None, config.model or None
61def catalogue_ids(db: Session) -> dict[tuple[str, str], UUID]:
62 """``(provider, model_name) → LLMModel.id`` for every catalogue model.
64 Matched in Python rather than filtered in SQL: ``providers.name`` is an
65 enum, and filtering it by a provider the enum does not list raises
66 instead of matching nothing. Never raises — a trace without catalogue
67 links still names its models.
68 """
69 try:
70 rows = (
71 db.query(Provider.name, LLMModel.model_name, LLMModel.id)
72 .join(Provider, LLMModel.provider_id == Provider.id)
73 .all()
74 )
75 except Exception: # noqa: BLE001 — the link is a convenience, not the record
76 logger.warning("Could not read the model catalogue for a trace", exc_info=True)
77 return {}
78 return {
79 (str(getattr(provider, "value", provider)), str(model)): model_id
80 for provider, model, model_id in rows
81 }
84def _call_rows(
85 calls: list[metering.LLMCall], ids: dict[tuple[str, str], UUID]
86) -> list[LLMInvocationCall]:
87 """One ``LLMInvocationCall`` per metered call, priced per call."""
88 rows: list[LLMInvocationCall] = []
89 for sequence, call in enumerate(calls):
90 failed = call.status != metering.CALL_SUCCESS
91 priced = None if failed else metering.price_detail(call)
92 cost = priced.cost if priced else None
93 rows.append(
94 LLMInvocationCall(
95 sequence=sequence,
96 provider=call.provider,
97 model_name=call.model,
98 model_id=ids.get((call.provider, call.model)),
99 kind=call.kind,
100 node=call.node,
101 step=call.step,
102 pass_index=call.pass_index,
103 prompt_tokens=call.input_tokens,
104 completion_tokens=call.output_tokens,
105 cache_read_tokens=call.cache_read_tokens,
106 cache_write_tokens=call.cache_write_tokens + call.cache_write_1h_tokens,
107 reasoning_tokens=call.reasoning_tokens,
108 pricing=_pricing_record(call, priced),
109 latency_ms=call.latency_ms,
110 status=InvocationEnum.Status.error
111 if failed
112 else InvocationEnum.Status.success,
113 error_detail=_strip_nul(call.error),
114 estimated_cost_usd=float(cost) if cost is not None else None,
115 )
116 )
117 return rows
120def _pricing_record(
121 call: metering.LLMCall, priced: metering.Priced | None
122) -> dict | None:
123 """What ``LLMInvocationCall.pricing`` keeps: the rates behind the cost,
124 or why there is none."""
125 if priced is None:
126 return None
127 record = dict(priced.detail)
128 if call.cache_write_1h_tokens:
129 record["cache_write_1h_tokens"] = call.cache_write_1h_tokens
130 if priced.unpriced_reason:
131 record["unpriced_reason"] = priced.unpriced_reason
132 return record or None
135def _row_model(
136 provider: str | None,
137 model: str | None,
138 calls: list[metering.LLMCall],
139) -> tuple[str | None, str | None]:
140 """The model a trace row is filed under.
142 The one the request named; otherwise the one model every chat call used
143 (embeddings beside chat do not make a run multi-model), or — for work
144 that made no chat call, like a retrieval — the one model every call
145 used. None when the request named none and its calls used several — the
146 call rows say which, and picking one of them would misattribute the rest.
147 """
148 if provider and model:
149 return provider, model
150 named = [c for c in calls if c.provider and c.model]
151 chat = [c for c in named if c.kind == "chat"]
152 used = {(c.provider, c.model) for c in (chat or named)}
153 if len(used) == 1:
154 return next(iter(used))
155 return None, None
158def _traced(
159 db: Session,
160 *,
161 provider: str | None,
162 model: str | None,
163 prompt_tokens: int,
164 completion_tokens: int,
165 estimated_cost_usd: float | None,
166 purpose: str | None,
167 calls: list[metering.LLMCall] | None = None,
168 **fields,
169) -> LLMInvocation:
170 """An ``LLMInvocation`` carrying the meter's unclaimed calls — or
171 ``calls``, when the caller has claimed them already.
173 The calls' own figures replace the caller's whenever any call succeeded:
174 every call's full prompt, each priced on its own model. A row with
175 tokens and no metered call means a model was reached without the meter —
176 built outside ``build_langchain_llm`` — which is logged, because its
177 calls are the ones a trace cannot name.
178 """
179 if calls is None:
180 calls = metering.claim_calls()
181 ids = catalogue_ids(db) if (calls or (provider and model)) else {}
182 row_provider, row_model = _row_model(provider, model, calls)
184 succeeded = [c for c in calls if c.status == metering.CALL_SUCCESS]
185 call_rows = _call_rows(calls, ids)
186 if succeeded:
187 prompt_tokens = sum(c.input_tokens for c in succeeded)
188 completion_tokens = sum(c.output_tokens for c in succeeded)
189 priced = [
190 Decimal(str(r.estimated_cost_usd))
191 for r in call_rows
192 if r.estimated_cost_usd is not None
193 ]
194 estimated_cost_usd = float(sum(priced)) if priced else None
195 elif prompt_tokens or completion_tokens:
196 logger.warning(
197 "Trace for %s reports %d tokens but no metered model call — a "
198 "model was reached without the usage meter, so its calls are "
199 "not on the trace",
200 purpose,
201 prompt_tokens + completion_tokens,
202 )
204 if "workspace" not in fields:
205 # Where svc-core says the work was done (app/common/workspace.py).
206 fields["workspace"] = workspace_context.stamp(fields.get("user_id"))
207 # The svc-core turn it was part of (app/common/invocation.py).
208 fields.setdefault("core_invocation_id", invocation_context.current())
209 return LLMInvocation(
210 provider=row_provider,
211 model_name=row_model,
212 model_id=ids.get((row_provider, row_model)) if row_model else None,
213 purpose=purpose,
214 prompt_tokens=prompt_tokens,
215 completion_tokens=completion_tokens,
216 total_tokens=prompt_tokens + completion_tokens,
217 estimated_cost_usd=estimated_cost_usd,
218 calls=call_rows,
219 **fields,
220 )
223def persist_execution(
224 db: Session,
225 request: ExecuteRequest,
226 response: ExecuteResponse,
227 started_at: float,
228) -> UUID | None:
229 """
230 Write an LLMInvocation trace for a completed execution.
232 conversation_id is a soft cross-service reference to svc-core's
233 conversations.id — passed in by the caller and stored without any
234 Conversation record being created or looked up in svc-ai.
236 The row's model is the one the request names, with the catalogue link
237 resolved here; its calls are the ones the meter saw.
239 A run an Output rule may withhold (``rules.may_withhold``) keeps nothing
240 of its answer here: no preview on the trace, an empty reply on svc-ai's
241 copy of the conversation. svc-core decides whether it is withheld, after
242 this; a person reads this trace (Activity, the decision record).
243 """
244 from app.inference.rules import may_withhold
246 held = may_withhold(getattr(request, "rules", None))
247 usage = response.usage or {}
248 prompt_tokens: int = usage.get("prompt_tokens", 0)
249 completion_tokens: int = usage.get("completion_tokens", 0)
250 total_tokens: int = usage.get("total_tokens", 0)
251 estimated_cost_usd: float | None = usage.get("estimated_cost_usd")
252 latency_ms = int((time.time() - started_at) * 1000)
254 conversation_id: UUID | None = None
255 if request.conversation_id:
256 try:
257 conversation_id = UUID(request.conversation_id)
258 except (ValueError, TypeError):
259 pass
261 if conversation_id:
262 from app.db.postgres.enums import MessageEnum
264 conv = db.get(Conversation, conversation_id)
265 if conv is None:
266 external_agent_id = None
267 if request.external_agent_id:
268 try:
269 external_agent_id = UUID(request.external_agent_id)
270 except (ValueError, TypeError):
271 pass
272 conv = Conversation(
273 id=conversation_id,
274 user_id=request.user_id,
275 external_agent_id=external_agent_id,
276 )
277 db.add(conv)
278 db.flush()
280 db.add_all(
281 [
282 ChatMessage(
283 conversation_id=conversation_id,
284 role=MessageEnum.Role.USER,
285 content=request.input,
286 token_count=prompt_tokens,
287 ),
288 ChatMessage(
289 conversation_id=conversation_id,
290 role=MessageEnum.Role.ASSISTANT,
291 content="" if held else response.output,
292 token_count=completion_tokens,
293 ),
294 ]
295 )
296 conv.total_input_tokens += prompt_tokens
297 conv.total_output_tokens += completion_tokens
298 conv.total_tokens += total_tokens
300 provider, model = requested_model(request)
301 db.add(
302 _traced(
303 db,
304 provider=provider,
305 model=model,
306 prompt_tokens=prompt_tokens,
307 completion_tokens=completion_tokens,
308 estimated_cost_usd=estimated_cost_usd,
309 purpose=invocation_purpose(request),
310 conversation_id=conversation_id,
311 user_id=_parse_uuid(request.user_id),
312 latency_ms=latency_ms,
313 status=InvocationEnum.Status.success,
314 request_config=_extract_request_config(request),
315 output_preview=None if held else _output_preview(response.output),
316 )
317 )
319 db.commit()
320 return conversation_id
323def _parse_uuid(value: str | None) -> UUID | None:
324 try:
325 return UUID(value) if value else None
326 except (ValueError, TypeError):
327 return None
330def persist_llm_invocation(
331 db: Session,
332 *,
333 purpose: str,
334 provider: str | None,
335 model: str | None,
336 user_id: str | None = None,
337 conversation_id: str | UUID | None = None,
338 prompt_tokens: int = 0,
339 completion_tokens: int = 0,
340 latency_ms: int | None = None,
341 status: InvocationEnum.Status = InvocationEnum.Status.success,
342 error_detail: str | None = None,
343 request_config: dict | None = None,
344 estimated_cost_usd: float | None = None,
345 output_preview: str | None = None,
346 calls: list[metering.LLMCall] | None = None,
347) -> None:
348 """Record an invocation made outside the execute pipeline.
350 Used by platform flows (e.g. generative agent setup) and resumed runs so
351 every LLM invocation is visible in the activity traces, not only
352 conversation executions. ``provider`` / ``model`` are the model the flow
353 called — required, so a caller cannot forget them — or None for a run
354 whose nodes choose (its calls then name the models). The catalogue link
355 is resolved from them, never taken from the caller: an id the catalogue
356 does not hold would fail the row's FK and lose the trace. Persistence
357 is observability — it must never fail the caller's request, so errors
358 are swallowed after a rollback.
359 """
360 try:
361 db.add(
362 _traced(
363 db,
364 provider=provider,
365 model=model,
366 prompt_tokens=prompt_tokens,
367 completion_tokens=completion_tokens,
368 estimated_cost_usd=estimated_cost_usd,
369 purpose=purpose,
370 calls=calls,
371 user_id=_parse_uuid(user_id),
372 conversation_id=_parse_uuid(str(conversation_id))
373 if conversation_id
374 else None,
375 latency_ms=latency_ms,
376 status=status,
377 error_detail=_strip_nul(error_detail),
378 request_config=request_config,
379 output_preview=_output_preview(output_preview),
380 )
381 )
382 db.commit()
383 except Exception as exc: # noqa: BLE001 — tracing must never break the request
384 db.rollback()
385 logger.exception("Failed to persist LLM invocation trace: %s", exc)
388class InvocationOutcome:
389 """What the work inside ``trace_invocation`` produced, for its trace."""
391 def __init__(self) -> None:
392 self.output: str | None = None
393 self.error: str | None = None
396@contextmanager
397def trace_invocation(
398 db: Session,
399 *,
400 purpose: str,
401 provider: str | None = None,
402 model: str | None = None,
403 user_id: str | None = None,
404 request_config: dict | None = None,
405) -> Iterator[InvocationOutcome]:
406 """Trace the model work in the block, whether it succeeds or fails.
408 For endpoints that reach a model outside the execute pipeline —
409 embedding, retrieval, simulation. The block may set ``outcome.output``
410 (the trace's preview) or ``outcome.error`` (a failure it handled); an
411 exception escaping the block is recorded and re-raised.
412 """
413 started = time.time()
414 outcome = InvocationOutcome()
415 try:
416 yield outcome
417 except Exception as exc:
418 outcome.error = f"{type(exc).__name__}: {exc}"
419 raise
420 finally:
421 persist_llm_invocation(
422 db,
423 purpose=purpose,
424 provider=provider,
425 model=model,
426 user_id=user_id,
427 latency_ms=int((time.time() - started) * 1000),
428 status=InvocationEnum.Status.error
429 if outcome.error
430 else InvocationEnum.Status.success,
431 error_detail=outcome.error,
432 request_config=request_config,
433 output_preview=outcome.output,
434 )
437#: Purpose of a trace written for model calls no endpoint traced itself.
438UNTRACED_PURPOSE = "untraced"
441def trace_unclaimed(calls: list[metering.LLMCall], method: str, path: str) -> None:
442 """Trace model calls a request made that no trace row claimed.
444 ``LLMUsageMiddleware`` hands over whatever is left on a request's meter
445 once the endpoint has finished, so a path that forgets to write its own
446 trace still leaves every call it made on record, under the endpoint
447 that made it. Its own session: the request's is closed by now.
448 """
449 from app.db.postgres.engine import SessionLocal
451 db = SessionLocal()
452 try:
453 persist_llm_invocation(
454 db,
455 purpose=UNTRACED_PURPOSE,
456 provider=None,
457 model=None,
458 status=InvocationEnum.Status.error
459 if all(c.status != metering.CALL_SUCCESS for c in calls)
460 else InvocationEnum.Status.success,
461 request_config={"endpoint": f"{method} {path}"},
462 calls=calls,
463 )
464 finally:
465 db.close()
468def persist_execution_error(
469 db: Session,
470 request: ExecuteRequest,
471 started_at: float,
472 error: str,
473) -> None:
474 """Record a failed invocation trace with the soft conversation_id reference."""
475 latency_ms = int((time.time() - started_at) * 1000)
477 conversation_id: UUID | None = None
478 if request.conversation_id:
479 try:
480 conversation_id = UUID(request.conversation_id)
481 except (ValueError, TypeError):
482 pass
484 # The calls made before the failure — and the one that failed — are on
485 # the row, so a run that broke on one node says which model it was on.
486 provider, model = requested_model(request)
487 db.add(
488 _traced(
489 db,
490 provider=provider,
491 model=model,
492 prompt_tokens=0,
493 completion_tokens=0,
494 estimated_cost_usd=None,
495 purpose=invocation_purpose(request),
496 conversation_id=conversation_id,
497 user_id=_parse_uuid(request.user_id),
498 latency_ms=latency_ms,
499 status=InvocationEnum.Status.error,
500 error_detail=error,
501 request_config=_extract_request_config(request),
502 )
503 )
504 db.commit()
507def _strip_nul(s: str | None) -> str | None:
508 """Remove NUL bytes that PostgreSQL rejects in string literals."""
509 return s.replace("\x00", "") if s else s
512# Cap on the stored output snapshot — enough to inspect what a call produced
513# without persisting unbounded LLM output twice.
514OUTPUT_PREVIEW_MAX_CHARS = 4000
517def _output_preview(text: str | None) -> str | None:
518 """Truncated, NUL-safe snapshot of an invocation's produced output."""
519 if not text:
520 return None
521 cleaned = _strip_nul(text) or ""
522 if len(cleaned) > OUTPUT_PREVIEW_MAX_CHARS:
523 return cleaned[:OUTPUT_PREVIEW_MAX_CHARS] + "…"
524 return cleaned
527def persist_tool_invocation(
528 db: Session,
529 tool_name: str,
530 input_args: dict | None,
531 raw_output: str | None,
532 status: ToolInvocationEnum.Status,
533 latency_ms: int | None = None,
534 error_detail: str | None = None,
535 execution_context: dict | None = None,
536 conversation_id: UUID | None = None,
537 user_id: UUID | None = None,
538 citations: list[dict] | None = None,
539 report: dict | None = None,
540) -> ToolInvocation:
541 """
542 Persist a single tool call and its extracted citations.
544 Args:
545 tool_name: Canonical name from the tool registry (e.g. "web_search").
546 input_args: Arguments passed to the tool, serialised as a dict.
547 raw_output: Full string output returned by the tool.
548 status: Outcome: success / error / timeout.
549 latency_ms: Wall-clock execution time in milliseconds.
550 error_detail: Exception message or detail string on failure.
551 execution_context: Free-form metadata (skill_id, node name, agent name, etc.)
552 for grouping invocations by workflow.
553 conversation_id: Links this invocation to an ongoing conversation; nullable.
554 user_id: Soft reference to svc-core's users.id; nullable.
555 report: What the tool kept beside its text: a web search's
556 report (``app/util/web_search_report.py``).
557 citations: List of citation dicts as produced by `_extract_citations`.
558 Each dict must have ``source``, ``title``, and ``index`` keys;
559 ``collection`` and ``relevance_score`` are optional.
561 Returns:
562 The persisted ToolInvocation ORM object (with citations loaded).
563 """
564 invocation = ToolInvocation(
565 conversation_id=conversation_id,
566 user_id=user_id,
567 workspace=workspace_context.stamp(user_id),
568 core_invocation_id=invocation_context.current(),
569 tool_name=tool_name,
570 input_args=input_args,
571 raw_output=_strip_nul(raw_output),
572 latency_ms=latency_ms,
573 status=status,
574 error_detail=_strip_nul(error_detail),
575 execution_context=execution_context,
576 report=report,
577 )
578 db.add(invocation)
579 db.flush() # populate invocation.id before adding citations
581 for c in citations or []:
582 source = c.get("source", "")
583 source_type = (
584 ToolInvocationEnum.SourceType.url
585 if source.startswith("http")
586 else ToolInvocationEnum.SourceType.document
587 if tool_name == "query_knowledge_base"
588 else ToolInvocationEnum.SourceType.other
589 )
590 db.add(
591 ToolCitation(
592 tool_invocation_id=invocation.id,
593 index=c.get("index", 0),
594 source_type=source_type,
595 source=source,
596 title=c.get("title", source),
597 collection=c.get("collection"),
598 relevance_score=c.get("relevance_score"),
599 )
600 )
602 db.commit()
603 db.refresh(invocation)
604 return invocation
607def invocation_purpose(request: ExecuteRequest) -> str:
608 """What the trace records this call as.
610 The execution ``type`` by default. A caller that knows the call is
611 something else — an evaluation cell, a judge grading one — says so on
612 the request, and that wins: an evaluation recorded as ``"model"`` is
613 indistinguishable from a chat in every trace that reads it back.
614 """
615 return request.purpose or request.type
618def _extract_request_config(request: ExecuteRequest) -> dict | None:
619 """Pull inference parameters from the spec for the invocation snapshot.
621 The caller's ``reference`` rides along when it sent one: it is the only
622 thing that ties the trace row back to the evaluation, batch and variant
623 that asked for the call.
624 """
625 spec = request.spec
626 config: dict | None = None
627 if request.type == "model":
628 config = {
629 "temperature": spec.temperature,
630 "max_tokens": spec.max_tokens,
631 }
632 elif request.type == "agent":
633 config = {
634 "temperature": spec.model.temperature,
635 "max_tokens": spec.model.max_tokens,
636 }
637 if request.reference:
638 config = {**(config or {}), "reference": dict(request.reference)}
639 return config