diff --git a/.sampo/changesets/langchain-context-distinct-id.md b/.sampo/changesets/langchain-context-distinct-id.md new file mode 100644 index 000000000..b212a026a --- /dev/null +++ b/.sampo/changesets/langchain-context-distinct-id.md @@ -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 diff --git a/posthog/ai/langchain/callbacks.py b/posthog/ai/langchain/callbacks.py index 0972cf43a..ec65cc181 100644 --- a/posthog/ai/langchain/callbacks.py +++ b/posthog/ai/langchain/callbacks.py @@ -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, @@ -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. @@ -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) _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, ) @@ -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, @@ -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}, ) diff --git a/posthog/ai/utils.py b/posthog/ai/utils.py index 62bd937a6..d4382114b 100644 --- a/posthog/ai/utils.py +++ b/posthog/ai/utils.py @@ -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: diff --git a/posthog/test/ai/langchain/test_callbacks.py b/posthog/test/ai/langchain/test_callbacks.py index 10df3378a..f11d62bd0 100644 --- a/posthog/test/ai/langchain/test_callbacks.py +++ b/posthog/test/ai/langchain/test_callbacks.py @@ -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" + 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")])