:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(evals): show which tool an agent called in eval traces (#89942)
Daniel Parker9f576aa190c5
diff --git a/products/posthog_ai/eval_harness/base.py b/products/posthog_ai/eval_harness/base.pyindex b7263a8c7155..cbccf4813e19 100644--- a/products/posthog_ai/eval_harness/base.py+++ b/products/posthog_ai/eval_harness/base.py@@ -14,6 +14,7 @@ from .config import AgentArtifacts, BaseEvalCase, SandboxedEvalCasefrom .engines.base import EvalEnginefrom .engines.types import CaseHooks, CaseSpec, ExperimentResult, ExperimentSpec, SpanKindfrom .harness.kernel_sandboxes import reclaim_kernels+from .log_parser import describe_tool_usefrom .log_sink import append_case_scores, build_case_dir, write_case_logsfrom .runner import AgentNeverRanError, EvalCaseResult, agent_never_ran, run_eval_casefrom .scorers import ExitCodeZero, wrap_scorers@@ -47,6 +48,7 @@ def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:content = msg.get("content", "")# Anthropic format: content can be a string or list of content blocks+ tool_calls: list[dict[str, Any]] = []if isinstance(content, list):# Render content blocks for displayparts: list[str] = []@@ -57,7 +59,12 @@ def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:if block_type == "text":parts.append(block.get("text", ""))elif block_type == "tool_use":- parts.append(f"[tool_use: {block.get('name', '?')}]")+ block_input = block.get("input")+ tool, tool_input = describe_tool_use(+ block.get("name"), block_input if isinstance(block_input, dict) else {}+ )+ tool_calls.append({"tool": tool, "input": tool_input})+ parts.append(f"[tool_use: {tool or '?'}]")elif block_type == "tool_result":result_text = str(block.get("content", ""))[:500]is_error = block.get("is_error", False)@@ -69,12 +76,13 @@ def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:span_type: SpanKindif role == "assistant":- # Check if this message contains tool_use blocks- has_tool_use = isinstance(content, list) and any(- isinstance(b, dict) and b.get("type") == "tool_use" for b in content- )- span_type = "function" if has_tool_use else "llm"- name = "tool_call" if has_tool_use else "agent"+ span_type = "function" if tool_calls else "llm"+ # Naming the span after the resolved tool keeps the trace tree scannable;+ # every single-exec call would otherwise read as an undifferentiated "exec".+ if len(tool_calls) == 1:+ name = f"tool_call: {tool_calls[0]['tool']}"+ else:+ name = "tool_call" if tool_calls else "agent"elif role == "user":has_tool_result = isinstance(content, list) and any(isinstance(b, dict) and b.get("type") == "tool_result" for b in content@@ -89,7 +97,12 @@ def _log_conversation_spans(hooks: CaseHooks, parsed: ParsedLog) -> None:if role == "user":span.log(input=display_content)elif role == "assistant":- span.log(output=display_content)+ # Logged untruncated: the arguments are the only record of what the+ # agent asked for, and a query payload is easy to cut short.+ if tool_calls:+ span.log(input=tool_calls, output=display_content)+ else:+ span.log(output=display_content)else:span.log(metadata={"message": display_content})diff --git a/products/posthog_ai/eval_harness/log_parser.py b/products/posthog_ai/eval_harness/log_parser.pyindex b427d61213b9..57dc0a812ffd 100644--- a/products/posthog_ai/eval_harness/log_parser.py+++ b/products/posthog_ai/eval_harness/log_parser.py@@ -47,6 +47,24 @@ def normalize_tool_name(name: str | None) -> str:return name+def describe_tool_use(name: str | None, tool_input: dict[str, Any]) -> tuple[str, dict[str, Any]]:+ """Resolve a raw ``tool_use`` name and input to the tool the agent actually invoked.++ Single-exec mode routes every PostHog tool through one ``exec`` call, so the raw+ name says ``exec`` for all of them and only the command string tells them apart.+ Falls back to the normalized raw name for command shapes that wrap no inner tool+ (``search``, ``tools``, ``schema``).+ """+ normalized = normalize_tool_name(name)+ if normalized == EXEC_TOOL_NAME:+ command = tool_input.get("command", "")+ if isinstance(command, str):+ unwrapped = _parse_exec_command(command)+ if unwrapped is not None:+ return unwrapped+ return (normalized, tool_input)++class ToolCall(BaseModel):model_config = ConfigDict(frozen=True)diff --git a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.pyindex 5261821a0d5a..0dbd46aa8446 100644--- a/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py+++ b/products/posthog_ai/eval_harness/test/test_sandboxed_harness_output.py@@ -1,13 +1,18 @@from __future__ import annotationsimport sys+import json+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Path+from typing import Anyimport pytestfrom unittest.mock import MagicMockfrom products.posthog_ai.eval_harness import base-from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary+from products.posthog_ai.eval_harness.acp_log import GenerationDescriptor, ParsedLog+from products.posthog_ai.eval_harness.engines.types import AggregateScore, EvalSummary, NullCaseHooksfrom products.posthog_ai.eval_harness.harness.reporting import ProgressReporter, SuiteRunResultfrom products.posthog_ai.eval_harness.harness.transcript import RunTranscriptfrom products.posthog_ai.eval_harness.scorers import ExitCodeZero@@ -113,6 +118,69 @@ async def test_reporter_output_is_labeled_and_reserves_pass_for_the_run(assert output.count("PASS") == 1+def test_tool_call_spans_carry_the_resolved_tool_and_its_arguments() -> None:+ trends_query = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}+ parsed = ParsedLog(+ generations=[+ GenerationDescriptor(+ output_content=[+ {+ "type": "tool_use",+ "id": "1",+ "name": "mcp__posthog__exec",+ "input": {"command": f"call query-trends {json.dumps(trends_query)}"},+ }+ ],+ )+ ]+ )++ spans = _collect_spans(parsed)++ assert spans == [("tool_call: query-trends", [{"tool": "query-trends", "input": trends_query}])]+++def test_exec_commands_wrapping_no_inner_tool_stay_under_the_raw_name() -> None:+ parsed = ParsedLog(+ generations=[+ GenerationDescriptor(+ output_content=[+ {+ "type": "tool_use",+ "id": "1",+ "name": "mcp__posthog__exec",+ "input": {"command": "schema query-trends series"},+ }+ ],+ )+ ]+ )++ spans = _collect_spans(parsed)++ assert spans == [("tool_call: exec", [{"tool": "exec", "input": {"command": "schema query-trends series"}}])]+++def _collect_spans(parsed: ParsedLog) -> list[tuple[str, Any]]:+ collected: list[tuple[str, Any]] = []++ class _Span:+ def __init__(self, name: str) -> None:+ self.name = name++ def log(self, *, input: Any = None, output: Any = None, metadata: Any = None) -> None:+ if input is not None:+ collected.append((self.name, input))++ class _Hooks(NullCaseHooks):+ @contextmanager+ def start_span(self, name: str, kind: Any) -> Iterator[_Span]:+ yield _Span(name)++ base._log_conversation_spans(_Hooks(), parsed)+ return collected++def test_sandboxed_eval_run_adds_exit_code_scorer(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:monkeypatch.setattr(base, "build_case_dir", MagicMock(return_value=tmp_path))ctx = MagicMock(posthog_client=None, case_filter=None)