From d7f472d92123480346585cfd3cce0fef0aab41b1 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 20 Nov 2026 15:21:31 -0500 Subject: [PATCH] fix(ai): use the context distinct id for streamed generations Streamed $ai_generation events fell back to the trace id even inside an identified context, unlike non-streamed calls. Check the context's distinct id before the trace id. Fixes #1284 --- .../streaming-context-distinct-id.md | 5 +++++ posthog/ai/utils.py | 7 +++++-- posthog/test/ai/anthropic/test_anthropic.py | 21 +++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 .sampo/changesets/streaming-context-distinct-id.md diff --git a/.sampo/changesets/streaming-context-distinct-id.md b/.sampo/changesets/streaming-context-distinct-id.md new file mode 100644 index 000000000..8f535ea05 --- /dev/null +++ b/.sampo/changesets/streaming-context-distinct-id.md @@ -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. diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 62bd937a6..a9c85841a 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -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"), ) diff --git a/posthog/test/ai/anthropic/test_anthropic.py b/posthog/test/ai/anthropic/test_anthropic.py index 1bdb0051d..8706df7aa 100644 --- a/posthog/test/ai/anthropic/test_anthropic.py +++ b/posthog/test/ai/anthropic/test_anthropic.py @@ -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")