|
| 1 | +"""Import real-world traces into vstack's :class:`~vstack.aar.AgentTrace`. |
| 2 | +
|
| 3 | +Your agent runs already produce traces — as chat-completion message logs |
| 4 | +(OpenAI / Anthropic style) or as OpenTelemetry spans. These converters turn |
| 5 | +those into the canonical ``AgentTrace`` that every vstack pattern consumes, so |
| 6 | +you can pipe real data straight into ``vstack-diagnose`` without hand-writing a |
| 7 | +trace. |
| 8 | +
|
| 9 | +Public API: |
| 10 | +
|
| 11 | +* :func:`from_chat_messages` — a list of ``{role, content, tool_calls?}`` dicts. |
| 12 | +* :func:`from_otel_spans` — a list of OpenTelemetry span dicts (best-effort, |
| 13 | + reads ``gen_ai.*`` attributes). |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +from datetime import datetime, timedelta, timezone |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +from vstack.aar import AgentTrace, TraceStep |
| 22 | + |
| 23 | +__all__ = ["from_chat_messages", "from_otel_spans"] |
| 24 | + |
| 25 | +_BASE_TS = datetime(2026, 1, 1, tzinfo=timezone.utc) |
| 26 | + |
| 27 | + |
| 28 | +def _coerce_content(content: Any) -> str: |
| 29 | + """Flatten a message ``content`` (str or multimodal list) to text.""" |
| 30 | + if content is None: |
| 31 | + return "" |
| 32 | + if isinstance(content, str): |
| 33 | + return content |
| 34 | + if isinstance(content, list): |
| 35 | + parts: list[str] = [] |
| 36 | + for block in content: |
| 37 | + if isinstance(block, dict): |
| 38 | + parts.append( |
| 39 | + str(block.get("text") or block.get("content") or block.get("type") or "") |
| 40 | + ) |
| 41 | + else: |
| 42 | + parts.append(str(block)) |
| 43 | + return "\n".join(p for p in parts if p) |
| 44 | + return str(content) |
| 45 | + |
| 46 | + |
| 47 | +def _ts(index: int) -> datetime: |
| 48 | + return _BASE_TS + timedelta(seconds=index) |
| 49 | + |
| 50 | + |
| 51 | +def from_chat_messages( |
| 52 | + messages: list[dict[str, Any]], |
| 53 | + *, |
| 54 | + goal: str = "", |
| 55 | + outcome: str = "", |
| 56 | + success: bool = False, |
| 57 | + agent_id: str | None = None, |
| 58 | + agent_framework: str = "chat", |
| 59 | + metadata: dict[str, Any] | None = None, |
| 60 | +) -> AgentTrace: |
| 61 | + """Build an ``AgentTrace`` from chat-completion messages. |
| 62 | +
|
| 63 | + Role → step mapping: ``system``/``user`` → ``message``; ``assistant`` |
| 64 | + text → ``message`` and any ``tool_calls`` → ``tool_call``; ``tool`` → |
| 65 | + ``observation``. ``goal`` defaults to the first user message and |
| 66 | + ``outcome`` to the last assistant message when not given. |
| 67 | + """ |
| 68 | + steps: list[TraceStep] = [] |
| 69 | + idx = 0 |
| 70 | + first_user = "" |
| 71 | + last_assistant = "" |
| 72 | + |
| 73 | + for msg in messages: |
| 74 | + role = str(msg.get("role", "")).lower() |
| 75 | + content = _coerce_content(msg.get("content")) |
| 76 | + tool_calls = msg.get("tool_calls") or [] |
| 77 | + |
| 78 | + if role in ("system", "user", "developer"): |
| 79 | + if content: |
| 80 | + steps.append(TraceStep(timestamp=_ts(idx), type="message", content=content)) |
| 81 | + idx += 1 |
| 82 | + if role == "user" and content and not first_user: |
| 83 | + first_user = content |
| 84 | + elif role == "assistant": |
| 85 | + if content: |
| 86 | + steps.append(TraceStep(timestamp=_ts(idx), type="message", content=content)) |
| 87 | + idx += 1 |
| 88 | + last_assistant = content |
| 89 | + for call in tool_calls: |
| 90 | + fn = call.get("function", call) if isinstance(call, dict) else {} |
| 91 | + name = fn.get("name", "tool") |
| 92 | + args = fn.get("arguments", "") |
| 93 | + steps.append( |
| 94 | + TraceStep(timestamp=_ts(idx), type="tool_call", content=f"{name}({args})") |
| 95 | + ) |
| 96 | + idx += 1 |
| 97 | + elif role == "tool": |
| 98 | + steps.append( |
| 99 | + TraceStep( |
| 100 | + timestamp=_ts(idx), type="observation", content=content or "(tool result)" |
| 101 | + ) |
| 102 | + ) |
| 103 | + idx += 1 |
| 104 | + elif content: |
| 105 | + steps.append(TraceStep(timestamp=_ts(idx), type="message", content=content)) |
| 106 | + idx += 1 |
| 107 | + |
| 108 | + return AgentTrace( |
| 109 | + agent_id=agent_id, |
| 110 | + agent_framework=agent_framework, |
| 111 | + goal=goal or first_user or "(goal not provided)", |
| 112 | + steps=steps, |
| 113 | + outcome=outcome or last_assistant or "(outcome not provided)", |
| 114 | + success=success, |
| 115 | + metadata=metadata or {}, |
| 116 | + ) |
| 117 | + |
| 118 | + |
| 119 | +def _span_start(span: dict[str, Any]) -> Any: |
| 120 | + return span.get("start_time") or span.get("startTime") or span.get("startTimeUnixNano") or 0 |
| 121 | + |
| 122 | + |
| 123 | +def from_otel_spans( |
| 124 | + spans: list[dict[str, Any]], |
| 125 | + *, |
| 126 | + goal: str = "", |
| 127 | + outcome: str = "", |
| 128 | + success: bool = False, |
| 129 | + agent_id: str | None = None, |
| 130 | + agent_framework: str = "otel", |
| 131 | + metadata: dict[str, Any] | None = None, |
| 132 | +) -> AgentTrace: |
| 133 | + """Build an ``AgentTrace`` from OpenTelemetry spans (best-effort). |
| 134 | +
|
| 135 | + Spans are ordered by start time. Each span becomes a step: GenAI/LLM spans |
| 136 | + (a ``gen_ai.*`` attribute or an ``llm``/``chat`` name) → ``tool_call``; |
| 137 | + others → ``observation``. Reads ``attributes`` either as a dict or as a |
| 138 | + list of ``{key, value}`` (OTLP-JSON form). |
| 139 | + """ |
| 140 | + ordered = sorted(spans, key=_span_start) |
| 141 | + steps: list[TraceStep] = [] |
| 142 | + |
| 143 | + for i, span in enumerate(ordered): |
| 144 | + attrs = _otel_attrs(span) |
| 145 | + name = str(span.get("name", "span")) |
| 146 | + is_genai = name.lower().startswith(("llm", "chat", "gen_ai")) or any( |
| 147 | + k.startswith("gen_ai") for k in attrs |
| 148 | + ) |
| 149 | + completion = ( |
| 150 | + attrs.get("gen_ai.completion") |
| 151 | + or attrs.get("gen_ai.response.content") |
| 152 | + or attrs.get("llm.output") |
| 153 | + ) |
| 154 | + prompt = attrs.get("gen_ai.prompt") or attrs.get("llm.input") |
| 155 | + detail = str(completion or prompt or "") |
| 156 | + content = f"{name}: {detail}" if detail else name |
| 157 | + steps.append( |
| 158 | + TraceStep( |
| 159 | + timestamp=_ts(i), |
| 160 | + type="tool_call" if is_genai else "observation", |
| 161 | + content=content, |
| 162 | + metadata={"span_name": name}, |
| 163 | + ) |
| 164 | + ) |
| 165 | + |
| 166 | + return AgentTrace( |
| 167 | + agent_id=agent_id, |
| 168 | + agent_framework=agent_framework, |
| 169 | + goal=goal or "(goal not provided)", |
| 170 | + steps=steps, |
| 171 | + outcome=outcome or "(outcome not provided)", |
| 172 | + success=success, |
| 173 | + metadata=metadata or {}, |
| 174 | + ) |
| 175 | + |
| 176 | + |
| 177 | +def _otel_attrs(span: dict[str, Any]) -> dict[str, Any]: |
| 178 | + raw = span.get("attributes", {}) |
| 179 | + if isinstance(raw, dict): |
| 180 | + return raw |
| 181 | + out: dict[str, Any] = {} |
| 182 | + if isinstance(raw, list): |
| 183 | + for item in raw: |
| 184 | + if isinstance(item, dict) and "key" in item: |
| 185 | + val = item.get("value") |
| 186 | + if isinstance(val, dict): |
| 187 | + val = next(iter(val.values()), val) |
| 188 | + out[str(item["key"])] = val |
| 189 | + return out |
0 commit comments