AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-product-analytics

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-product-analytics at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 62

references/posthog-python.md · 24000

) - Whether to only evaluate locally.

  • send_feature_flag_events (bool) - Deprecated. Use get_feature_flag() instead if you need events.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • device_id? (str) - The device ID for this request.

Returns

  • Optional[object]

Examples

is_my_flag_enabled = posthog.feature_enabled('flag-key', 'distinct_id_of_your_user')

if is_my_flag_enabled:
    # Do something differently for this user
    # Optional: fetch the payload
    matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')

get_feature_flags_and_payloads()

Release Tag: public

Get feature flags and payloads for a user.

Parameters

  • distinct_id? (Number) - The distinct ID of the user.
  • groups? (Mapping[str, Union[str, int]]) - A dictionary of group information.
  • person_properties? (dict[str, Any]) - A dictionary of person properties.
  • group_properties? (dict[str, dict[str, Any]]) - A dictionary of group properties.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • flag_keys_to_evaluate? (list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
  • device_id? (str) - The device ID for this request.

Returns

  • FlagsAndPayloads

Examples

result = posthog.get_feature_flags_and_payloads('<distinct_id>')

get_feature_payloads()

Release Tag: public

Get feature flag payloads for a user, preserving valid serialized JSON.

Parameters

  • distinct_id? (Number) - The distinct ID of the user.
  • groups? (Mapping[str, Union[str, int]]) - A dictionary of group information.
  • person_properties? (dict[str, Any]) - A dictionary of person properties.
  • group_properties? (dict[str, dict[str, Any]]) - A dictionary of group properties.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • flag_keys_to_evaluate? (list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
  • device_id? (str) - The device ID for this request.

Returns

  • dict[str, Optional[str]]

Examples

payloads = posthog.get_feature_payloads('<distinct_id>')

get_feature_variants()

Release Tag: public

Get feature flag variants for a user.

Parameters

  • distinct_id? (Number) - The distinct ID of the user.
  • groups? (Mapping[str, Union[str, int]]) - A dictionary of group information.
  • person_properties? (dict[str, Any]) - A dictionary of person properties.
  • group_properties? (dict[str, dict[str, Any]]) - A dictionary of group properties.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • flag_keys_to_evaluate? (list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
  • device_id? (str) - The device ID for this request.

Returns

  • dict[str, Union[bool, str]]

get_flags_decision()

Release Tag: public

Get feature flags decision.

Parameters

  • distinct_id (Number) - The distinct ID of the user.
  • groups? (Mapping[str, Union[str, int]]) - A dictionary of group information.
  • person_properties? (dict[str, Any]) - A dictionary of person properties.
  • group_properties? (dict[str, dict[str, Any]]) - A dictionary of group properties.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • flag_keys_to_evaluate? (list[str]) - A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance.
  • device_id? (str) - The device ID for this request.

Returns

  • FlagsResponse

Examples

decision = posthog.get_flags_decision('user123')

get_remote_config_payload()

Release Tag: public

Get the payload for a remote config feature flag.

Parameters

  • key? (str) - The remote config feature flag key.

Returns

  • None

load_feature_flags()

Release Tag: public

Load feature flags for local evaluation.

Returns

  • None

Examples

posthog.load_feature_flags()

Other methods

flush()

Release Tag: public

Attempt immediate delivery of queued events and ended spans, keeping the client reusable. For a client shared across requests or serverless invocations (including the module-level client), call flush() before a short-lived invocation returns. Use shutdown() instead only for final process cleanup or when disposing of a client that will not be reused. Flush does not stop the background workers or feature flag poller, and does not end open spans. Returning does not guarantee server receipt: pending work can remain after a timeout or span export failure, and failed events may be dropped by the consumers. Calls made directly from SDK callbacks such as on_error are deferred rather than blocking the worker that invoked the callback.

Parameters

  • timeout_seconds? (float) - Seconds to wait for event queues to drain, shared across event lanes. Defaults to 10 seconds. Pass None to wait without a time limit; this does not guarantee successful delivery. Queued spans flush concurrently. The span exporter waits up to this many seconds for an in-flight flush, then uses a fresh drain budget once it acquires the lock. If the lock wait times out, the in-flight flush is left to finish. At least one span request is attempted after acquiring the lock, even with no budget left; retriable failures are retried after backoff while budget remains, with one last attempt at the deadline. Each span request is bounded by the client's timeout in seconds, and the last request is not cut short. This is therefore not a strict wall-clock limit for the whole call. With None, a retriable span failure is left for a later flush rather than retried within this call.

Returns

  • any

Examples

posthog.capture('event_name', distinct_id='user_id')
# Before a serverless invocation returns; keep the shared client open.
posthog.flush(timeout_seconds=10)

get_feature_flag_result()

Release Tag: public

Get a FeatureFlagResult object which contains the flag result and payload for a key by evaluating locally or remotely depending on whether local evaluation is enabled and the flag can be locally evaluated. This also captures the $feature_flag_called event unless send_feature_flag_events is False.

Parameters

  • key? (str) - The feature flag key.
  • distinct_id? (Number) - The distinct ID of the user.
  • groups? (Mapping[str, Union[str, int]]) - A dictionary of group information.
  • person_properties? (dict[str, Any]) - A dictionary of person properties.
  • group_properties? (dict[str, dict[str, Any]]) - A dictionary of group properties.
  • only_evaluate_locally (bool) - Whether to only evaluate locally.
  • send_feature_flag_events (bool) - Whether to send feature flag events.
  • disable_geoip? (bool) - Whether to disable GeoIP for this request.
  • device_id? (str) - The device ID for this request.

Returns

  • Optional[FeatureFlagResult]

Examples

flag_result = posthog.get_feature_flag_result('flag-key', 'distinct_id_of_your_user')
if flag_result and flag_result.get_value() == 'variant-key':
    # Do something differently for this user
    # Optional: fetch the payload
    matched_flag_payload = flag_result.payload

join()

Release Tag: public

Attempt to process queued events and end the consumer threads. Do not use directly, call shutdown() instead. Failed or undrainable events may be dropped and reported through logging or on_error; returning does not guarantee server receipt. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry.

Returns

  • any

Examples

posthog.join()

shutdown()

Release Tag: public

Attempt final delivery and permanently shut down the client. Call this for final process cleanup or when disposing of a client that will not be reused. It closes capture lanes, stops background workers and the feature flag poller, and tears down integrations. Do not call it at the end of each request or serverless invocation when the client is shared; call flush() before returning instead. A shut-down client cannot be reused; create a new client if needed. Normally this method blocks until queued events have been attempted and cleanup finishes. Failed or undrainable events may be dropped and reported through logging or on_error; returning does not guarantee server receipt. Event draining has no timeout. Queued spans get one final flush with up to 30 seconds waiting for an in-flight flush, then a fresh 30-second drain budget; the last HTTP request is not cut short. Any spans it cannot send are discarded with a warning, as are spans still open. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. When called directly from an SDK callback such as on_error, shutdown is deferred to avoid blocking the worker that invoked the callback. If the callback must coordinate a blocking shutdown, have it signal an application-owned thread and return before that thread calls shutdown. Do not wait inside the callback for another thread or task that calls a lifecycle method.

Returns

  • any

Examples

posthog.shutdown()

Tracing methods

get_active_span()

Release Tag: public

The span that is active in the current context, or None. Alpha. Only entering a span (with posthog.start_span(...) as span:) makes it active; a span started manually is not. Use it to propagate the trace to the next service: span.traceparent() is the header value.

Returns

  • Optional[Span]

Examples

span = posthog.get_active_span()
if span is not None:
    headers["traceparent"] = span.traceparent()

start_span()

Release Tag: public

Start a span for distributed tracing. Alpha. Returns a span handle. Use it as a context manager to make it the active span for the block and end it on exit (recording a raised exception on the way out); or call end() yourself for a span that cannot wrap a block. Spans started inside the block nest under it automatically. Always returns a usable handle, even when tracing is off, so calling code never branches.

Parameters

  • name? (str) - A low-cardinality operation name, e.g. GET /users/:id. Variable values belong in attributes, not the name.
  • kind? (str) - internal (default), server, client, producer or consumer.
  • attributes? (Mapping[str, Any]) - Initial attributes.
  • parent (Span) - A span handle, or an inbound W3C traceparent header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork.
  • tracestate? (str) - The inbound tracestate header accompanying a traceparent string parent; preserved and propagated.
  • start_time (datetime) - A datetime or epoch seconds, to backdate the span.

Returns

  • Span

Examples

posthog = Posthog("<ph_project_api_key>", traces={"service_name": "checkout-api"})

with posthog.start_span("POST /checkout", parent=request.headers.get("traceparent")) as span:
    span.set_attribute("plan", user.plan)
    with posthog.start_span("db.query", kind="client"):
        ...
    outgoing_headers = {"traceparent": span.traceparent()}

Contexts methods

get_tags()

Release Tag: public

Get all tags from the current context. Returns: Dict of all tags in the current context.

Returns

  • dict[str, Any]

identify_context()

Release Tag: public

Identify the current context with a distinct ID.

Parameters

  • distinct_id? (str) - The distinct ID to associate with the current context and its children.

Returns

  • any

new_context()

Release Tag: public

Create a new context for managing shared state. Learn more about contexts.

Parameters

  • fresh (bool) - Whether to create a fresh context that doesn't inherit from parent.
  • capture_exceptions? (bool) - Whether to automatically capture exceptions in this context. If omitted, defaults to this client's exception autocapture setting.

Returns

  • None

Examples

with client.new_context():
    client.identify_context('<distinct_id>')
    client.capture('event_name')

scoped()

Release Tag: public

Decorator that creates a new context for the wrapped function using this client.

Parameters

  • fresh (bool) - Whether to create a fresh context that doesn't inherit from parent.
  • capture_exceptions? (bool) - Whether to automatically capture exceptions in this context. If omitted, defaults to this client's exception autocapture setting.

Returns

  • None

set_context_device_id()

Release Tag: public

Set the device ID for the current context.

Parameters

  • device_id? (str) - The device ID to associate with the current context and its children.

Returns

  • any

set_context_session()

Release Tag: public

Set the session ID for the current context.

Parameters

  • session_id? (str) - The session ID to associate with the current context and its children.

Returns

  • any

tag()

Release Tag: public

Add a tag to the current context.

Parameters

  • name? (str) - The tag key.
  • value? (Any) - The tag value.

Returns

  • any

PostHog Module Functions

Global functions available in the PostHog module

Identification methods

alias()

Release Tag: public

Associate user behaviour before and after they e.g. register, login, or perform some other identifying action.

Notes:

To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?". Particularly useful for associating user behaviour before and after they e.g. register, login, or perform some other identifying action.

Parameters

  • previous_id? (Number) - The unique ID of the user before
  • distinct_id? (str) - The current unique id
  • timestamp (datetime) - Optional timestamp for the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
  • uuid? (str) - Optional UUID for the event
  • disable_geoip? (bool) - Whether to disable GeoIP lookup

Returns

  • Optional[str]

Examples

# Alias user
from posthog import alias
alias(previous_id='distinct_id', distinct_id='alias_id')

group_identify()

Release Tag: public

Set properties on a group.

Parameters

  • group_type? (str) - Type of your group. Required - the call is dropped with a warning if it is missing or empty.
  • group_key? (str) - Unique identifier of the group. Required - the call is dropped with a warning if it is missing or empty.
  • properties? (dict[str, Any]) - Properties to set on the group
  • timestamp (datetime) - Optional timestamp for the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.
  • uuid? (str) - Optional UUID for the event
  • disable_geoip? (bool) - Whether to disable GeoIP lookup
  • distinct_id (Number) - Optional distinct ID of the user performing the action

Returns

  • Optional[str]

Examples

# Group identify
from posthog import group_identify
group_identify('company', 'company_id_in_your_db', {
    'name': 'Awesome Inc.',
    'employees': 11
})

identify_context()

Release Tag: public

Identify the current context with a distinct ID.

Parameters

  • distinct_id? (str) - The distinct ID to associate with the current context and its children

Returns

  • None

Examples

from posthog import identify_context
identify_context("user_123")

set()

Release Tag: public

Set properties on a user record.

Notes:

This will overwrite previous people property values. Generally operates similar to capture, with distinct_id being an optional argument, defaulting to the current context's distinct ID. If there is no context-level distinct ID, and no override distinct_id is passed, this function will do nothing. Context tags are folded into $set properties, so tagging the current context and then calling set will cause those tags to be set on the user (unlike capture, which causes them to just be set on the event).

Parameters

  • kwargs? (Unpack[OptionalSetArgs])

Returns

  • Optional[str]

Examples

# Set person properties
from posthog import set
set(distinct_id='distinct_id', properties={'name': 'Max Hedgehog'})

set_once()

Release Tag: public

Set properties on a user record, only if they do not yet exist.

Notes:

This will not overwrite previous people property values, unlike set. Otherwise, operates in an identical manner to set.

Parameters

  • kwargs? (Unpack[OptionalSetArgs])

Returns

  • Optional[str]

Examples

# Set property once
from posthog import set_once
set_once(distinct_id='distinct_id', properties={'initial_url': '/blog'})

Events methods

capture()

Release Tag: public

Capture anything a user does within your system.

Notes:

Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up. A capture call requires an event name to specify the event. We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on. Capture takes a number of optional arguments, which are defined by the OptionalCaptureArgs type.

Parameters

  • event? (str) - The event name to specify the event **kwargs: Optional arguments including:
  • kwargs? (Unpack[OptionalCaptureArgs])

Returns

  • Optional[str]

Examples

Context and capture usage

# Context and capture usage
from posthog import new_context, identify_context, tag_context, capture
# Enter a new context (e.g. a request/response cycle, an instance of a background job, etc)
with new_context():
    # Associate this context with some user, by distinct_id
    identify_context('some user')

    # Capture an event, associated with the context-level distinct ID ('some user')
    capture('movie started')

    # Capture an event associated with some other user (overriding the context-level distinct ID)
    capture('movie joined', distinct_id='some-other-user')

    # Capture an event with some properties
    capture('movie played', properties={'movie_id': '123', 'category': 'romcom'})

    # Capture an event with some properties
    capture('purchase', properties={'product_id': '123', 'category': 'romcom'})
    # Capture an event with some associated group
    capture('purchase', groups={'company': 'id:5'})

    # Adding a tag to the current context will cause it to appear on all subsequent events
    tag_context('some-tag', 'some-value')

    capture('another-event') # Will be captured with `'some-tag': 'some-value'` in the properties dict

Set event properties

# Set event properties
from posthog import capture
capture(
    "user_signed_up",
    distinct_id="distinct_id_of_the_user",
    properties={
        "login_type": "email",
        "is_free_trial": "true"
    }
)

capture_ai()

Release Tag: public

Capture an AI event on the dedicated AI capture endpoint. Beta: the signature is stable; operational limits (per-event size cap, batching, endpoint) may change without notice. Takes the same arguments and returns the same value as capture(): the event UUID, or None when the event was not admitted (disabled client, or dropped by before_send). The event is delivered on an isolated queue with its own consumer pool and a higher per-event size cap, posting to the dedicated AI ingestion endpoint. The payload is sent as given — no redaction or truncation is applied here.

Parameters

  • event? (str) - The event name, normally one of the $ai_* event names. **kwargs: Same optional arguments as capture().
  • kwargs? (Unpack[OptionalCaptureArgs])

Returns

  • Optional[str]

Examples

from posthog import capture_ai

uuid = capture_ai(
    "$ai_generation",
    distinct_id="user_123",
    properties={"$ai_model": "gpt-5"},
)

capture_exception()

Release Tag: public

Capture exceptions that happen in your code.

Notes:

Capture exception is idempotent - if it is called twice with the same exception instance, only a occurrence will be tracked in posthog. This is because, generally, contexts will cause exceptions to be captured automatically. However, to ensure you track an exception, if you catch and do not re-raise it, capturing it manually is recommended, unless you are certain it will have crossed a context boundary (e.g. by existing a with posthog.new_context(): block already). If the passed exception was raised and caught, the captured stack trace will consist of every frame between where the exception was raised and the point at which it is captured (the "traceback"). If the passed exception was never raised, e.g. if you call posthog.capture_exception(ValueError("Some Error")), the stack trace captured will be the full stack trace at the moment the exception was captured. Note that heavy use of contexts will lead to truncated stack traces, as the exception will be captured by the context entered most recently, which may not be the point you catch the exception for the final time in your code. It's recommended to use contexts sparingly, for this reason. capture_exception takes the same set of optional arguments as capture.

Parameters

  • exception (BaseException) - The exception to capture. If not provided, the current exception is captured via sys.exc_info() **kwargs: Optional capture arguments including distinct_id, properties, timestamp, uuid, groups, flags, send_feature_flags, and disable_geoip. Overriding reserved exception properties through properties is deprecated and will stop working in the next major version.
  • kwargs? (Unpack[OptionalCaptureArgs])

Returns

  • Optional[str]

Examples

# Capture exception
from posthog import capture_exception
try:
    risky_operation()
except Exception as e:
    capture_exception(e)

Feature flags methods

evaluate_flags()

Release Tag: public

Evaluate all feature flags for a user in a single call and return a :class:FeatureFlagEvaluations snapshot. Branch on .is_enabled() / .get_flag() and pass the same snapshot to capture() via the flags option so events carry the exact flag va