Coverage for mt_ai/trace.py: 100.00%
52 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""What one turn did and how long it took (SB-1197).
3`TurnRecorder` is fed by the agent's ADK callbacks: model calls are timed
4(before/after model), tool calls are timed and their arguments and results
5kept (before/after tool). It imports nothing from ADK: the callbacks pass it
6plain values, so it is unit-tested with a fake clock.
8The service writes the records to `ai_tool_calls` and the timings to the
9assistant row of `ai_messages`, best-effort, after the turn itself is saved.
10"""
12import hashlib
13import json
14import time
15from collections.abc import Callable
16from dataclasses import dataclass, field
17from typing import Any
19# A tool result bigger than this (as JSON) is stored as a digest. MT's tools
20# cap their output (8 candidates, 20 matches), so this is a guard, not a norm.
21MAX_RESULT_BYTES = 32_000
24@dataclass(frozen=True)
25class ToolCallRecord:
26 seq: int
27 tool_name: str
28 args: dict[str, Any]
29 result: dict[str, Any] | None
30 error_kind: str | None
31 duration_ms: int | None
34@dataclass
35class TurnRecorder:
36 """Collects one turn's tool calls and model time. Not thread-safe: one per turn."""
38 clock: Callable[[], float] = time.perf_counter
39 calls: list[ToolCallRecord] = field(default_factory=list)
40 llm_seconds: float = 0.0
41 _model_started: float | None = None
42 _tool_started: dict[str, float] = field(default_factory=dict)
44 @property
45 def llm_ms(self) -> int:
46 return round(self.llm_seconds * 1000)
48 def before_model(self, callback_context: Any = None, llm_request: Any = None) -> None:
49 self._model_started = self.clock()
51 def after_model(self, callback_context: Any = None, llm_response: Any = None) -> None:
52 if self._model_started is not None:
53 self.llm_seconds += self.clock() - self._model_started
54 self._model_started = None
56 def before_tool(self, tool: Any, args: dict[str, Any], tool_context: Any) -> None:
57 self._tool_started[_call_key(tool, tool_context)] = self.clock()
59 def after_tool(self, tool: Any, args: dict[str, Any], tool_context: Any, tool_response: Any) -> None:
60 started = self._tool_started.pop(_call_key(tool, tool_context), None)
61 duration = None if started is None else round((self.clock() - started) * 1000)
62 result = tool_response if isinstance(tool_response, dict) else {"value": tool_response}
63 self.calls.append(
64 ToolCallRecord(
65 seq=len(self.calls) + 1,
66 tool_name=getattr(tool, "name", str(tool)),
67 args=dict(args or {}),
68 result=bounded(result),
69 error_kind=error_kind(result),
70 duration_ms=duration,
71 )
72 )
75def _call_key(tool: Any, tool_context: Any) -> str:
76 """ADK gives each function call an id; fall back to the tool name."""
77 return str(getattr(tool_context, "function_call_id", None) or getattr(tool, "name", tool))
80def error_kind(result: dict[str, Any]) -> str | None:
81 """The `error.kind` a tool reported in its result, if any."""
82 error = result.get("error")
83 if isinstance(error, dict):
84 kind = error.get("kind")
85 return str(kind) if kind else "unknown"
86 return None
89def bounded(result: dict[str, Any]) -> dict[str, Any]:
90 """The result itself, or a digest when it is too big to keep."""
91 text = json.dumps(result, default=str, sort_keys=True)
92 size = len(text.encode())
93 if size <= MAX_RESULT_BYTES:
94 return json.loads(text) # plain JSON types only, as jsonb will hold them
95 return {"truncated": True, "bytes": size, "sha256": hashlib.sha256(text.encode()).hexdigest()}