|
| 1 | +"""Adapter for pagarsky/agent-trace style academic trajectories.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from context_profiler.models import APIRequest, BlockType, ContentBlock, Message, Role, Session |
| 10 | +from context_profiler.token_utils import count_tokens |
| 11 | + |
| 12 | + |
| 13 | +def is_agent_trace(data: dict[str, Any]) -> bool: |
| 14 | + return ( |
| 15 | + ("llm_steps" in data or "llm_steps_json" in data) |
| 16 | + and ("spans" in data or "spans_json" in data) |
| 17 | + ) |
| 18 | + |
| 19 | + |
| 20 | +def load_agent_trace_session(path: Path) -> Session: |
| 21 | + with open(path, encoding="utf-8") as f: |
| 22 | + data = json.load(f) |
| 23 | + return parse_agent_trace(data, source=str(path)) |
| 24 | + |
| 25 | + |
| 26 | +def parse_agent_trace(data: dict[str, Any], source: str = "") -> Session: |
| 27 | + llm_steps = _json_field(data, "llm_steps") |
| 28 | + spans = _json_field(data, "spans") |
| 29 | + metadata = _json_field(data, "metadata") if ("metadata" in data or "metadata_json" in data) else {} |
| 30 | + |
| 31 | + messages: list[Message] = [] |
| 32 | + requests: list[APIRequest] = [] |
| 33 | + |
| 34 | + prompt = data.get("prompt") |
| 35 | + if prompt: |
| 36 | + messages.append(Message( |
| 37 | + role=Role.USER, |
| 38 | + blocks=[_text_block(prompt)], |
| 39 | + index=len(messages), |
| 40 | + )) |
| 41 | + |
| 42 | + span_idx = 0 |
| 43 | + for step in llm_steps: |
| 44 | + assistant_blocks = _assistant_blocks(step) |
| 45 | + if assistant_blocks: |
| 46 | + messages.append(Message(role=Role.ASSISTANT, blocks=assistant_blocks, index=len(messages))) |
| 47 | + |
| 48 | + tool_calls = step.get("tool_calls") or [] |
| 49 | + for call in tool_calls: |
| 50 | + span = spans[span_idx] if span_idx < len(spans) else None |
| 51 | + if span is not None: |
| 52 | + span_idx += 1 |
| 53 | + messages.append(_tool_result_message(span, len(messages))) |
| 54 | + |
| 55 | + requests.append(_snapshot(messages, len(requests), data)) |
| 56 | + |
| 57 | + return Session( |
| 58 | + requests=requests, |
| 59 | + metadata={ |
| 60 | + "source": source, |
| 61 | + "source_format": "agent-trace", |
| 62 | + "trace_id": data.get("trace_id"), |
| 63 | + "dataset_name": data.get("dataset_name") or metadata.get("dataset_name"), |
| 64 | + "task_id": data.get("task_id") or metadata.get("task_id"), |
| 65 | + "model": data.get("model") or metadata.get("model_family"), |
| 66 | + "llm_step_count": len(llm_steps), |
| 67 | + "tool_span_count": len(spans), |
| 68 | + }, |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +def _json_field(data: dict[str, Any], name: str) -> Any: |
| 73 | + if name in data: |
| 74 | + return data[name] |
| 75 | + raw = data.get(f"{name}_json") |
| 76 | + if raw is None: |
| 77 | + return [] if name in {"llm_steps", "spans"} else {} |
| 78 | + return json.loads(raw) |
| 79 | + |
| 80 | + |
| 81 | +def _assistant_blocks(step: dict[str, Any]) -> list[ContentBlock]: |
| 82 | + blocks = [] |
| 83 | + reasoning = step.get("reasoning_content") |
| 84 | + model_output = step.get("model_output") |
| 85 | + text_parts = [part for part in (reasoning, model_output) if part] |
| 86 | + if text_parts: |
| 87 | + blocks.append(_text_block("\n\n".join(text_parts))) |
| 88 | + |
| 89 | + for idx, call in enumerate(step.get("tool_calls") or []): |
| 90 | + name = call.get("name") or "unknown" |
| 91 | + arguments = call.get("arguments") or {} |
| 92 | + text = json.dumps(arguments, ensure_ascii=False) |
| 93 | + blocks.append(ContentBlock( |
| 94 | + block_type=BlockType.TOOL_USE, |
| 95 | + text=text, |
| 96 | + token_count=count_tokens(text), |
| 97 | + tool_name=name, |
| 98 | + tool_call_id=f"{step.get('step_id', 'step')}:tool:{idx}", |
| 99 | + tool_input=arguments if isinstance(arguments, dict) else {"value": arguments}, |
| 100 | + )) |
| 101 | + return blocks |
| 102 | + |
| 103 | + |
| 104 | +def _tool_result_message(span: dict[str, Any], index: int) -> Message: |
| 105 | + output = span.get("tool_output") |
| 106 | + if not isinstance(output, str): |
| 107 | + output = json.dumps(output, ensure_ascii=False) |
| 108 | + block = ContentBlock( |
| 109 | + block_type=BlockType.TOOL_RESULT, |
| 110 | + text=output or "", |
| 111 | + token_count=count_tokens(output or ""), |
| 112 | + tool_name=span.get("tool_name"), |
| 113 | + tool_call_id=span.get("span_id"), |
| 114 | + ) |
| 115 | + return Message(role=Role.TOOL, blocks=[block], index=index) |
| 116 | + |
| 117 | + |
| 118 | +def _text_block(text: str) -> ContentBlock: |
| 119 | + return ContentBlock( |
| 120 | + block_type=BlockType.TEXT, |
| 121 | + text=text, |
| 122 | + token_count=count_tokens(text), |
| 123 | + ) |
| 124 | + |
| 125 | + |
| 126 | +def _snapshot(messages: list[Message], request_index: int, data: dict[str, Any]) -> APIRequest: |
| 127 | + return APIRequest( |
| 128 | + messages=list(messages), |
| 129 | + tools=[], |
| 130 | + model=data.get("model", "unknown"), |
| 131 | + request_index=request_index, |
| 132 | + source_format="agent-trace", |
| 133 | + raw_input={ |
| 134 | + "model": data.get("model", "unknown"), |
| 135 | + "messages": [_message_to_raw(message) for message in messages], |
| 136 | + "tools": [], |
| 137 | + "source_format": "agent-trace", |
| 138 | + }, |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +def _message_to_raw(message: Message) -> dict[str, Any]: |
| 143 | + content = [] |
| 144 | + tool_calls = [] |
| 145 | + for block in message.blocks: |
| 146 | + if block.block_type == BlockType.TEXT: |
| 147 | + content.append({"type": "text", "text": block.text}) |
| 148 | + elif block.block_type == BlockType.TOOL_USE: |
| 149 | + tool_calls.append({ |
| 150 | + "id": block.tool_call_id, |
| 151 | + "type": "function", |
| 152 | + "function": { |
| 153 | + "name": block.tool_name or "unknown", |
| 154 | + "arguments": block.text, |
| 155 | + }, |
| 156 | + }) |
| 157 | + elif block.block_type == BlockType.TOOL_RESULT: |
| 158 | + content.append({ |
| 159 | + "type": "tool_result", |
| 160 | + "tool_use_id": block.tool_call_id, |
| 161 | + "content": block.text, |
| 162 | + }) |
| 163 | + |
| 164 | + raw: dict[str, Any] = {"role": message.role.value, "content": content} |
| 165 | + if len(content) == 1 and content[0].get("type") == "text": |
| 166 | + raw["content"] = content[0]["text"] |
| 167 | + if tool_calls: |
| 168 | + raw["tool_calls"] = tool_calls |
| 169 | + return raw |
0 commit comments