: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(aio): render responses api tool outputs in trace text (#78095)
posthog[bot]bcc03ead3b11
diff --git a/products/ai_observability/backend/text_repr/formatters/constants.py b/products/ai_observability/backend/text_repr/formatters/constants.pyindex 025493fb655d..32d205d44fe6 100644--- a/products/ai_observability/backend/text_repr/formatters/constants.py+++ b/products/ai_observability/backend/text_repr/formatters/constants.py@@ -30,6 +30,34 @@ SAMPLING_REDUCTION_FACTOR = 0.9 # Safety margin when reducing target line count# Tool formattingDEFAULT_TOOLS_COLLAPSE_THRESHOLD = 5 # Collapse tool lists longer than this+# OpenAI Responses API item shapes. Unlike Chat Completions messages, these keep their payload+# outside `content`: tool calls in `arguments` / `input`, tool results in `output`, model+# reasoning in `summary`. A formatter that reads only `content` renders them as a bare header.+RESPONSES_TOOL_CALL_TYPES = frozenset({"function_call", "custom_tool_call"})+RESPONSES_TOOL_OUTPUT_TYPES = frozenset({"function_call_output", "custom_tool_call_output"})+# Rendered in an unrecognized item's signature line, so its payload dump can skip them.+RESPONSES_ITEM_METADATA_KEYS = frozenset(+ {"type", "id", "call_id", "name", "arguments", "input", "status", "encrypted_content"}+)+# Any of these makes a dict a Chat Completions message, not a Responses item.+CHAT_COMPLETIONS_MESSAGE_KEYS = frozenset({"role", "content", "tool_calls"})+# Blocks that are already plain text, so a `[TYPE]` label would only restate them.+PLAIN_TEXT_BLOCK_TYPES = frozenset({"text", "input_text", "output_text", "summary_text"})+# Non-Responses tool blocks with a dedicated renderer in `_format_special_block`.+SPECIAL_BLOCK_TYPES = frozenset({"tool-call", "tool_use", "function"})++# An unrecognized item dumps its own fields, and one of them can be a base64 image or screenshot.+# Capping per field keeps the item's shape readable without pushing megabytes into the trace view,+# where `truncate_content`'s expand marker would otherwise carry the whole value.+MAX_RESPONSES_FIELD_CHARS = 2000+OVERSIZED_FIELD_NOTE = "[{chars:,} chars not shown]"++# Placeholders for evidence the event never carried. Without them a reader, or an LLM judge+# grading the trace, cannot tell a tool that returned nothing from a payload we failed to record.+MISSING_TOOL_OUTPUT_NOTE = "[tool output not recorded]"+MISSING_REASONING_NOTE = "[reasoning summary not recorded]"+MISSING_TOOLS_NOTE = "[tool catalog not recorded]"+# Tree renderingMAX_TREE_DEPTH = 10 # Maximum depth for hierarchical trace tree renderingdiff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex 20a96f587c0a..46ae781e7a65 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -11,14 +11,26 @@ import base64from typing import Any, TypedDictfrom .constants import (+ CHAT_COMPLETIONS_MESSAGE_KEYS,DEFAULT_TRUNCATE_BUFFER,+ MAX_RESPONSES_FIELD_CHARS,MAX_UNABLE_TO_PARSE_REPR_LENGTH,MAX_UNPARSED_DISPLAY_LENGTH,+ MISSING_REASONING_NOTE,+ MISSING_TOOL_OUTPUT_NOTE,+ MISSING_TOOLS_NOTE,+ OVERSIZED_FIELD_NOTE,+ PLAIN_TEXT_BLOCK_TYPES,PRESERVE_HEADER_LINES,+ RESPONSES_ITEM_METADATA_KEYS,+ RESPONSES_TOOL_CALL_TYPES,+ RESPONSES_TOOL_OUTPUT_TYPES,SAMPLED_VIEW_HEADER,SAMPLING_MAX_ITERATIONS,SAMPLING_REDUCTION_FACTOR,+ SPECIAL_BLOCK_TYPES,)+from .tool_formatter import format_toolsclass FormatterOptions(TypedDict, total=False):@@ -279,8 +291,8 @@ def safe_extract_text(content: Any) -> str:if i > 0 and text_parts:text_parts.append("") # Blank line separator- # If we have a type and it's not just "text", label it- if item_type and item_type != "text":+ # If we have a type that isn't already plain text, label it+ if item_type and item_type not in PLAIN_TEXT_BLOCK_TYPES:text_parts.append(f"[{item_type.upper()}]")text_parts.append("") # Blank line after label@@ -313,7 +325,7 @@ def _is_special_block(block: Any) -> bool:return Falseblock_type = block.get("type")- if block_type in ("tool-call", "tool_use", "function"):+ if block_type in SPECIAL_BLOCK_TYPES:return True# Check for tool-call content format@@ -400,6 +412,146 @@ def extract_text_content(content: Any) -> str:return safe_extract_text(content)+def extract_payload_text(payload: Any) -> str:+ """Extract text from a tool payload, returning "" only when nothing was recorded.++ A falsey scalar such as `0` or `False` is a real result, so it must not collapse to "" the+ way `None` and empty containers do. Callers label the "" case as unrecorded, and a tool that+ counted zero rows would otherwise be reported as missing evidence.+ """+ if payload is None:+ return ""+ if isinstance(payload, str):+ return payload+ if isinstance(payload, list | dict | tuple) and not payload:+ # `extract_text_content`'s repr fallback would render an empty container as a literal+ # "[]" / "{}", which reads as recorded output.+ return ""+ return extract_text_content(payload)+++def _is_responses_item(msg: dict[str, Any]) -> bool:+ """True for a Responses API item, which is a typed entry carrying no Chat Completions message.++ Responses items sit at the top level of the conversation array with a `type` and none of+ `role`, `content`, or `tool_calls`. Matching on that shape rather than on a list of known+ types means a built-in tool OpenAI adds later renders its fields instead of a bare header.+ Excluding `tool_calls` keeps the shape from claiming a Chat Completions message that happens+ to be keyed by `type` and carries nothing but tool calls.+ """+ item_type = msg.get("type")+ return bool(item_type) and item_type not in PLAIN_TEXT_BLOCK_TYPES and CHAT_COMPLETIONS_MESSAGE_KEYS.isdisjoint(msg)+++def _format_call_signature(msg: dict[str, Any]) -> str:+ """Render a Responses item as a function signature.++ `arguments` is a JSON tool-call payload, so it parses into keyword arguments. `input` is+ freeform custom-tool text, so it goes through verbatim. Reparsing it would rewrite an input+ that happens to look like JSON.+ """+ name = str(msg.get("name") or msg.get("type") or "unknown")+ arguments = msg.get("arguments")+ if arguments is not None:+ return format_single_tool_call(name, arguments)+ return f"{name}({msg.get('input') or ''})"+++def _cap_long_strings(value: Any) -> Any:+ """Replace long strings with a note of their size, recursing into containers.++ An unrecognized item's payload can be a base64 image or screenshot. `truncate_content` would+ carry the whole value in its expand marker, so the cap has to happen before the dump.+ """+ if isinstance(value, str) and len(value) > MAX_RESPONSES_FIELD_CHARS:+ return OVERSIZED_FIELD_NOTE.format(chars=len(value))+ if isinstance(value, dict):+ return {key: _cap_long_strings(item) for key, item in value.items()}+ if isinstance(value, list):+ return [_cap_long_strings(item) for item in value]+ return value+++def _format_responses_item_fields(msg: dict[str, Any], options: FormatterOptions | None) -> list[str]:+ """Format a Responses item from its own fields, for types with no dedicated branch.++ Built-in tools each carry a different payload (`action`, `code`, `queries`, `result`), so+ render what the item holds rather than fitting every type to a function signature.+ """+ signature = _format_call_signature(msg)+ status = msg.get("status")+ parts = [f"{signature} ({status})" if status else signature]++ payload = {key: value for key, value in msg.items() if key not in RESPONSES_ITEM_METADATA_KEYS}+ if payload:+ parts.append(json.dumps(_cap_long_strings(payload), indent=2, default=str))++ lines, _ = truncate_content("\n".join(parts), options)+ return lines+++def _format_responses_item(msg: dict[str, Any], options: FormatterOptions | None = None) -> list[str] | None:+ """Format one OpenAI Responses API item, or return None when the item is not one.++ Returning None lets the caller fall back to the Chat Completions `content` path. These items+ are worth special-casing because they hold their payload outside `content`, so reading+ `content` alone drops every tool call, tool result, and reasoning summary in the conversation+ while still printing its header.+ """+ item_type = msg.get("type")++ if item_type in RESPONSES_TOOL_CALL_TYPES:+ lines, _ = truncate_content(_format_call_signature(msg), options)+ return lines++ if item_type in RESPONSES_TOOL_OUTPUT_TYPES:+ output = msg.get("output")+ text = extract_payload_text(msg.get("content") if output is None else output)+ if not text:+ return [MISSING_TOOL_OUTPUT_NOTE]+ lines, _ = truncate_content(text, options)+ return lines++ if item_type == "reasoning":+ text = extract_payload_text(msg.get("summary") or msg.get("content"))+ if not text:+ # Reasoning is frequently returned encrypted, with no readable summary at all.+ return [MISSING_REASONING_NOTE]+ lines, _ = truncate_content(text, options)+ return lines++ if item_type == "additional_tools":+ # The tool catalog this item carries runs to tens of thousands of characters, so lean on+ # `format_tools` to collapse anything longer than a short list down to a count.+ return format_tools(msg.get("tools"), options) or [MISSING_TOOLS_NOTE]++ if item_type in SPECIAL_BLOCK_TYPES:+ # Anthropic and Vercel tool blocks reach this array too, and already have a renderer that+ # produces a signature rather than a field dump.+ formatted = _format_special_block(msg)+ if formatted:+ lines, _ = truncate_content(formatted, options)+ return lines++ if _is_responses_item(msg):+ return _format_responses_item_fields(msg, options)++ return None+++def _extract_responses_output_items(value: Any) -> list[Any] | None:+ """Return the item list of an OpenAI Responses API response object, or None if it isn't one.++ The Responses API answers with `{"object": "response", "output": [...]}` where Chat+ Completions answers with `{"choices": [...]}`, so a formatter that only knows `choices`+ renders no model output at all.+ """+ if not isinstance(value, dict) or value.get("object") != "response":+ return None+ output = value.get("output")+ return output if isinstance(output, list) else None++def format_messages_array(messages: list[Any], options: FormatterOptions | None = None) -> list[str]:"""Format an array of message objects without header.@@ -428,7 +580,10 @@ def format_messages_array(messages: list[Any], options: FormatterOptions | Nonelines.append(f"[{i + 1}] {role.upper()}")lines.append("")- if content:+ responses_lines = _format_responses_item(msg, options)+ if responses_lines is not None:+ lines.extend(responses_lines)+ elif content:text_content = extract_text_content(content)if text_content:content_lines, _ = truncate_content(text_content, options)@@ -485,6 +640,15 @@ def format_output_messages("""Format output messages section."""lines: list[str] = []+ # Responses API output (an item list) rather than Chat Completions choices. An empty item+ # list falls through, so a recorded `$ai_output` string still gets rendered below.+ responses_items = _extract_responses_output_items(ai_output_choices) or _extract_responses_output_items(ai_output)+ if responses_items:+ lines.append("")+ lines.append("OUTPUT:")+ lines.extend(format_messages_array(responses_items, options))+ return lines+# Simple string outputif ai_output and isinstance(ai_output, str):lines.append("")@@ -508,6 +672,13 @@ def format_output_messages(if not isinstance(choice, dict):continue+ # The Responses API can send its items at the top level of the array, with no `role`+ # and no `content`. Pass those straight to `format_messages_array`, which knows their+ # shapes, rather than dropping them for failing the role check below.+ if _is_responses_item(choice):+ messages.append(choice)+ continue+# Extract message from choice# Handle both OpenAI format (choice.message) and Anthropic format (choice is the message)message = choice.get("message")diff --git a/products/ai_observability/backend/text_repr/formatters/span_formatter.py b/products/ai_observability/backend/text_repr/formatters/span_formatter.pyindex aca555a646d2..6bcc59c60026 100644--- a/products/ai_observability/backend/text_repr/formatters/span_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/span_formatter.py@@ -9,9 +9,11 @@ import astimport jsonfrom typing import Any+from .constants import MISSING_TOOL_OUTPUT_NOTEfrom .message_formatter import (FormatterOptions,add_line_numbers,+ extract_payload_text,format_messages_array,format_single_tool_call,truncate_content,@@ -99,10 +101,14 @@ def _format_tool_result(state: dict, options: FormatterOptions | None) -> list[sheader_parts.append(f"({status})")lines.append(" ".join(header_parts))- if content:- lines.append("")- content_lines, _ = truncate_content(str(content), options)+ lines.append("")+ # `content` is often a list of content blocks, which `str()` would render as a Python repr.+ text = extract_payload_text(content)+ if text:+ content_lines, _ = truncate_content(text, options)lines.extend(content_lines)+ else:+ lines.append(MISSING_TOOL_OUTPUT_NOTE)return linesdiff --git a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.pyindex 8bafd5a12eef..938a5c666795 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_event_formatter.py@@ -8,10 +8,14 @@ dicts, nested structures, and plain text.import jsonfrom datetime import datetime+from parameterized import parameterized++from ..constants import MISSING_TOOL_OUTPUT_NOTEfrom ..event_formatter import (_dict_to_yaml_lines,format_embedding_text_repr,format_evaluation_text_repr,+ format_event_text_repr,format_event_text_repr_from_ai_events_row,format_generation_text_repr,)@@ -407,3 +411,39 @@ class TestFormatEventTextReprFromAiEventsRow:)assert "Embedding vector generated" in resultassert "text to embed" in result+++class TestSpanToolResultFormatting:+ @staticmethod+ def _span(output_state):+ return {"event": "$ai_span", "properties": {"$ai_span_name": "search", "$ai_output_state": output_state}}++ @parameterized.expand(+ [+ ("empty_string", ""),+ ("none", None),+ ("empty_list", []),+ ]+ )+ def test_tool_result_without_content_says_so(self, _name, content):+ state = {"type": "tool", "name": "search", "status": "success", "content": content}+ result = format_event_text_repr(self._span(state))+ assert "[TOOL RESULT] search (success)" in result+ assert MISSING_TOOL_OUTPUT_NOTE in result++ def test_tool_result_with_a_falsey_payload_is_kept(self):+ state = {"type": "tool", "name": "count", "status": "success", "content": 0}+ result = format_event_text_repr(self._span(state))+ assert "0" in result+ assert MISSING_TOOL_OUTPUT_NOTE not in result++ def test_tool_result_content_blocks_render_as_text(self):+ state = {+ "type": "tool",+ "name": "search",+ "status": "success",+ "content": [{"type": "text", "text": "3 issues found"}],+ }+ result = format_event_text_repr(self._span(state))+ assert "3 issues found" in result+ assert "'type': 'text'" not in resultdiff --git a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.pyindex bc162c3f3ecf..7884fedb447b 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_message_formatter.py@@ -4,6 +4,9 @@ Tests for message_formatter.py - message input/output formatting logic.Tests cover multiple LLM provider formats, tool calls, truncation, and edge cases."""+from parameterized import parameterized++from ..constants import MISSING_REASONING_NOTE, MISSING_TOOL_OUTPUT_NOTE, MISSING_TOOLS_NOTEfrom ..message_formatter import (extract_text_content,extract_tool_calls_from_content,@@ -486,3 +489,204 @@ class TestEdgeCases:lines = format_input_messages("")# Empty string should be treated as no inputassert len(lines) == 0+++class TestResponsesApiItems:+ @parameterized.expand(+ [+ (+ "custom_tool_call",+ {+ "call_id": "call_1",+ "input": "const r = await tools.foo(); text(r)",+ "name": "exec",+ "status": "completed",+ "type": "custom_tool_call",+ },+ ["exec(const r = await tools.foo(); text(r))"],+ ),+ (+ "custom_tool_call_with_json_like_input",+ {"call_id": "call_1", "input": '{"a": 1}', "name": "exec", "type": "custom_tool_call"},+ ['exec({"a": 1})'],+ ),+ (+ "custom_tool_call_output",+ {+ "call_id": "call_1",+ "output": [{"text": "channel|sessions\nDirect|21800", "type": "input_text"}],+ "type": "custom_tool_call_output",+ },+ ["Direct|21800"],+ ),+ (+ "function_call",+ {+ "call_id": "call_2",+ "name": "execute_sql",+ "arguments": '{"query": "select 1"}',+ "type": "function_call",+ },+ ['execute_sql(query="select 1")'],+ ),+ (+ "function_call_output",+ {+ "call_id": "call_2",+ "output": [{"text": "event|c_7d\nnot_found|4", "type": "input_text"}],+ "type": "function_call_output",+ },+ ["not_found|4"],+ ),+ (+ "reasoning",+ {"type": "reasoning", "summary": [{"text": "Checking the error rate.", "type": "summary_text"}]},+ ["Checking the error rate."],+ ),+ (+ "string_output",+ {"call_id": "call_3", "output": "London", "type": "function_call_output"},+ ["London"],+ ),+ (+ "unrecognized_item_type",+ {"id": "f1", "status": "completed", "whatever": [1, 2], "type": "some_future_call"},+ ["some_future_call() (completed)", '"whatever"'],+ ),+ (+ "builtin_web_search_call",+ {"id": "ws1", "status": "completed", "type": "web_search_call"},+ ["web_search_call() (completed)"],+ ),+ (+ "builtin_code_interpreter_call",+ {"id": "ci1", "status": "completed", "code": 'print("hi")', "type": "code_interpreter_call"},+ ["code_interpreter_call() (completed)", "print"],+ ),+ (+ "builtin_mcp_call",+ {"id": "m1", "name": "get_thing", "arguments": '{"x": 1}', "output": "done", "type": "mcp_call"},+ ["get_thing(x=1)", "done"],+ ),+ ]+ )+ def test_renders_payload_held_outside_content(self, _name, message, expected):+ result = "\n".join(format_input_messages([message]))+ for fragment in expected:+ assert fragment in result++ @parameterized.expand(+ [+ ("empty_list", {"call_id": "call_1", "type": "function_call_output", "output": []}),+ ("explicit_none", {"call_id": "call_1", "type": "function_call_output", "output": None}),+ ("key_absent", {"call_id": "call_1", "type": "function_call_output"}),+ ("empty_string", {"call_id": "call_1", "type": "function_call_output", "output": ""}),+ ]+ )+ def test_tool_output_without_payload_says_so(self, _name, message):+ result = "\n".join(format_input_messages([message]))+ assert MISSING_TOOL_OUTPUT_NOTE in result++ @parameterized.expand(+ [+ ("short_list_is_expanded", 2, ["AVAILABLE TOOLS: 2", "tool_0()"]),+ ("long_list_collapses_to_a_count", 7, ["[+] AVAILABLE TOOLS: 7"]),+ ]+ )+ def test_additional_tools_catalog_is_summarized(self, _name, tool_count, expected):+ message = {+ "role": "developer",+ "type": "additional_tools",+ "tools": [{"name": f"tool_{i}", "description": "Does a thing."} for i in range(tool_count)],+ }+ result = "\n".join(format_input_messages([message], {"include_markers": False}))+ for fragment in expected:+ assert fragment in result++ def test_additional_tools_without_a_catalog_says_so(self):+ result = "\n".join(format_input_messages([{"role": "developer", "type": "additional_tools"}]))+ assert MISSING_TOOLS_NOTE in result++ def test_oversized_item_field_is_summarized_rather_than_embedded(self):+ message = {"id": "img", "status": "completed", "type": "image_generation_call", "result": "A" * 200_000}+ result = "\n".join(format_input_messages([message]))+ assert "200,000 chars not shown" in result+ assert "A" * 3_000 not in result++ def test_message_keyed_by_type_keeps_its_tool_calls(self):+ message = {"type": "assistant", "tool_calls": [{"function": {"name": "search", "arguments": '{"q": "x"}'}}]}+ result = "\n".join(format_input_messages([message]))+ assert "Tool calls: 1" in result+ assert 'search(q="x")' in result++ def test_anthropic_tool_use_uses_the_existing_block_renderer(self):+ choices = [{"type": "tool_use", "id": "t1", "name": "get_weather", "input": {"city": "Paris"}}]+ result = "\n".join(format_output_messages(None, choices))+ assert 'get_weather(city="Paris")' in result++ def test_empty_responses_output_falls_back_to_string_output(self):+ result = "\n".join(format_output_messages("the model refused", {"object": "response", "output": []}))+ assert "OUTPUT:" in result+ assert "the model refused" in result++ def test_reasoning_without_summary_says_so(self):+ message = {"type": "reasoning", "encrypted_content": "gAAAA", "summary": []}+ result = "\n".join(format_input_messages([message]))+ assert MISSING_REASONING_NOTE in result++ def test_legacy_choice_objects_still_route_to_the_message_path(self):+ choices = [{"index": 0, "message": {"role": "assistant", "content": "Hi"}, "finish_reason": "stop"}]+ result = "\n".join(format_output_messages(None, choices))+ assert "[1] ASSISTANT" in result+ assert "Hi" in result++ def test_falsey_tool_output_is_not_reported_as_missing(self):+ message = {"call_id": "call_1", "output": 0, "type": "function_call_output"}+ result = "\n".join(format_input_messages([message]))+ assert "0" in result+ assert MISSING_TOOL_OUTPUT_NOTE not in result++ def test_top_level_output_items_are_rendered(self):+ output_choices = [+ {"call_id": "c1", "name": "get_weather", "arguments": '{"city": "Paris"}', "type": "function_call"},+ {"call_id": "c1", "output": "22C, sunny", "type": "function_call_output"},+ ]+ result = "\n".join(format_output_messages(None, output_choices))+ assert 'get_weather(city="Paris")' in result+ assert "22C, sunny" in result++ def test_responses_output_object_is_unwrapped(self):+ output_choices = {+ "object": "response",+ "status": "completed",+ "output": [+ {"type": "reasoning", "summary": [{"text": "Time to query.", "type": "summary_text"}]},+ {+ "call_id": "c9",+ "input": "text(1)",+ "name": "exec",+ "status": "completed",+ "type": "custom_tool_call",+ },+ ],+ }+ result = "\n".join(format_output_messages(None, output_choices))+ assert "OUTPUT:" in result+ assert "Time to query." in result+ assert "exec(text(1))" in result++ def test_chat_completions_messages_are_unaffected(self):+ messages = [+ {"role": "user", "content": "Hello"},+ {"role": "assistant", "content": "Hi", "tool_calls": [{"function": {"name": "test", "arguments": ""}}]},+ ]+ result = "\n".join(format_input_messages(messages))+ assert "Hello" in result+ assert "Tool calls: 1" in result+ assert "test()" in result++ def test_plain_text_blocks_are_not_labelled(self):+ messages = [{"role": "user", "content": [{"type": "input_text", "text": "Run the scout"}]}]+ result = "\n".join(format_input_messages(messages))+ assert "Run the scout" in result+ assert "[INPUT_TEXT]" not in result