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-results.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
posthog: patch
---

Send tool results on AI tool spans. Claude Agent SDK tool spans now wait for the tool's result and carry `$ai_output_state`, `$ai_is_error`, `$ai_error` and `$ai_latency`. LangChain tool spans set `$ai_span_type: "tool"` and mark tools that return an error `ToolMessage`, and converted `ToolMessage`s keep `tool_call_id`, `name` and an error `status`.
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()
26 changes: 17 additions & 9 deletions posthog/ai/claude_agent_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from posthog.ai.claude_agent_sdk.processor import (
PostHogClaudeAgentProcessor,
_GenerationTracker,
_ToolSpanTracker,
_from_subagent,
_promote_input,
_starts_generation,
Expand Down Expand Up @@ -114,6 +115,7 @@ def __init__(

# Shared state across turns
self._tracker = _GenerationTracker()
self._tool_spans = _ToolSpanTracker(self._processor)
self._generation_index = 0
self._current_generation_span_id: Optional[str] = None
self._current_input: Optional[List[Dict[str, Any]]] = None
Expand Down Expand Up @@ -186,16 +188,21 @@ def _process_message(self, message: Any) -> None:
elif isinstance(message, AssistantMessage):
self._process_assistant_message(message)

elif isinstance(message, UserMessage) and not _from_subagent(message):
if not self._tracker.had_any_stream_events:
# Without stream events, a tool result ends the assistant turn;
# the result fallback reports the final turn only.
self._pending_output = []
self._next_input = _format_user_input(
message.content, self._processor._client, self._next_input
)
elif isinstance(message, UserMessage):
if not _from_subagent(message):
if not self._tracker.had_any_stream_events:
# Without stream events, a tool result ends the assistant
# turn; the result fallback reports the final turn only.
self._pending_output = []
self._next_input = _format_user_input(
message.content, self._processor._client, self._next_input
)
# Subagent tool spans are tracked too, so match their results.
self._tool_spans.finish(message.content)

elif isinstance(message, ResultMessage):
# The turn is over: spans still waiting for a result go out now.
self._tool_spans.flush()
if not self._tracker.had_any_stream_events:
self._processor._emit_generation_from_result(
message,
Expand All @@ -217,7 +224,7 @@ def _process_assistant_message(self, message: "AssistantMessage") -> None:
parent_id = self._tracker.current_span_id or self._current_generation_span_id
for block in message.content:
if isinstance(block, ToolUseBlock):
self._processor._emit_tool_span(
self._tool_spans.start(
block,
self._trace_id,
parent_id,
Expand All @@ -237,6 +244,7 @@ async def disconnect(self) -> None:
"""
# Emit the trace event covering the entire session
try:
self._tool_spans.flush()
latency = time.time() - self._query_start
resolved_id = self._processor._resolve_distinct_id(self._distinct_id)

Expand Down
Loading