From f3c8d48b9eb28ebc0969c563447f84f96cd972fd Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 22 Nov 2026 00:52:57 -0400 Subject: [PATCH 1/2] fix(ai): use context distinct_id for OpenAI and Gemini embedding events Embedding wrappers only looked at the posthog_distinct_id argument, so a distinct_id set via identify_context() was ignored and the $ai_embedding event was captured personless under the trace id. Resolve the id from the argument first, then the active context, matching the chat/generation path. Signed-off-by: Alex --- .../embeddings-context-distinct-id.md | 5 +++++ posthog/ai/gemini/_shared.py | 7 ++++--- posthog/ai/openai/_embeddings.py | 7 ++++--- posthog/ai/utils.py | 7 +++++++ posthog/test/ai/gemini/test_gemini.py | 19 +++++++++++++++++++ posthog/test/ai/openai/test_openai.py | 17 +++++++++++++++++ 6 files changed, 56 insertions(+), 6 deletions(-) create mode 100644 .sampo/changesets/embeddings-context-distinct-id.md diff --git a/.sampo/changesets/embeddings-context-distinct-id.md b/.sampo/changesets/embeddings-context-distinct-id.md new file mode 100644 index 000000000..f9a5f2b03 --- /dev/null +++ b/.sampo/changesets/embeddings-context-distinct-id.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +fix(ai): OpenAI and Gemini embedding events now use the context distinct ID instead of falling back to a personless trace ID diff --git a/posthog/ai/gemini/_shared.py b/posthog/ai/gemini/_shared.py index 4c30a6320..c4df28bab 100644 --- a/posthog/ai/gemini/_shared.py +++ b/posthog/ai/gemini/_shared.py @@ -12,10 +12,10 @@ from ...client import Client as PostHogClient from ..types import StreamingEventData, TokenUsage from ..utils import ( - _user_distinct_id, _ai_event_options, _capture_ai_event, _resolve_ai_client, + _resolve_distinct_id, capture_streaming_event, finalize_ai_content, _format_ai_error, @@ -275,12 +275,13 @@ def _capture_embedding_outcome( self._ph_client, privacy_mode, error ) + resolved_distinct_id = _resolve_distinct_id(distinct_id) _capture_ai_event( self._ph_client, "$ai_embedding", - distinct_id=_user_distinct_id(distinct_id) or trace_id, + distinct_id=resolved_distinct_id or trace_id, properties=event_properties, groups=groups, - personless=_user_distinct_id(distinct_id) is None, + personless=resolved_distinct_id is None, options=options, ) diff --git a/posthog/ai/openai/_embeddings.py b/posthog/ai/openai/_embeddings.py index 70a47037a..0ab0c991b 100644 --- a/posthog/ai/openai/_embeddings.py +++ b/posthog/ai/openai/_embeddings.py @@ -4,7 +4,7 @@ _capture_ai_event, _format_ai_error, _get_http_status, - _user_distinct_id, + _resolve_distinct_id, finalize_ai_content, with_privacy_mode, ) @@ -56,12 +56,13 @@ def _capture_embedding_event( } if callable(getattr(posthog_client, "capture_ai", None)): + resolved_distinct_id = _resolve_distinct_id(distinct_id) _capture_ai_event( posthog_client, "$ai_embedding", - distinct_id=_user_distinct_id(distinct_id) or trace_id, + distinct_id=resolved_distinct_id or trace_id, properties=event_properties, groups=groups, - personless=_user_distinct_id(distinct_id) is None, + personless=resolved_distinct_id is None, options=options, ) diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 62bd937a6..73e452338 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -72,6 +72,13 @@ def _user_distinct_id(distinct_id: Any) -> Any: return distinct_id if _explicit_distinct_id(distinct_id) is not None else None +def _resolve_distinct_id(distinct_id: Any) -> Any: + """The caller's distinct id, else the one from the active PostHog context, else None.""" + return _user_distinct_id(distinct_id) or _user_distinct_id( + contexts.get_context_distinct_id() + ) + + def _ai_event_options(value: Any) -> Dict[str, Any]: """Return a copy of a caller's ``posthog_options``, or ``{}`` when it is not a dict.""" if value is None: diff --git a/posthog/test/ai/gemini/test_gemini.py b/posthog/test/ai/gemini/test_gemini.py index b8aab03ed..811c41f81 100644 --- a/posthog/test/ai/gemini/test_gemini.py +++ b/posthog/test/ai/gemini/test_gemini.py @@ -1371,6 +1371,25 @@ def mock_embed_content_response_with_stats(): return mock_response +def test_embed_content_uses_context_distinct_id( + mock_client, mock_google_genai_client, mock_embed_content_response +): + from posthog import identify_context, new_context + + mock_google_genai_client.models.embed_content.return_value = ( + mock_embed_content_response + ) + + client = Client(api_key="test-key", posthog_client=mock_client) + with new_context(): + identify_context("context-user") + client.models.embed_content(model="gemini-embedding-001", contents="Hello") + + call_args = mock_client.capture_ai.call_args[1] + assert call_args["distinct_id"] == "context-user" + assert call_args["event"] == "$ai_embedding" + + def test_embed_content_basic( mock_client, mock_google_genai_client, mock_embed_content_response ): diff --git a/posthog/test/ai/openai/test_openai.py b/posthog/test/ai/openai/test_openai.py index 31aa4c14b..4b80615f0 100644 --- a/posthog/test/ai/openai/test_openai.py +++ b/posthog/test/ai/openai/test_openai.py @@ -465,6 +465,23 @@ def test_embeddings(mock_client, mock_embedding_response): assert isinstance(props["$ai_latency"], float) +def test_embeddings_use_context_distinct_id(mock_client, mock_embedding_response): + from posthog import identify_context, new_context + + with patch( + "openai.resources.embeddings.Embeddings.create", + return_value=mock_embedding_response, + ): + client = OpenAI(api_key="test-key", posthog_client=mock_client) + with new_context(): + identify_context("context-user") + client.embeddings.create(model="text-embedding-3-small", input="Hello") + + call_args = mock_client.capture_ai.call_args[1] + assert call_args["distinct_id"] == "context-user" + assert call_args["event"] == "$ai_embedding" + + @pytest.mark.parametrize("stream_options", [None, NOT_GIVEN, {"foo": "bar"}]) def test_streaming_stream_options_are_not_mutated( mock_client, streaming_tool_call_chunks, stream_options From 01feddcf46364e70c93040b5e2c18978ae3e8c26 Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 23 Nov 2026 17:56:21 -0400 Subject: [PATCH 2/2] test(ai): cover embedding distinct_id precedence and use is-not-None checks Address review: assert options are absent for context-resolved embedding events, add _resolve_distinct_id precedence/blank tests, and compare resolved ids with 'is not None' so a falsy id such as 0 cannot disagree between distinct_id and personless. Signed-off-by: Alex --- posthog/ai/gemini/_shared.py | 4 +++- posthog/ai/openai/_embeddings.py | 4 +++- posthog/ai/utils.py | 7 ++++--- posthog/test/ai/gemini/test_gemini.py | 1 + posthog/test/ai/openai/test_openai.py | 1 + posthog/test/ai/test_utils.py | 15 +++++++++++++++ 6 files changed, 27 insertions(+), 5 deletions(-) diff --git a/posthog/ai/gemini/_shared.py b/posthog/ai/gemini/_shared.py index c4df28bab..ff475c6aa 100644 --- a/posthog/ai/gemini/_shared.py +++ b/posthog/ai/gemini/_shared.py @@ -279,7 +279,9 @@ def _capture_embedding_outcome( _capture_ai_event( self._ph_client, "$ai_embedding", - distinct_id=resolved_distinct_id or trace_id, + distinct_id=( + resolved_distinct_id if resolved_distinct_id is not None else trace_id + ), properties=event_properties, groups=groups, personless=resolved_distinct_id is None, diff --git a/posthog/ai/openai/_embeddings.py b/posthog/ai/openai/_embeddings.py index 0ab0c991b..570f06ca3 100644 --- a/posthog/ai/openai/_embeddings.py +++ b/posthog/ai/openai/_embeddings.py @@ -60,7 +60,9 @@ def _capture_embedding_event( _capture_ai_event( posthog_client, "$ai_embedding", - distinct_id=resolved_distinct_id or trace_id, + distinct_id=( + resolved_distinct_id if resolved_distinct_id is not None else trace_id + ), properties=event_properties, groups=groups, personless=resolved_distinct_id is None, diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 73e452338..646c7b3ed 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -74,9 +74,10 @@ def _user_distinct_id(distinct_id: Any) -> Any: def _resolve_distinct_id(distinct_id: Any) -> Any: """The caller's distinct id, else the one from the active PostHog context, else None.""" - return _user_distinct_id(distinct_id) or _user_distinct_id( - contexts.get_context_distinct_id() - ) + resolved = _user_distinct_id(distinct_id) + if resolved is not None: + return resolved + return _user_distinct_id(contexts.get_context_distinct_id()) def _ai_event_options(value: Any) -> Dict[str, Any]: diff --git a/posthog/test/ai/gemini/test_gemini.py b/posthog/test/ai/gemini/test_gemini.py index 811c41f81..3129ba5ae 100644 --- a/posthog/test/ai/gemini/test_gemini.py +++ b/posthog/test/ai/gemini/test_gemini.py @@ -1388,6 +1388,7 @@ def test_embed_content_uses_context_distinct_id( call_args = mock_client.capture_ai.call_args[1] assert call_args["distinct_id"] == "context-user" assert call_args["event"] == "$ai_embedding" + assert "options" not in call_args def test_embed_content_basic( diff --git a/posthog/test/ai/openai/test_openai.py b/posthog/test/ai/openai/test_openai.py index 4b80615f0..8e519ac46 100644 --- a/posthog/test/ai/openai/test_openai.py +++ b/posthog/test/ai/openai/test_openai.py @@ -480,6 +480,7 @@ def test_embeddings_use_context_distinct_id(mock_client, mock_embedding_response call_args = mock_client.capture_ai.call_args[1] assert call_args["distinct_id"] == "context-user" assert call_args["event"] == "$ai_embedding" + assert "options" not in call_args @pytest.mark.parametrize("stream_options", [None, NOT_GIVEN, {"foo": "bar"}]) diff --git a/posthog/test/ai/test_utils.py b/posthog/test/ai/test_utils.py index 49add2881..46598a856 100644 --- a/posthog/test/ai/test_utils.py +++ b/posthog/test/ai/test_utils.py @@ -164,3 +164,18 @@ 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_resolve_distinct_id_precedence_and_blank_values(): + from posthog import identify_context, new_context + from posthog.ai.utils import _resolve_distinct_id + + with new_context(fresh=True): + assert _resolve_distinct_id(None) is None + identify_context(" ") + assert _resolve_distinct_id(None) is None + identify_context("context-user") + assert _resolve_distinct_id(None) == "context-user" + assert _resolve_distinct_id(" ") == "context-user" + assert _resolve_distinct_id("explicit-user") == "explicit-user" + assert _resolve_distinct_id(0) == 0