: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): stop a non-string block type failing a whole trace (#99759)
posthog[bot]7b4638540227
diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex 7a13cca1c8bf..e31d21443f66 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -322,6 +322,16 @@ def extract_tool_calls_from_content(content: Any) -> list[ToolCall]:return tool_calls+def _string_type(msg: dict[str, Any]) -> str | None:+ """The value under `type` when it is a string, else None.++ Customer payloads record any JSON value there, and the membership tests below hash what they+ are given. An unhashable value such as a dict raises `TypeError` against a frozenset.+ """+ msg_type = msg.get("type")+ return msg_type if isinstance(msg_type, str) else None++def safe_extract_text(content: Any) -> str:"""Safely extract text from various content formats.@@ -346,7 +356,7 @@ def safe_extract_text(content: Any) -> str:text_parts: list[str] = []for i, item in enumerate(content):if isinstance(item, dict):- item_type = item.get("type")+ item_type = _string_type(item)# Try both "text" and "content" keys (tool_result uses "content")text_value = item.get("text") or item.get("content")@@ -388,7 +398,7 @@ def _is_special_block(block: Any) -> bool:if not isinstance(block, dict):return False- block_type = block.get("type")+ block_type = _string_type(block)if block_type in SPECIAL_BLOCK_TYPES:return True@@ -423,7 +433,7 @@ def _format_special_block(block: dict) -> str | None:if not tool_input and "partial_json" in block:try:tool_input = json.loads(block["partial_json"])- except (json.JSONDecodeError, ValueError):+ except (TypeError, ValueError):passreturn format_single_tool_call(tool_name, tool_input)@@ -504,7 +514,11 @@ def _is_responses_item(msg: dict[str, Any]) -> bool: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)+ if not item_type or not CHAT_COMPLETIONS_MESSAGE_KEYS.isdisjoint(msg):+ return False+ # Only a string can name a plain-text block, so any other type is a malformed item whose+ # recorded payload is still worth rendering.+ return not isinstance(item_type, str) or item_type not in PLAIN_TEXT_BLOCK_TYPESdef _format_call_signature(msg: dict[str, Any]) -> str:@@ -562,7 +576,7 @@ def _format_responses_item(msg: dict[str, Any], options: FormatterOptions | None`content` alone drops every tool call, tool result, and reasoning summary in the conversationwhile still printing its header."""- item_type = msg.get("type")+ item_type = _string_type(msg)if item_type in RESPONSES_TOOL_CALL_TYPES:lines, _ = truncate_content(_format_call_signature(msg), options)@@ -616,6 +630,28 @@ def _extract_responses_output_items(value: Any) -> list[Any] | None:return output if isinstance(output, list) else None+def _format_message_body(msg: dict[str, Any], options: FormatterOptions | None) -> list[str]:+ """Format what sits under a message header: its Responses item or content, then its tool calls."""+ lines: list[str] = []++ responses_lines = _format_responses_item(msg, options)+ content = msg.get("content", "")+ 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)+ lines.extend(content_lines)++ tool_calls = msg.get("tool_calls", [])+ if tool_calls:+ lines.append("")+ lines.extend(format_tool_calls(tool_calls))++ return lines++def format_messages_array(messages: list[Any], options: FormatterOptions | None = None) -> list[str]:"""Format an array of message objects without header.@@ -638,25 +674,20 @@ def format_messages_array(messages: list[Any], options: FormatterOptions | None# SDKs record non-string roles, which crash `.upper()`.role = str(msg.get("role") or msg.get("type") or "unknown")- content = msg.get("content", "")- tool_calls = msg.get("tool_calls", [])lines.append("")lines.append(f"[{i + 1}] {role.upper()}")lines.append("")- 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)- lines.extend(content_lines)-- if tool_calls:- lines.append("")- lines.extend(format_tool_calls(tool_calls))+ try:+ body_lines = _format_message_body(msg, options)+ except RenderBudgetExceeded:+ raise+ except Exception:+ # Customer payloads can break any shape assumption in the body formatters, so one+ # malformed message degrades to its own repr and the rest of the trace still renders.+ body_lines, _ = truncate_content(safe_extract_text(msg), options)+ lines.extend(body_lines)# Add separator between messages (but not after the last one)if i < len(messages) - 1:diff --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 c8799936f1d4..6a1e49ddf286 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@@ -217,9 +217,16 @@ class TestExtractTextContent:assert "World" in resultassert "function" not in result- def test_extract_from_tool_use_block(self):+ @parameterized.expand(+ [+ ("without_partial_json", {}),+ ("dict_partial_json", {"partial_json": {"city": "Paris"}}),+ ("int_partial_json", {"partial_json": 5}),+ ]+ )+ def test_extract_from_tool_use_block(self, _name, extra_fields):"""Should format tool_use blocks as function calls."""- content = [{"type": "tool_use", "name": "get_weather"}]+ content = [{"type": "tool_use", "name": "get_weather", **extra_fields}]result = extract_text_content(content)assert "get_weather()" in result@@ -514,6 +521,43 @@ class TestEdgeCases:# Empty string should be treated as no inputassert len(lines) == 0+ def test_malformed_message_does_not_stop_the_render(self):+ messages = [+ {"role": "assistant", "content": "first", "tool_calls": 5},+ {"role": "user", "content": "second"},+ ]+ result = "\n".join(format_input_messages(messages))+ assert "first" in result+ assert "second" in result++ @parameterized.expand(+ [+ ("dict", {"kind": "oops"}),+ ("list", ["oops"]),+ ("int", 5),+ ]+ )+ def test_large_malformed_block_keeps_the_blocks_after_it(self, _name, block_type):+ content = [+ {"type": block_type, "text": "A" * 1200},+ {"type": "text", "text": "keep me"},+ ]+ result = extract_text_content(content)+ assert "A" * 1200 in result+ assert "keep me" in result++ @parameterized.expand(+ [+ ("dict", {"a": 1}),+ ("list", ["a"]),+ ("int", 5),+ ]+ )+ def test_non_string_item_type_keeps_its_payload(self, _name, item_type):+ item = {"type": item_type, "name": "search", "arguments": '{"q":"x"}', "status": "completed"}+ assert 'search(q="x")' in "\n".join(format_input_messages([item]))+ assert 'search(q="x")' in "\n".join(format_output_messages(None, [item]))+class TestResponsesApiItems:@parameterized.expand(