: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 malformed tool metadata failing a trace text view (#100893)
posthog[bot]a6b7f9a5e1b7
diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.pyindex 0a6849fd7de8..25dab1bed9e0 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_tool_formatter.py@@ -147,13 +147,23 @@ class TestFormatTools:result = "\n".join(lines)assert "create_user(username: string, email: string)" in result- def test_tool_with_no_description(self):- """Should handle tool with no description."""- tools = [{"name": "mystery_tool", "input_schema": {"type": "object", "properties": {}}}]+ @parameterized.expand(+ [+ ("missing", {}),+ ("a list", {"description": ["first", "second"]}),+ ("an object", {"description": {"text": "Does things."}}),+ ("a number", {"description": 42}),+ ]+ )+ def test_tool_with_unusable_description(self, _name, description_field):+ """Should render the signature alone when the description is not usable text."""+ tools = [{"name": "mystery_tool", "input_schema": {"type": "object", "properties": {}}, **description_field}]+lines = format_tools(tools)result = "\n".join(lines)++ assert "AVAILABLE TOOLS: 1" in resultassert "mystery_tool()" in result- # Should not have description lineassert "N/A" not in resultdef test_tool_with_multiline_description(self):@@ -171,7 +181,7 @@ class TestFormatTools:assert "third line" not in resultdef test_google_gemini_format(self):- """Should handle Google/Gemini functionDeclarations format."""+ """Should handle Google/Gemini functionDeclarations format, and skip malformed declarations."""tools = [{"functionDeclarations": [@@ -185,17 +195,22 @@ class TestFormatTools:},"required": ["query"],},- }+ },+ "not a declaration",+ None,]}]lines = format_tools(tools)result = "\n".join(lines)+assert "AVAILABLE TOOLS: 1" in resultassert "search(query: string)" in result+ assert "Search the web." in result+ assert "UNKNOWN" not in resultdef test_invalid_tool_format(self):- """Should skip invalid tool entries."""+ """Should skip invalid tool entries, and count only the tools it can render."""tools = ["not a dict",{"name": "valid_tool", "description": "A valid tool."},@@ -203,9 +218,19 @@ class TestFormatTools:]lines = format_tools(tools)result = "\n".join(lines)- assert "AVAILABLE TOOLS: 3" in result+ assert "AVAILABLE TOOLS: 1" in resultassert "valid_tool()" in result+ def test_malformed_declarations_do_not_collapse_a_short_list(self):+ """Should keep a valid signature visible when malformed declarations sit beside it."""+ tools = [{"functionDeclarations": [{"name": "search"}, *["junk"] * 5]}]++ result = "\n".join(format_tools(tools, {"include_markers": False}))++ assert "AVAILABLE TOOLS: 1" in result+ assert "search()" in result+ assert "[+]" not in result+def test_tool_with_nested_schema(self):"""Should handle tools with complex nested schemas."""tools = [@@ -304,6 +329,22 @@ class TestEdgeCases:assert "AVAILABLE TOOLS: 5" in resultassert "tool0()" in result+ @parameterized.expand(+ [+ ("one bundle", 1, 6),+ ("two bundles", 2, 3),+ ]+ )+ def test_gemini_bundles_count_their_declarations(self, _name, bundle_count, per_bundle):+ tools = [+ {"functionDeclarations": [{"name": f"tool{bundle}_{i}"} for i in range(per_bundle)]}+ for bundle in range(bundle_count)+ ]++ result = "\n".join(format_tools(tools, {"include_markers": False}))++ assert f"[+] AVAILABLE TOOLS: {bundle_count * per_bundle}" in result+def test_six_tools_collapsed(self):"""Should collapse tool list with 6 tools (just over threshold)."""tools = [{"name": f"tool{i}", "description": f"Tool {i}."} for i in range(6)]@@ -324,13 +365,34 @@ class TestEdgeCases:@parameterized.expand([- ("list", ["query", "limit"]),- ("string", "query"),+ ("list", ["query", "limit"], "search()"),+ ("string", "query", "search()"),+ ("non-dict property value", {"query": "string", "limit": {"type": "integer"}}, "search(limit?: integer)"),])- def test_unusable_properties_schema_still_renders_the_tool(self, _name, properties):+ def test_unusable_properties_schema_still_renders_the_tool(self, _name, properties, expected_signature):tools = [{"name": "search", "description": "Search things.", "input_schema": {"properties": properties}}]result = "\n".join(format_tools(tools))- assert "search()" in result+ assert expected_signature in result++ @parameterized.expand(+ [+ ("null", None),+ ("a number", 3),+ ("a boolean", True),+ ]+ )+ def test_unusable_required_list_marks_every_parameter_optional(self, _name, required):+ tools = [+ {+ "name": "search",+ "description": "Search things.",+ "input_schema": {"properties": {"query": {"type": "string"}}, "required": required},+ }+ ]++ result = "\n".join(format_tools(tools))++ assert "search(query?: string)" in resultdiff --git a/products/ai_observability/backend/text_repr/formatters/tool_formatter.py b/products/ai_observability/backend/text_repr/formatters/tool_formatter.pyindex a65b92917162..e89938299e29 100644--- a/products/ai_observability/backend/text_repr/formatters/tool_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/tool_formatter.py@@ -10,6 +10,8 @@ import jsonimport base64from typing import TYPE_CHECKING, Any, TypedDict+from posthog.dataclasses import frozen+from .constants import DEFAULT_TOOLS_COLLAPSE_THRESHOLDif TYPE_CHECKING:@@ -29,84 +31,114 @@ class Tool(TypedDict, total=False):parameters: dict[str, Any] # Google/Gemini format (unwrapped)-def _format_tools_list(tools_list: list[Any]) -> str:+@frozen+class _ToolDefinition:+ """A tool reduced to the fields a signature needs, whatever provider format it came in."""++ name: str+ description: str+ parameter_schema: Any+++def _unwrap_declarations(tool: dict[str, Any]) -> list[Any]:+ """Unwrap the Google/Gemini format: {functionDeclarations: [{name, description, parameters}]}."""+ declarations = tool.get("functionDeclarations")+ if isinstance(declarations, list):+ return declarations+ return [tool]+++def _flatten_tools(tools_list: list[Any]) -> list[dict[str, Any]]:+ """+ Unwrap every container, so a Google/Gemini bundle counts as its tools and not as one item.+ Drops what cannot render, so the count and the collapse decision see the real tools."""- Format a list of tools into text representation.+ flattened: list[dict[str, Any]] = []+ for tool in tools_list:+ if not isinstance(tool, dict):+ continue+ flattened.extend(declaration for declaration in _unwrap_declarations(tool) if isinstance(declaration, dict))+ return flattened+++def _read_description(source: dict[str, Any]) -> str:+ """SDKs record non-string descriptions, which crash `.split()` in `_format_description`."""+ description = source.get("description", "N/A")+ return description if isinstance(description, str) else "N/A"+++def _read_tool(tool: dict[str, Any]) -> _ToolDefinition:+ """Read name, description and parameter schema out of any supported provider format."""+ if "function" in tool and isinstance(tool["function"], dict):+ # OpenAI format: {type: 'function', function: {name, description, parameters}}+ function = tool["function"]+ return _ToolDefinition(+ name=str(function.get("name", "unknown")),+ description=_read_description(function),+ parameter_schema=function.get("parameters"),+ )++ if "name" in tool:+ # Multiple formats:+ # - Anthropic: {name, description, input_schema} (snake_case)+ # - OpenAI: {name, description, inputSchema} (camelCase)+ # - Google/Gemini unwrapped: {name, description, parameters}+ return _ToolDefinition(+ name=str(tool["name"]),+ description=_read_description(tool),+ parameter_schema=tool.get("input_schema") or tool.get("inputSchema") or tool.get("parameters"),+ )++ # Unknown format+ return _ToolDefinition(+ name=str(tool.get("type", "UNKNOWN")), description=json.dumps(tool)[:100], parameter_schema=None+ )+++def _format_signature(name: str, schema: Any) -> str:+ """Build a function signature such as `read_file(path: string, lines?: string)`."""+ # SDKs record non-object `properties`, which crashes `.items()` below.+ if not isinstance(schema, dict) or not isinstance(schema.get("properties"), dict):+ return f"{name}()"++ # SDKs record a `required` that holds no members, which crashes the `in` test below.+ required = schema.get("required", [])+ if not isinstance(required, list | tuple | set):+ required = []++ params: list[str] = []+ for param_name, param_info in schema["properties"].items():+ if not isinstance(param_info, dict):+ continue+ param_type = param_info.get("type", "any")+ optional_marker = "" if param_name in required else "?"+ params.append(f"{param_name}{optional_marker}: {param_type}")++ return f"{name}({', '.join(params)})"+++def _format_description(description: str) -> str:+ """Keep only the first line of the description, and end it with a period."""+ first_line = description.split("\n")[0]+ first_sentence = first_line.split(". ")[0]+ return first_sentence if first_sentence.endswith(".") else f"{first_sentence}."+++def _format_tools_list(tools_list: list[dict[str, Any]]) -> str:+ """+ Format a flattened list of tools into text representation.Returns the formatted text as a single string."""lines: list[str] = []for tool in tools_list:- # Skip non-dict entries- if not isinstance(tool, dict):- continue+ definition = _read_tool(tool)- # Handle Google/Gemini format: {functionDeclarations: [{name, description, parameters}]}- tools_to_process: list[Any] = []- if "functionDeclarations" in tool and isinstance(tool["functionDeclarations"], list):- tools_to_process = tool["functionDeclarations"]- else:- tools_to_process = [tool]-- for t in tools_to_process:- # Skip non-dict entries in tools_to_process- if not isinstance(t, dict):- continue- name: str- desc: str- schema: dict[str, Any] | None = None-- # Handle different tool formats- if "function" in t and isinstance(t["function"], dict):- # OpenAI format: {type: 'function', function: {name, description, parameters}}- name = t["function"].get("name", "unknown")- desc = t["function"].get("description", "N/A")- schema = t["function"].get("parameters")- elif "name" in t:- # Multiple formats:- # - Anthropic: {name, description, input_schema} (snake_case)- # - OpenAI: {name, description, inputSchema} (camelCase)- # - Google/Gemini unwrapped: {name, description, parameters}- name = t["name"]- desc = t.get("description", "N/A")- schema = t.get("input_schema") or t.get("inputSchema") or t.get("parameters")- else:- # Unknown format- name = t.get("type", "UNKNOWN")- desc = json.dumps(t)[:100]- schema = None-- # Build function signature from schema- signature = f"{name}("- # SDKs record non-object `properties`, which crashes `.items()` below.- if isinstance(schema, dict) and isinstance(schema.get("properties"), dict):- properties = schema["properties"]- required = schema.get("required", [])- params: list[str] = []-- for param_name, param_info in properties.items():- if not isinstance(param_info, dict):- continue- param_type = param_info.get("type", "any")- if param_name in required:- params.append(f"{param_name}: {param_type}")- else:- params.append(f"{param_name}?: {param_type}")-- signature += ", ".join(params)- signature += ")"-- # Show signature- lines.append("")- lines.append(f" {signature}")-- # Show only first line of description (up to first newline or sentence)- if desc and desc != "N/A":- # Split by newline first, then by sentence- first_line = desc.split("\n")[0]- first_sentence = first_line.split(". ")[0]- final_sentence = first_sentence if first_sentence.endswith(".") else f"{first_sentence}."- lines.append(f" {final_sentence}")+ lines.append("")+ lines.append(f" {_format_signature(definition.name, definition.parameter_schema)}")++ if definition.description and definition.description != "N/A":+ lines.append(f" {_format_description(definition.description)}")return "\n".join(lines)@@ -139,7 +171,10 @@ def format_tools(ai_tools: Any, options: "FormatterOptions | None" = None) -> lielse:return lines- if len(tools_list) == 0:+ # The count drives the collapse threshold, so unwrap before counting.+ tools: list[dict[str, Any]] = _flatten_tools(tools_list)++ if len(tools) == 0:return linesoptions = options or {}@@ -149,12 +184,12 @@ def format_tools(ai_tools: Any, options: "FormatterOptions | None" = None) -> lilines.append("")# For long tool lists (> threshold), create expandable section- if len(tools_list) > collapse_threshold:- display_text = f"AVAILABLE TOOLS: {len(tools_list)}"+ if len(tools) > collapse_threshold:+ display_text = f"AVAILABLE TOOLS: {len(tools)}"if include_markers:# Format all tools and encode for frontend to expand- tools_content = _format_tools_list(tools_list)+ tools_content = _format_tools_list(tools)full_content = f"{display_text}\n{tools_content}"encoded_content = base64.b64encode(full_content.encode()).decode()expandable_marker = f"<<<TOOLS_EXPANDABLE|{display_text}|{encoded_content}>>>"@@ -166,8 +201,8 @@ def format_tools(ai_tools: Any, options: "FormatterOptions | None" = None) -> lireturn lines# For short tool lists (<= threshold), show full list- lines.append(f"AVAILABLE TOOLS: {len(tools_list)}")- tools_content = _format_tools_list(tools_list)+ lines.append(f"AVAILABLE TOOLS: {len(tools)}")+ tools_content = _format_tools_list(tools)lines.append(tools_content)return lines