Skip to content

Commit 8f37893

Browse files
committed
instrument with contexts
1 parent 2dba2a4 commit 8f37893

File tree

2 files changed

+230
-182
lines changed

2 files changed

+230
-182
lines changed

posthog/ai/langchain/callbacks.py

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,14 @@ def _capture_trace_or_span(
506506
if isinstance(outputs, BaseException):
507507
event_properties["$ai_error"] = _stringify_exception(outputs)
508508
event_properties["$ai_is_error"] = True
509+
event_properties = _capture_exception_and_update_properties(
510+
self._ph_client,
511+
outputs,
512+
self._distinct_id,
513+
self._groups,
514+
event_properties,
515+
)
516+
509517
elif outputs is not None:
510518
event_properties["$ai_output_state"] = with_privacy_mode(
511519
self._ph_client, self._privacy_mode, outputs
@@ -587,14 +595,13 @@ def _capture_generation(
587595
event_properties["$ai_error"] = _stringify_exception(output)
588596
event_properties["$ai_is_error"] = True
589597

590-
if self._ph_client.enable_exception_autocapture:
591-
exception_id = self._ph_client.capture_exception(
592-
output,
593-
distinct_id=self._distinct_id,
594-
groups=self._groups,
595-
properties=event_properties,
596-
)
597-
event_properties["$exception_event_id"] = exception_id
598+
event_properties = _capture_exception_and_update_properties(
599+
self._ph_client,
600+
output,
601+
self._distinct_id,
602+
self._groups,
603+
event_properties,
604+
)
598605
else:
599606
# Add usage
600607
usage = _parse_usage(output, run.provider, run.model)
@@ -870,6 +877,26 @@ def _parse_usage(
870877
return llm_usage
871878

872879

880+
def _capture_exception_and_update_properties(
881+
client: Client,
882+
exception: BaseException,
883+
distinct_id: Union[str, int, UUID],
884+
groups: Optional[Dict[str, Any]],
885+
event_properties: Dict[str, Any],
886+
):
887+
if client.enable_exception_autocapture:
888+
exception_id = client.capture_exception(
889+
exception,
890+
distinct_id=distinct_id,
891+
groups=groups,
892+
properties=event_properties,
893+
)
894+
895+
event_properties["$exception_event_id"] = exception_id
896+
897+
return event_properties
898+
899+
873900
def _get_http_status(error: BaseException) -> int:
874901
# OpenAI: https://github.com/openai/openai-python/blob/main/src/openai/_exceptions.py
875902
# Anthropic: https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/_exceptions.py

0 commit comments

Comments
 (0)