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/embeddings-context-distinct-id.md
Original file line number Diff line number Diff line change
@@ -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
9 changes: 6 additions & 3 deletions posthog/ai/gemini/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -275,12 +275,15 @@ 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 if resolved_distinct_id is not None else trace_id
),
properties=event_properties,
groups=groups,
personless=_user_distinct_id(distinct_id) is None,
personless=resolved_distinct_id is None,
options=options,
)
9 changes: 6 additions & 3 deletions posthog/ai/openai/_embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -56,12 +56,15 @@ 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 if resolved_distinct_id is not None else trace_id
),
properties=event_properties,
groups=groups,
personless=_user_distinct_id(distinct_id) is None,
personless=resolved_distinct_id is None,
options=options,
)
8 changes: 8 additions & 0 deletions posthog/ai/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ 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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Now that #1286 (470a6413) has landed on main with the identical _user_distinct_id(...) or _user_distinct_id(contexts.get_context_distinct_id()) expression in capture_streaming_event (posthog/ai/utils.py:1321-1323 on main), consider reusing _resolve_distinct_id(event_data.get("distinct_id")) there if you rebase onto main, so both streaming and embedding paths share one helper. (No merge conflict exists either way.)

"""The caller's distinct id, else the one from the active PostHog context, else None."""
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]:
"""Return a copy of a caller's ``posthog_options``, or ``{}`` when it is not a dict."""
if value is None:
Expand Down
20 changes: 20 additions & 0 deletions posthog/test/ai/gemini/test_gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -1371,6 +1371,26 @@ 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"
assert "options" not in call_args


def test_embed_content_basic(
mock_client, mock_google_genai_client, mock_embed_content_response
):
Expand Down
18 changes: 18 additions & 0 deletions posthog/test/ai/openai/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,24 @@ 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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concern: Neither new test asserts that options is absent when the embedding event resolves distinct_id from identify_context(), leaving the personless=resolved_distinct_id is None half of the production change in posthog/ai/openai/_embeddings.py (line 66) and posthog/ai/gemini/_shared.py (line 285) unguarded, along with _resolve_distinct_id's precedence and blank-context branches.

Evidence and impact:

  • Inside with new_context(): identify_context("context-user"), this PR changes two user-visible behaviors: distinct_id switches from trace_id to "context-user", and personless switches from True (options={"process_person_profile": False}) to False (options omitted).
  • Both test_embeddings_use_context_distinct_id (posthog/test/ai/openai/test_openai.py:480-482) and test_embed_content_uses_context_distinct_id (posthog/test/ai/gemini/test_gemini.py:1388-1390) assert only call_args["distinct_id"] and call_args["event"]. Reverting personless=resolved_distinct_id is None back to personless=_user_distinct_id(distinct_id) is None in both production files would silently emit personless $ai_embedding events (options={"process_person_profile": False}) for identified users while all 404 OpenAI and Gemini tests still pass.
  • Sibling context tests in this repo (test_streaming_uses_outer_context_distinct_id from fix(ai): use the context distinct id for streamed generations #1286 and test_outer_context_distinct_id_is_used in posthog/test/ai/anthropic/test_anthropic.py) assert assert "options" not in call_args to guard this contract (capture-ai spec: only fallback trace IDs force options.process_person_profile: false).

Recommendation:
Consider adding assert "options" not in call_args to both test_embeddings_use_context_distinct_id (here) and test_embed_content_uses_context_distinct_id (posthog/test/ai/gemini/test_gemini.py:1390), plus a focused test covering explicit posthog_distinct_id overriding identify_context and a whitespace-only context falling back to a personless trace_id.

Test sketch (not executed as a committed test; equivalent scenarios passed on head f3c8d48b via local mock-server smoke testing):

# In both test_embeddings_use_context_distinct_id and test_embed_content_uses_context_distinct_id:
assert call_args["distinct_id"] == "context-user"
assert call_args["event"] == "$ai_embedding"
assert "options" not in call_args

# Plus in posthog/test/ai/test_utils.py (or alongside the embedding tests):
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 "options" not in call_args


@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
Expand Down
15 changes: 15 additions & 0 deletions posthog/test/ai/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading