Skip to content
Merged
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/ai-posthog-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

AI integrations take capture options. Every wrapper method that takes `posthog_properties` also takes `posthog_options` (OpenAI, Anthropic, Gemini, sync and async, and the Claude Agent SDK `query()` and `PostHogClaudeSDKClient`), and the Gemini clients take it as a default for every call. LangChain's `CallbackHandler` and `PostHogMiddleware`, and `instrument()` and the tracing processors for OpenAI Agents and the Claude Agent SDK, take `options=`. LangChain also reads `posthog_options` from run metadata. These options win over context options and `super_options`. An event without a distinct ID still always sends `process_person_profile: False`, and a value that is not a dict is logged and ignored.
5 changes: 5 additions & 0 deletions .sampo/changesets/celery-context-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

The Celery integration propagates context options from the publisher to the worker, like tags. Options set with `set_context_option` before a task is published apply to every event captured while the task runs. `propagate_context=False` sends none of them.
5 changes: 5 additions & 0 deletions .sampo/changesets/lib-is-an-sdk-value.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: major
---

Events send `$lib` and `$lib_version` as they are at send time, whoever set them. If no `$lib` is set in the call's `properties`, a context tag or `super_properties`, the SDK sets both to `posthog-python` and the installed version. If `$lib` is `posthog-python` and `$lib_version` is missing, the SDK fills in the version. A `$lib` that names another library is sent with whatever `$lib_version` it has, so set both when you override them. Only a non-empty string counts as set. In 7.x the SDK overwrote a `$lib` or `$lib_version` set in a call or a context tag. `before_send` can still change or remove both, and `AsyncPosthog` follows the same rules.
5 changes: 5 additions & 0 deletions .sampo/changesets/mcp-event-options.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

MCP events take capture options. The `PostHogMCP` capture methods and `McpAnalytics.capture` take an `event_options` argument, and `MCPAnalyticsOptions(event_options=...)` sets options on every event `instrument()` captures automatically, from a function of `(request, extra)` like `event_properties`. An event without an identity still always sends `process_person_profile: False`. `PostHogMCP.capture()` keeps the core client's `options` argument.
2 changes: 1 addition & 1 deletion .sampo/changesets/mcp-keeps-sdk-identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
pypi/posthog: major
---

MCP instrumentation no longer relabels the client as `posthog-python-mcp`. `posthog.mcp.instrument()` and `PostHogMCP` used to change `$lib`, the `PostHog-Sdk-Info` header and the feature flag request `User-Agent` for every event the client sent, including the app's own events. All events now report `posthog-python`. Filter MCP traffic on the `$mcp_*` events and properties.
MCP instrumentation no longer relabels the whole client. In 7.x, `posthog.mcp.instrument()` and `PostHogMCP` changed `$lib` on every event the client sent, including the app's own, and the SDK name in its request headers, feature flag requests included. `instrument()` without a client relabeled the global client. Now only MCP analytics events report `posthog-python-mcp`, and everything else reports `posthog-python`. The label is set in each MCP event's own properties, so a `$lib` in `super_properties` no longer replaces it; `before_send` can.
148 changes: 116 additions & 32 deletions docs/migration-7.x-to-8.0.md

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions posthog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,10 +394,7 @@ def get_context_options() -> Dict[str, Any]:
super_options: Capture options for every captured event, such as
``{"cookieless_mode": True}``. They fill only options the event leaves
unset, before ``before_send`` runs. An event's own ``options`` and
context options override them, and ``before_send`` can change them. They also
win over an event's legacy property for the same key, such as
``$cookieless_mode``, so pass per-event overrides of that key as
``options``.
context options override them, and ``before_send`` can change them.
metrics: Config dict for the ``client.metrics`` API (``service_name``,
``service_version``, ``environment``, ``flush_interval``, ...). Applied
when ``setup()`` builds the global client, or on a later ``setup()``
Expand Down
19 changes: 19 additions & 0 deletions posthog/ai/anthropic/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def create(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
"""
Expand All @@ -71,6 +72,10 @@ def create(
posthog_properties: Optional dictionary of extra properties to include in the event
posthog_privacy_mode: Whether to redact sensitive information in tracking
posthog_groups: Optional group analytics properties
posthog_options: Optional capture options for the event, such as
``{"cookieless_mode": True}``. They win over context options
and ``super_options``. An event without a distinct ID always
sends ``process_person_profile: False``.
**kwargs: Arguments passed to Anthropic's messages.create
"""

Expand All @@ -84,6 +89,7 @@ def create(
posthog_properties,
posthog_privacy_mode,
posthog_groups,
posthog_options=posthog_options,
**kwargs,
)

Expand All @@ -97,6 +103,7 @@ def create(
posthog_groups,
self._client.base_url,
super().create,
posthog_options=posthog_options,
**kwargs,
)

Expand All @@ -107,6 +114,7 @@ def stream(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
"""
Expand All @@ -118,6 +126,10 @@ def stream(
posthog_properties: Additional properties to include with the usage event.
posthog_privacy_mode: Whether to redact captured input and output.
posthog_groups: Optional PostHog groups to associate with the event.
posthog_options: Capture options for the event, such as
``{"cookieless_mode": True}``. They win over context options
and ``super_options``. An event without a distinct ID always
sends ``process_person_profile: False``.
**kwargs: Arguments passed to Anthropic's ``messages.create`` API.

Returns:
Expand Down Expand Up @@ -147,6 +159,7 @@ def tracked_request():
posthog_groups,
kwargs,
start_time,
options=posthog_options,
)

setattr(manager, request_attribute, tracked_request)
Expand All @@ -159,6 +172,7 @@ def _create_streaming(
posthog_properties: Optional[Dict[str, Any]],
posthog_privacy_mode: bool,
posthog_groups: Optional[Dict[str, Any]],
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
start_time = time.time()
Expand All @@ -172,6 +186,7 @@ def _create_streaming(
posthog_groups,
kwargs,
start_time,
options=posthog_options,
)

def _track_streaming_response(
Expand All @@ -184,6 +199,7 @@ def _track_streaming_response(
posthog_groups: Optional[Dict[str, Any]],
kwargs: Dict[str, Any],
start_time: float,
options: Optional[Dict[str, Any]] = None,
):
accumulator = _AnthropicStreamAccumulator()

Expand Down Expand Up @@ -213,6 +229,7 @@ def generator():
accumulator.accumulated_content,
stop_reason=accumulator.stop_reason,
error=stream_error,
options=options,
)

return _StreamWrapper(generator(), stream=response)
Expand All @@ -231,6 +248,7 @@ def _capture_streaming_event(
accumulated_content: str,
stop_reason: Optional[str] = None,
error: Optional[BaseException] = None,
options: Optional[Dict[str, Any]] = None,
):
from posthog.ai.types import StreamingEventData
from posthog.ai.anthropic.anthropic_converter import (
Expand Down Expand Up @@ -259,6 +277,7 @@ def _capture_streaming_event(
groups=posthog_groups,
stop_reason=stop_reason,
error=error,
options=options,
)

# Use the common capture function
Expand Down
19 changes: 19 additions & 0 deletions posthog/ai/anthropic/anthropic_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ async def create(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
"""
Expand All @@ -71,6 +72,10 @@ async def create(
posthog_properties: Optional dictionary of extra properties to include in the event
posthog_privacy_mode: Whether to redact sensitive information in tracking
posthog_groups: Optional group analytics properties
posthog_options: Optional capture options for the event, such as
``{"cookieless_mode": True}``. They win over context options
and ``super_options``. An event without a distinct ID always
sends ``process_person_profile: False``.
**kwargs: Arguments passed to Anthropic's messages.create
"""

Expand All @@ -84,6 +89,7 @@ async def create(
posthog_properties,
posthog_privacy_mode,
posthog_groups,
posthog_options=posthog_options,
**kwargs,
)

Expand All @@ -97,6 +103,7 @@ async def create(
posthog_groups,
self._client.base_url,
super().create,
posthog_options=posthog_options,
**kwargs,
)

Expand All @@ -107,6 +114,7 @@ def stream(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
"""
Expand All @@ -118,6 +126,10 @@ def stream(
posthog_properties: Additional properties to include with the usage event.
posthog_privacy_mode: Whether to redact captured input and output.
posthog_groups: Optional PostHog groups to associate with the event.
posthog_options: Capture options for the event, such as
``{"cookieless_mode": True}``. They win over context options
and ``super_options``. An event without a distinct ID always
sends ``process_person_profile: False``.
**kwargs: Arguments passed to Anthropic's async ``messages.create`` API.

Returns:
Expand Down Expand Up @@ -147,6 +159,7 @@ async def tracked_request():
posthog_groups,
kwargs,
start_time,
options=posthog_options,
)

setattr(manager, request_attribute, tracked_request())
Expand All @@ -159,6 +172,7 @@ async def _create_streaming(
posthog_properties: Optional[Dict[str, Any]],
posthog_privacy_mode: bool,
posthog_groups: Optional[Dict[str, Any]],
posthog_options: Optional[Dict[str, Any]] = None,
**kwargs: Any,
):
start_time = time.time()
Expand All @@ -172,6 +186,7 @@ async def _create_streaming(
posthog_groups,
kwargs,
start_time,
options=posthog_options,
)

def _track_streaming_response(
Expand All @@ -184,6 +199,7 @@ def _track_streaming_response(
posthog_groups: Optional[Dict[str, Any]],
kwargs: Dict[str, Any],
start_time: float,
options: Optional[Dict[str, Any]] = None,
):
accumulator = _AnthropicStreamAccumulator()

Expand Down Expand Up @@ -213,6 +229,7 @@ async def generator():
accumulator.accumulated_content,
stop_reason=accumulator.stop_reason,
error=stream_error,
options=options,
)

return AsyncStreamWrapper(generator(), stream=response)
Expand All @@ -231,6 +248,7 @@ async def _capture_streaming_event(
accumulated_content: str,
stop_reason: Optional[str] = None,
error: Optional[BaseException] = None,
options: Optional[Dict[str, Any]] = None,
):
from posthog.ai.types import StreamingEventData
from posthog.ai.anthropic.anthropic_converter import (
Expand Down Expand Up @@ -259,6 +277,7 @@ async def _capture_streaming_event(
groups=posthog_groups,
stop_reason=stop_reason,
error=error,
options=options,
)

# Use the common capture function
Expand Down
13 changes: 13 additions & 0 deletions posthog/ai/claude_agent_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def instrument(
privacy_mode: bool = False,
groups: Optional[Dict[str, Any]] = None,
properties: Optional[Dict[str, Any]] = None,
options: Optional[Dict[str, Any]] = None,
) -> PostHogClaudeAgentProcessor:
"""
Create a PostHog-instrumented query wrapper for the Claude Agent SDK.
Expand All @@ -49,6 +50,10 @@ def instrument(
privacy_mode: If True, redacts sensitive information in tracking.
groups: Optional PostHog groups to associate with events.
properties: Optional additional properties to include with all events.
options: Optional capture options for all events, such as
``{"cookieless_mode": True}``. They win over context options and
``super_options``. An event without a distinct ID always sends
``process_person_profile: False``.

Returns:
PostHogClaudeAgentProcessor: A processor whose .query() method wraps claude_agent_sdk.query().
Expand All @@ -69,6 +74,7 @@ def instrument(
privacy_mode=privacy_mode,
groups=groups,
properties=properties,
options=options,
)


Expand All @@ -85,6 +91,7 @@ async def query(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
):
"""
Drop-in replacement for claude_agent_sdk.query() with PostHog instrumentation.
Expand All @@ -102,6 +109,11 @@ async def query(
posthog_properties: Extra properties to include with all events.
posthog_privacy_mode: If True, redacts sensitive content.
posthog_groups: Optional PostHog groups.
posthog_options: Capture options for all events, such as
``{"cookieless_mode": True}``. They win over context options and
``super_options``. An event without a distinct ID always sends
``process_person_profile: False``. Named so it does not clash with
``options``, the Claude Agent SDK options.

Example:
```python
Expand Down Expand Up @@ -147,5 +159,6 @@ async def query(
posthog_properties=posthog_properties,
posthog_privacy_mode=posthog_privacy_mode,
posthog_groups=posthog_groups,
posthog_options=posthog_options,
):
yield message
6 changes: 6 additions & 0 deletions posthog/ai/claude_agent_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def __init__(
posthog_properties: Optional[Dict[str, Any]] = None,
posthog_privacy_mode: bool = False,
posthog_groups: Optional[Dict[str, Any]] = None,
posthog_options: Optional[Dict[str, Any]] = None,
):
"""
Initialize a stateful Claude Agent SDK client with PostHog instrumentation.
Expand All @@ -78,6 +79,10 @@ def __init__(
posthog_properties: Additional properties included on emitted AI events.
posthog_privacy_mode: Whether to redact captured inputs, outputs, and tool data.
posthog_groups: Optional PostHog groups to associate with emitted events.
posthog_options: Capture options for emitted AI events, such as
``{"cookieless_mode": True}``. They win over context options and
``super_options``. An event without a distinct ID always sends
``process_person_profile: False``.
"""
from dataclasses import replace as dc_replace

Expand All @@ -94,6 +99,7 @@ def __init__(
privacy_mode=posthog_privacy_mode,
groups=posthog_groups,
properties=posthog_properties or {},
options=posthog_options,
)
self._trace_id = posthog_trace_id or str(uuid.uuid4())
self._distinct_id = posthog_distinct_id
Expand Down
Loading
Loading