Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/ai-tool-span-error-details.md
Original file line number Diff line number Diff line change
@@ -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"`.
12 changes: 9 additions & 3 deletions posthog/ai/claude_agent_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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()
55 changes: 25 additions & 30 deletions posthog/ai/claude_agent_sdk/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -654,18 +640,14 @@ 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(),
distinct_id=distinct_id,
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:
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Comment thread
DanielVisca marked this conversation as resolved.
Resolved
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(
Expand Down
20 changes: 3 additions & 17 deletions posthog/ai/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Comment thread
DanielVisca marked this conversation as resolved.
Resolved
)

_capture_ai_event(
Expand Down Expand Up @@ -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):
Expand Down
1 change: 1 addition & 0 deletions posthog/ai/langchain/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
39 changes: 39 additions & 0 deletions posthog/ai/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import copy
import functools
import json
import logging
import re
import sys
Expand Down Expand Up @@ -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):
Comment thread
DanielVisca marked this conversation as resolved.
Resolved
# 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)
Comment thread
DanielVisca marked this conversation as resolved.
Resolved
except Exception:
return str(content)


_MCP_TOOL_CREDENTIAL_FIELDS = ("headers", "authorization")
_REDACTED_MCP_CREDENTIAL = "[REDACTED]"

Expand Down
89 changes: 87 additions & 2 deletions posthog/test/ai/claude_agent_sdk/test_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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]

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion posthog/test/ai/langchain/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
1 change: 1 addition & 0 deletions posthog/test/ai/langchain/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading