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

fix(ai): the LangChain callback handler now uses the context distinct ID instead of falling back to a personless run ID
26 changes: 19 additions & 7 deletions posthog/ai/langchain/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
_capture_ai_event,
_extract_cache_creation_ttl_breakdown,
_resolve_ai_client,
_user_distinct_id,
_resolve_distinct_id,
finalize_ai_content,
_format_ai_error,
get_model_params,
Expand Down Expand Up @@ -152,6 +152,9 @@ def __init__(
Args:
client: PostHog client instance.
distinct_id: Optional distinct ID of the user to associate the trace with.
When omitted or blank, falls back to the active PostHog context
distinct ID (set via ``identify_context``), or sends personless
events if neither is set.
trace_id: Optional trace ID to use for the event.
properties: Optional additional metadata to use for the trace.
privacy_mode: Whether to redact the input and output of the trace.
Expand Down Expand Up @@ -594,13 +597,16 @@ def _capture_trace_or_span(
finalize_ai_content(outputs, self._ph_client),
)

resolved_distinct_id = _resolve_distinct_id(self._distinct_id)

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: Since CallbackHandler (and PostHogMiddleware, whose docstring defers to CallbackHandler) now resolves distinct_id from the active PostHog context before falling back to personless mode, consider noting that fallback in CallbackHandler.__init__'s docstring (posthog/ai/langchain/callbacks.py:154 and 162-163, outside this diff). For example:

distinct_id: Optional distinct ID of the user to associate the trace with. When omitted or blank, falls back to the active PostHog context distinct ID (set via identify_context), or sends personless events if neither is set.

This keeps IDE tooltips and generated SDK reference docs clear about when process_person_profile: False applies (per SDK guidelines: Treat docs and examples as part of the SDK).

_capture_ai_event(
self._ph_client,
event_name,
distinct_id=_user_distinct_id(self._distinct_id) or run_id,
distinct_id=resolved_distinct_id
if resolved_distinct_id is not None
else run_id,
properties=event_properties,
groups=self._groups,
personless=_user_distinct_id(self._distinct_id) is None,
personless=resolved_distinct_id is None,
options=self._options,
)

Expand All @@ -617,12 +623,15 @@ def _capture_exception_and_update_properties(
return event_properties

exception_options = dict(options)
if _user_distinct_id(self._distinct_id) is None:
resolved_distinct_id = _resolve_distinct_id(self._distinct_id)
if resolved_distinct_id is None:
# Matches the AI event: without a user, person processing stays off.
exception_options["process_person_profile"] = False
exception_id = self._ph_client.capture_exception(
exception,
distinct_id=self._distinct_id,
distinct_id=resolved_distinct_id
if resolved_distinct_id is not None
else self._distinct_id,
groups=self._groups,
properties=event_properties,
options=exception_options or None,
Expand Down Expand Up @@ -774,13 +783,16 @@ def _capture_generation(
if stop_reason is not None:
event_properties["$ai_stop_reason"] = stop_reason

resolved_distinct_id = _resolve_distinct_id(self._distinct_id)
_capture_ai_event(
self._ph_client,
"$ai_generation",
distinct_id=_user_distinct_id(self._distinct_id) or trace_id,
distinct_id=resolved_distinct_id
if resolved_distinct_id is not None
else trace_id,
properties=event_properties,
groups=self._groups,
personless=_user_distinct_id(self._distinct_id) is None,
personless=resolved_distinct_id is None,
# The handler's options win over the run's, like its properties.
options={**_ai_event_options(run.posthog_options), **self._options},
)
Expand Down
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:
"""The caller's distinct id, else the one from the active PostHog context, else None."""
explicit = _user_distinct_id(distinct_id)
if explicit is not None:
return explicit
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
78 changes: 78 additions & 0 deletions posthog/test/ai/langchain/test_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,84 @@ def test_trace_id_and_inputs_for_multiple_chains(mock_client):
assert trace_props["$ai_span_name"] == "RunnableSequence"


def test_context_distinct_id_is_used(mock_client):
from posthog import identify_context, new_context

prompt = ChatPromptTemplate.from_messages([("user", "Foo")])
chain = prompt | FakeMessagesListChatModel(responses=[AIMessage(content="Bar")])

with new_context():
identify_context("context-user")
chain.invoke({}, config={"callbacks": [CallbackHandler(mock_client)]})

assert mock_client.capture_ai.call_count == 3
for call in mock_client.capture_ai.call_args_list:
assert call[1]["distinct_id"] == "context-user"
assert "options" not in call[1]

# An explicit handler distinct_id still wins over the context.
mock_client.capture_ai.reset_mock()
with new_context():
identify_context("context-user")
handler = CallbackHandler(mock_client, distinct_id="explicit")
chain.invoke({}, config={"callbacks": [handler]})
assert mock_client.capture_ai.call_count == 3
for call in mock_client.capture_ai.call_args_list:
assert call[1]["distinct_id"] == "explicit"

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: The modified _capture_exception_and_update_properties path (posthog/ai/langchain/callbacks.py:621-631) has no test coverage for active PostHog context resolution, and the explicit-override block here omits call_count and options assertions.

Evidence & impact: Before this PR, a failed LangChain run inside identify_context(...) with enable_exception_autocapture=True emitted $exception with the context user's distinct_id and options={"process_person_profile": False}. This PR fixes both the distinct_id forwarding and exception_options, but test_context_distinct_id_is_used is the only test in posthog/test/ai/langchain/ using identify_context and only covers a successful chain run. In addition, lines 558–559 loop over mock_client.capture_ai.call_args_list without asserting call_count == 3 (so zero calls would pass vacuously) or "options" not in call[1].

Recommendation: Consider:

  1. Adding assert mock_client.capture_ai.call_count == 3 and assert "options" not in call[1] to the explicit-override block.
  2. Adding a test exercising _capture_exception_and_update_properties inside identify_context(...) (and optionally blank explicit distinct_id=" " falling back to context / reusing one CallbackHandler across contexts):
def test_context_distinct_id_exception_autocapture(mock_client):
    from langchain_core.runnables import RunnableLambda
    from posthog import identify_context, new_context

    mock_client.enable_exception_autocapture = True
    mock_client.capture_exception.return_value = "exception-uuid-ctx"

    def failing_span(_):
        raise ValueError("boom")

    with new_context():
        identify_context("context-user")
        with pytest.raises(ValueError):
            RunnableLambda(failing_span).invoke(
                {}, config={"callbacks": [CallbackHandler(mock_client)]}
            )

    assert mock_client.capture_exception.call_count == 1
    exc_kwargs = mock_client.capture_exception.call_args[1]
    assert exc_kwargs["distinct_id"] == "context-user"
    assert exc_kwargs["options"] is None
    assert mock_client.capture_ai.call_count == 1
    assert mock_client.capture_ai.call_args[1]["distinct_id"] == "context-user"
    assert "options" not in mock_client.capture_ai.call_args[1]

(Verified against base 84fc9e06 vs. head c4d3d8ca: fails on base and passes on head.)

assert "options" not in call[1]


def test_context_distinct_id_exception_autocapture(mock_client):
from langchain_core.runnables import RunnableLambda
from posthog import identify_context, new_context

mock_client.enable_exception_autocapture = True
mock_client.capture_exception.return_value = "exception-uuid-ctx"

def failing_span(_):
raise ValueError("boom")

with new_context():
identify_context("context-user")
with pytest.raises(ValueError):
RunnableLambda(failing_span).invoke(
{}, config={"callbacks": [CallbackHandler(mock_client)]}
)

assert mock_client.capture_exception.call_count == 1
exc_kwargs = mock_client.capture_exception.call_args[1]
assert exc_kwargs["distinct_id"] == "context-user"
assert exc_kwargs["options"] is None
assert mock_client.capture_ai.call_count == 1
assert mock_client.capture_ai.call_args[1]["distinct_id"] == "context-user"
assert "options" not in mock_client.capture_ai.call_args[1]


def test_zero_distinct_id_preserved_over_context(mock_client):
from langchain_core.runnables import RunnableLambda
from posthog import identify_context, new_context

mock_client.enable_exception_autocapture = True
mock_client.capture_exception.return_value = "exc-id"

def fail(_):
raise ValueError("boom")

with new_context():
identify_context("context-user")
with pytest.raises(ValueError):
RunnableLambda(fail).invoke(
{}, config={"callbacks": [CallbackHandler(mock_client, distinct_id=0)]}
)

assert mock_client.capture_ai.call_count == 1
assert mock_client.capture_ai.call_args[1]["distinct_id"] == 0
assert "options" not in mock_client.capture_ai.call_args[1]
assert mock_client.capture_exception.call_count == 1
assert mock_client.capture_exception.call_args[1]["distinct_id"] == 0
assert mock_client.capture_exception.call_args[1]["options"] is None


def test_personless_mode(mock_client):
prompt = ChatPromptTemplate.from_messages([("user", "Foo")])
chain = prompt | FakeMessagesListChatModel(responses=[AIMessage(content="Bar")])
Expand Down
Loading