| 386 | |
| 387 | |
| 388 | def extract_last_agent_text(events: list[dict[str, Any]]) -> str: |
| 389 | agent_events = [ |
| 390 | event |
| 391 | for event in events |
| 392 | if event.get('kind') == 'MessageEvent' and event.get('source') == 'agent' |
| 393 | ] |
| 394 | if not agent_events: |
| 395 | raise RuntimeError( |
| 396 | 'No assistant text message was found in the conversation events' |
| 397 | ) |
| 398 | |
| 399 | llm_message = agent_events[-1].get('llm_message') |
| 400 | if not isinstance(llm_message, dict): |
| 401 | raise RuntimeError('Last agent message has no llm_message field') |
| 402 | content = llm_message.get('content') |
| 403 | if not isinstance(content, list): |
| 404 | raise RuntimeError('Last agent message content is not a list') |
| 405 | |
| 406 | text_parts: list[str] = [] |
| 407 | for part in content: |
| 408 | if not isinstance(part, dict): |
| 409 | continue |
| 410 | if part.get('type') == 'text' and part.get('text'): |
| 411 | text_parts.append(str(part['text'])) |
| 412 | if not text_parts: |
| 413 | raise RuntimeError('Last agent message contains no text content') |
| 414 | return ''.join(text_parts).strip() |
| 415 | |
| 416 | |
| 417 | def parse_agent_json(text: str) -> dict[str, Any]: |