Coverage for src/retrospeedlab/search/lab/transcript.py: 98%
104 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
1from dataclasses import dataclass
2from datetime import datetime
3from pathlib import Path
4from typing import Any, cast
6import msgspec
8GENERATION = "generation"
9TOOL = "tool"
10AGENT = "agent"
11AGENT_TOOLS = frozenset({"Agent", "Task"})
12USAGE_KEYS = {
13 "input_tokens": "input",
14 "output_tokens": "output",
15 "cache_read_input_tokens": "cache_read_input_tokens",
16 "cache_creation_input_tokens": "cache_creation_input_tokens",
17}
20@dataclass(slots=True)
21class Step:
22 kind: str
23 key: str
24 name: str
25 owner: str | None
26 start: datetime
27 end: datetime
28 input: Any
29 output: str
30 usage: dict[str, int]
31 failed: bool
34@dataclass(slots=True)
35class Round:
36 start: datetime
37 end: datetime
38 cost: float
39 result: str
40 failed: bool
41 steps: list[Step]
44def moment(stamp: str) -> datetime:
45 return datetime.fromisoformat(stamp)
48def text_of(content: Any) -> str:
49 if isinstance(content, str):
50 return content
51 return "\n".join(block["text"] for block in content if block["type"] == "text")
54def usage_of(usage: dict[str, Any]) -> dict[str, int]:
55 return {name: usage[key] for key, name in USAGE_KEYS.items() if key in usage}
58class Reader:
59 def __init__(self) -> None:
60 self.rounds: list[Round] = []
61 self.steps: dict[str, Step] = {}
62 self.last: dict[str | None, datetime] = {}
63 self.costs: dict[str, float] = {}
64 self.now: datetime | None = None
65 self.start: datetime | None = None
67 def read(self, event: dict[str, Any]) -> None:
68 if "timestamp" in event:
69 self.now = moment(event["timestamp"])
70 self.start = self.now if self.start is None else self.start
71 if event["type"] == "assistant":
72 self.answer(event["parent_tool_use_id"], event["message"])
73 if event["type"] == "user":
74 self.results(event["message"]["content"])
75 if event["type"] == "result":
76 self.close(event)
78 def answer(self, owner: str | None, message: dict[str, Any]) -> None:
79 now = self.clock()
80 if message["id"] not in self.steps:
81 start = self.last[owner] if owner in self.last else now
82 self.steps[message["id"]] = Step(
83 GENERATION, message["id"], message["model"], owner, start, now, None, "", {}, False
84 )
85 generation = self.steps[message["id"]]
86 generation.end, generation.usage = now, usage_of(message["usage"])
87 generation.output = "\n".join(filter(None, [generation.output, text_of(message["content"])]))
88 for block in message["content"]:
89 if block["type"] == "tool_use":
90 self.call(owner, block, now)
91 self.last[owner] = now
93 def call(self, owner: str | None, block: dict[str, Any], now: datetime) -> None:
94 agent = block["name"] in AGENT_TOOLS
95 name = block["input"]["subagent_type"] if agent and "subagent_type" in block["input"] else block["name"]
96 self.steps[block["id"]] = Step(
97 AGENT if agent else TOOL, block["id"], name, owner, now, now, block["input"], "", {}, False
98 )
100 def results(self, content: Any) -> None:
101 if isinstance(content, str):
102 return
103 for block in content:
104 if block["type"] == "tool_result" and block["tool_use_id"] in self.steps:
105 step = self.steps[block["tool_use_id"]]
106 step.end, step.output = self.clock(), text_of(block["content"])
107 step.failed = "is_error" in block and bool(block["is_error"])
108 self.last[step.owner] = step.end
110 def close(self, event: dict[str, Any]) -> None:
111 end = self.clock()
112 session, total = event["session_id"], event["total_cost_usd"]
113 cost = total - (self.costs[session] if session in self.costs else 0.0)
114 self.costs[session] = total
115 result = event["result"] if "result" in event else ""
116 start = self.start if self.start is not None else end
117 self.rounds.append(Round(start, end, cost, result, event["is_error"], list(self.steps.values())))
118 self.steps, self.last, self.start = {}, {}, None
120 def clock(self) -> datetime:
121 if self.now is None:
122 raise ValueError("the lab log has an event before its first timestamp")
123 return self.now
126def read_transcript(log: Path) -> list[Round]:
127 reader = Reader()
128 for line in log.read_bytes().splitlines():
129 try:
130 event = msgspec.json.decode(line)
131 except msgspec.DecodeError:
132 continue
133 if isinstance(event, dict) and "type" in event:
134 reader.read(cast(dict[str, Any], event))
135 return reader.rounds