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

Use the context's distinct ID for streamed LLM analytics generations when no `posthog_distinct_id` is passed, as non-streamed calls already do.
7 changes: 5 additions & 2 deletions posthog/ai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1318,12 +1318,15 @@ def capture_streaming_event(

# Send event to PostHog
if callable(getattr(ph_client, "capture_ai", None)):
distinct_id = _user_distinct_id(
event_data.get("distinct_id")
) or _user_distinct_id(contexts.get_context_distinct_id())
_capture_ai_event(
ph_client,
"$ai_generation",
distinct_id=_user_distinct_id(event_data.get("distinct_id")) or trace_id,
distinct_id=distinct_id or trace_id,
properties=event_properties,
groups=event_data.get("groups"),
personless=_user_distinct_id(event_data.get("distinct_id")) is None,
personless=distinct_id is None,
options=event_data.get("options"),
)
21 changes: 21 additions & 0 deletions posthog/test/ai/anthropic/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2087,6 +2087,27 @@ def test_explicit_distinct_id_overrides_outer_context(
assert call_args["distinct_id"] == "explicit-user-789"


def test_streaming_uses_outer_context_distinct_id(mock_client):
with patch(
"anthropic.resources.Messages.create",
return_value=iter(anthropic_stream_with_cache_ttl()),
):
client = Anthropic(api_key="test-key", posthog_client=mock_client)
with new_context():
identify_context("outer-user-456")
list(
client.messages.create(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
)

call_args = mock_client.capture_ai.call_args[1]
assert call_args["distinct_id"] == "outer-user-456"
assert "options" not in call_args


ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")


Expand Down