diff --git a/.sampo/changesets/ai-tool-span-error-details.md b/.sampo/changesets/ai-tool-span-error-details.md new file mode 100644 index 000000000..1c542ef4e --- /dev/null +++ b/.sampo/changesets/ai-tool-span-error-details.md @@ -0,0 +1,5 @@ +--- +posthog: patch +--- + +Tool spans that report an error now always carry `$ai_error`: in privacy mode it is the fixed label `ToolError`, and outside it media is redacted and empty content gives the same label. Claude Agent SDK tool inputs are redacted when the span is sent, so privacy and media capture settings changed while a tool ran apply. Closing the `query()` stream early now sends tool spans still waiting for a result, and LangChain `PostHogMiddleware` tool spans set `$ai_span_type: "tool"`. diff --git a/posthog/ai/claude_agent_sdk/__init__.py b/posthog/ai/claude_agent_sdk/__init__.py index 4e492d313..8d03b1135 100644 --- a/posthog/ai/claude_agent_sdk/__init__.py +++ b/posthog/ai/claude_agent_sdk/__init__.py @@ -151,7 +151,7 @@ async def query( yield message return - async for message in processor.query( + stream = processor.query( prompt=prompt, options=options, transport=transport, @@ -160,5 +160,11 @@ async def query( posthog_privacy_mode=posthog_privacy_mode, posthog_groups=posthog_groups, posthog_options=posthog_options, - ): - yield message + ) + try: + async for message in stream: + yield message + finally: + # Closing this stream early must also close the processor's, so it + # sends the tool spans still waiting for a result. + await stream.aclose() diff --git a/posthog/ai/claude_agent_sdk/processor.py b/posthog/ai/claude_agent_sdk/processor.py index d607b8367..066f41bc5 100644 --- a/posthog/ai/claude_agent_sdk/processor.py +++ b/posthog/ai/claude_agent_sdk/processor.py @@ -34,6 +34,7 @@ from posthog.ai.utils import ( _ai_event_options, _capture_processor_event, + _format_tool_error, _resolve_ai_client, finalize_ai_content, with_privacy_mode as _with_privacy_mode, @@ -72,24 +73,9 @@ class _PendingToolSpan: groups: Dict[str, Any] extra_options: Optional[Dict[str, Any]] = None privacy: bool = False - - -_TOOL_SPAN_CONTENT_PROPERTIES = ("$ai_input_state", "$ai_output_state", "$ai_error") - - -def _tool_error_text(content: Any) -> str: - """The `$ai_error` text for an errored tool result's content.""" - if isinstance(content, str): - return content - if isinstance(content, list): - texts = [ - item["text"] - for item in content - if isinstance(item, dict) and isinstance(item.get("text"), str) - ] - if texts: - return "\n".join(texts) - return "" if content is None else str(content) + # Redacted into `$ai_input_state` when the span is sent, so privacy and + # media capture settings changed while the tool ran still apply. + tool_input: Any = None class _GenerationTracker: @@ -654,11 +640,6 @@ def _start_tool_span( **extra_props, } - if _with_privacy_mode(self._client, privacy, True): - properties["$ai_input_state"] = finalize_ai_content( - _ensure_serializable(block.input), self._client - ) - span = _PendingToolSpan( properties=properties, start_time=time.time(), @@ -666,6 +647,7 @@ def _start_tool_span( groups=groups, extra_options=extra_options, privacy=privacy, + tool_input=_ensure_serializable(block.input), ) tool_use_id = getattr(block, "id", None) if tool_use_id is None: @@ -693,11 +675,15 @@ def _finish_tool_span( properties["$ai_latency"] = time.time() - span.start_time is_error = bool(getattr(block, "is_error", False)) properties["$ai_is_error"] = is_error + output = None if _with_privacy_mode(self._client, privacy, True): - content = format_tool_result_content(block, self._client) - properties["$ai_output_state"] = finalize_ai_content(content, self._client) - if is_error: - properties["$ai_error"] = _tool_error_text(content) + output = finalize_ai_content( + format_tool_result_content(block, self._client), self._client + ) + properties["$ai_output_state"] = output + if is_error: + # In privacy mode this is a fixed label, so output isn't needed. + properties["$ai_error"] = _format_tool_error(self._client, privacy, output) self._capture_tool_span(span) def _flush_tool_spans(self, pending: Dict[str, _PendingToolSpan]) -> None: @@ -709,9 +695,18 @@ def _flush_tool_spans(self, pending: Dict[str, _PendingToolSpan]) -> None: def _capture_tool_span(self, span: _PendingToolSpan) -> None: if _with_privacy_mode(self._client, span.privacy, True) is None: # Privacy may have been enabled while the tool ran; drop content - # buffered before then. - for key in _TOOL_SPAN_CONTENT_PROPERTIES: - span.properties.pop(key, None) + # buffered before then (or passed in properties) and keep only + # the error label. + span.properties.pop("$ai_input_state", None) + span.properties.pop("$ai_output_state", None) + if "$ai_error" in span.properties: + span.properties["$ai_error"] = _format_tool_error( + self._client, True, None + ) + else: + span.properties["$ai_input_state"] = finalize_ai_content( + span.tool_input, self._client + ) resolved_id = self._resolve_distinct_id(span.distinct_id) trace_id = span.properties["$ai_trace_id"] self._capture_event( diff --git a/posthog/ai/langchain/callbacks.py b/posthog/ai/langchain/callbacks.py index 3b459a51c..e8c4725b7 100644 --- a/posthog/ai/langchain/callbacks.py +++ b/posthog/ai/langchain/callbacks.py @@ -43,6 +43,7 @@ from posthog.ai.gateway import warn_if_posthog_ai_gateway from posthog.ai.utils import ( + _format_tool_error, _ai_event_options, _capture_ai_event, _extract_cache_creation_ttl_breakdown, @@ -611,10 +612,8 @@ def _capture_trace_or_span( # normally, with the error as a ToolMessage. Only the tool's own # span is the error, not a chain that returns the message. event_properties["$ai_is_error"] = True - event_properties["$ai_error"] = with_privacy_mode( - self._ph_client, - self._privacy_mode, - _tool_message_text(outputs), + event_properties["$ai_error"] = _format_tool_error( + self._ph_client, self._privacy_mode, outputs.content ) _capture_ai_event( @@ -870,19 +869,6 @@ def _convert_lc_tool_calls_to_oai( return tool_calls -def _tool_message_text(message: ToolMessage) -> str: - """The text of a ToolMessage, for `$ai_error`.""" - content = message.content - if isinstance(content, str): - return content - texts = [ - item if isinstance(item, str) else item.get("text", "") - for item in content - if isinstance(item, str) or isinstance(item, dict) - ] - return "\n".join(text for text in texts if text) - - def _convert_message_to_dict(message: BaseMessage) -> dict[str, Any]: # assistant message if isinstance(message, HumanMessage): diff --git a/posthog/ai/langchain/middleware.py b/posthog/ai/langchain/middleware.py index 669a2d010..73c4e3d9e 100644 --- a/posthog/ai/langchain/middleware.py +++ b/posthog/ai/langchain/middleware.py @@ -286,6 +286,7 @@ def _start_tool(self, request: ToolCallRequest) -> UUID | None: run_id, _root_id(request.state), name=name, + span_type="tool", ) except Exception: log.exception("Failed to prepare PostHog LangChain tool telemetry") diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 36c4c3377..43df35e63 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -1,6 +1,7 @@ import asyncio import copy import functools +import json import logging import re import sys @@ -1083,6 +1084,44 @@ def _format_ai_error( return describe(exc) +_PRIVACY_SAFE_TOOL_ERROR = "ToolError" + + +def _format_tool_error( + ph_client: Any, privacy_mode: Optional[bool], content: Any +) -> str: + """ + The `$ai_error` value for a tool result the tool reported as an error. + + The result content can echo prompts and user data, so privacy mode keeps + only a fixed label. + """ + if _privacy_mode_enabled(ph_client, privacy_mode): + return _PRIVACY_SAFE_TOOL_ERROR + # The content can carry media (data URLs, base64 blocks), so redact it + # the same way as `$ai_output_state` before building the message. + content = finalize_ai_content(content, ph_client) + if content is None or content == "" or content == []: + # No error text: a fixed label rather than "null" or "[]". + return _PRIVACY_SAFE_TOOL_ERROR + if isinstance(content, str): + return content + if isinstance(content, list): + # LangChain content mixes plain strings and dict blocks. + texts = [ + block if isinstance(block, str) else block["text"] + for block in content + if isinstance(block, str) + or (isinstance(block, dict) and isinstance(block.get("text"), str)) + ] + if texts: + return "\n".join(texts) + try: + return json.dumps(content, default=str) + except Exception: + return str(content) + + _MCP_TOOL_CREDENTIAL_FIELDS = ("headers", "authorization") _REDACTED_MCP_CREDENTIAL = "[REDACTED]" diff --git a/posthog/test/ai/claude_agent_sdk/test_processor.py b/posthog/test/ai/claude_agent_sdk/test_processor.py index cb0f05421..331c01d3a 100644 --- a/posthog/test/ai/claude_agent_sdk/test_processor.py +++ b/posthog/test/ai/claude_agent_sdk/test_processor.py @@ -559,10 +559,12 @@ async def query(messages): spans = [p for name, p in self._events(mock_client) if name == "$ai_span"] assert len(spans) == 1 - for key in ("$ai_input_state", "$ai_output_state", "$ai_error"): + for key in ("$ai_input_state", "$ai_output_state"): assert key not in spans[0] if result_arrives: assert spans[0]["$ai_is_error"] is True + # Privacy mode keeps a fixed label so the span still reads as an error. + assert spans[0]["$ai_error"] == "ToolError" @pytest.mark.asyncio async def test_span_carries_tool_error(self, processor, mock_client): @@ -600,7 +602,7 @@ async def test_privacy_mode_keeps_error_flag_but_redacts_result(self, mock_clien spans = [p for name, p in self._events(mock_client) if name == "$ai_span"] assert spans[0]["$ai_is_error"] is True assert "$ai_latency" in spans[0] - assert "$ai_error" not in spans[0] + assert spans[0]["$ai_error"] == "ToolError" assert "$ai_output_state" not in spans[0] assert "$ai_input_state" not in spans[0] @@ -635,6 +637,60 @@ async def test_pending_span_is_flushed_when_query_ends_without_result( assert len(spans) == 1 assert "$ai_is_error" not in spans[0] + @pytest.mark.asyncio + async def test_full_capture_disabled_mid_tool_redacts_buffered_input( + self, processor, mock_client + ): + data_url = "data:image/png;base64," + "A" * 3000 + turn = [ + _make_message_start(), + _make_assistant_message( + tool_uses=[{"id": "tu_1", "name": "Look", "input": {"image": data_url}}] + ), + _make_message_stop(), + UserMessage(content=[ToolResultBlock(tool_use_id="tu_1", content="ok")]), + _make_result_message(), + ] + mock_client.enable_full_ai_capture = True + + async def query(messages): + for i, msg in enumerate(messages): + if i == 3: + # Full capture turns off while the tool runs. + mock_client.enable_full_ai_capture = False + yield msg + + with patch( + "posthog.ai.claude_agent_sdk.processor.original_query", + side_effect=lambda **kw: query(turn), + ): + async for _ in processor.query(prompt="go", options=ClaudeAgentOptions()): + pass + + [props] = [p for name, p in self._events(mock_client) if name == "$ai_span"] + assert props["$ai_input_state"]["image"] != data_url + assert "AAAA" not in props["$ai_input_state"]["image"] + + @pytest.mark.asyncio + @pytest.mark.parametrize("entry_point", ["module_query", "processor_query"]) + async def test_pending_span_is_sent_when_caller_stops_early( + self, mock_client, entry_point + ): + messages = self._tool_turn(ToolResultBlock(tool_use_id="tu_1", content="ok")) + with patch( + "posthog.ai.claude_agent_sdk.processor.original_query", + side_effect=lambda **kw: _fake_query(messages), + ): + stream = _claude_query(entry_point, mock_client, "user", None) + async for message in stream: + if isinstance(message, AssistantMessage): + break + await stream.aclose() + + [props] = [p for name, p in self._events(mock_client) if name == "$ai_span"] + assert props["$ai_span_name"] == "Bash" + assert "$ai_is_error" not in props + class TestTraceEmission: @pytest.mark.asyncio @@ -754,6 +810,35 @@ async def test_client_without_privacy_mode_captures_content(self): properties = client.capture_ai.call_args.kwargs["properties"] assert properties["$ai_input"] == [{"role": "user", "content": "visible"}] + @pytest.mark.asyncio + async def test_privacy_mode_drops_input_state_passed_in_properties( + self, mock_client + ): + proc = PostHogClaudeAgentProcessor( + client=mock_client, distinct_id="user", privacy_mode=True + ) + messages = TestToolSpanEmission._tool_turn( + ToolResultBlock(tool_use_id="tu_1", content="a.txt") + ) + + with patch( + "posthog.ai.claude_agent_sdk.processor.original_query", + side_effect=lambda **kw: _fake_query(messages), + ): + async for _ in proc.query( + prompt="go", + options=ClaudeAgentOptions(), + posthog_properties={"$ai_input_state": "secret"}, + ): + pass + + [span] = [ + c.kwargs["properties"] + for c in mock_client.capture_ai.call_args_list + if c.kwargs["event"] == "$ai_span" + ] + assert "$ai_input_state" not in span + @pytest.mark.asyncio async def test_privacy_mode_redacts_tool_input(self, mock_client): proc = PostHogClaudeAgentProcessor( diff --git a/posthog/test/ai/langchain/test_callbacks.py b/posthog/test/ai/langchain/test_callbacks.py index e57da92b9..fc6c36979 100644 --- a/posthog/test/ai/langchain/test_callbacks.py +++ b/posthog/test/ai/langchain/test_callbacks.py @@ -1668,7 +1668,7 @@ def get_weather(city: str) -> str: spans = _tool_spans(mock_client) assert spans[0]["$ai_is_error"] is True - assert spans[0]["$ai_error"] is None + assert spans[0]["$ai_error"] == "ToolError" assert spans[0]["$ai_output_state"] is None diff --git a/posthog/test/ai/langchain/test_middleware.py b/posthog/test/ai/langchain/test_middleware.py index 609d9e882..7a3ae5503 100644 --- a/posthog/test/ai/langchain/test_middleware.py +++ b/posthog/test/ai/langchain/test_middleware.py @@ -576,6 +576,7 @@ def handler(inner_request: ToolCallRequest) -> ToolMessage: span = _event(client, "$ai_span")["properties"] assert span["$ai_is_error"] is True assert "Invalid arguments" in span["$ai_error"] + assert span["$ai_span_type"] == "tool" assert "$ai_parent_id" in span client.reset_mock() diff --git a/posthog/test/ai/test_utils.py b/posthog/test/ai/test_utils.py index 49add2881..8b1f92c1d 100644 --- a/posthog/test/ai/test_utils.py +++ b/posthog/test/ai/test_utils.py @@ -6,7 +6,11 @@ import pytest from posthog.ai.types import TokenUsage -from posthog.ai.utils import merge_usage_stats, serialize_raw_usage +from posthog.ai.utils import ( + _format_tool_error, + merge_usage_stats, + serialize_raw_usage, +) class PydanticUsage: @@ -164,3 +168,51 @@ def test_merge_usage_stats_invalid_mode_does_not_mutate_target(): with pytest.raises(ValueError, match="Invalid mode: unknown"): merge_usage_stats(target, TokenUsage(input_tokens=4), mode="unknown") assert target == {"input_tokens": 10} + + +def test_format_tool_error_redacts_media_blocks(): + client = SimpleNamespace(privacy_mode=False, enable_full_ai_capture=False) + content = [ + { + "type": "image", + "source_type": "base64", + "data": "iVBORw0KGgo" + "A" * 3000, + "mime_type": "image/png", + } + ] + + error = _format_tool_error(client, False, content) + + assert "iVBORw0KGgo" not in error + assert "redacted" in error + + +def test_format_tool_error_redacts_data_url_string(): + client = SimpleNamespace(privacy_mode=False, enable_full_ai_capture=False) + + error = _format_tool_error(client, False, "data:image/png;base64," + "A" * 3000) + + assert "AAAA" not in error + + +@pytest.mark.parametrize("content", [None, "", []]) +def test_format_tool_error_labels_empty_content(content): + client = SimpleNamespace(privacy_mode=False, enable_full_ai_capture=False) + + assert _format_tool_error(client, False, content) == "ToolError" + + +@pytest.mark.parametrize( + "content, expected", + [ + ( + ["Connection refused", {"type": "text", "text": "details"}], + "Connection refused\ndetails", + ), + (["Connection refused", "timeout"], "Connection refused\ntimeout"), + ], +) +def test_format_tool_error_keeps_plain_string_items(content, expected): + client = SimpleNamespace(privacy_mode=False, enable_full_ai_capture=False) + + assert _format_tool_error(client, False, content) == expected