Generated banner for Instrument Integration
Generated logo for Instrument Integration

Instrument Integration

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog SDK integration to your application. Use when setting up PostHog for the first time or reviewing PRs that need PostHog initialization. Covers SDK installation, provider setup, and basic configuration for any framework.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, multi-step procedure for integrating the PostHog SDK into a wide range of web, mobile, and backend frameworks. It handles the detection of the project environment, installation of the appropriate SDK, initialization, user identification, and secure configuration of environment variables. The skill emphasizes following framework-specific patterns and maintaining an analytics contract, ensuring that PostHog is implemented consistently without disrupting existing application logic.

What it does

  • Detects the project's framework, language, and package manager.
  • Installs the correct PostHog SDK for the identified platform.
  • Configures PostHog initialization and provider setup based on framework-specific references.
  • Implements user identification logic for login and signup events.
  • Manages environment variables for project tokens and host URLs securely.
  • Verifies the integration and performs minimal cleanup.

When to use it

  • When setting up PostHog in a project for the first time.
  • When reviewing pull requests that require PostHog initialization.
  • When adding analytics to a new application across supported frameworks.
  • When migrating or updating PostHog configurations in an existing codebase.

Advantages

  • Ensures consistent implementation across diverse technology stacks.
  • Prevents hardcoding of sensitive project tokens and host URLs.
  • Follows established framework-specific best practices and patterns.
  • Minimizes the risk of breaking application boot or build processes.
  • Automates the repetitive aspects of SDK setup and environment configuration.

Usage examples

“Set up PostHog in my Next.js project.”
The agent will detect the Next.js environment, install the PostHog SDK, configure the necessary provider, and set up environment variables in .env.local.
“Integrate PostHog into this Android app.”
The agent will identify the Android/Kotlin structure, initialize PostHog in the Application class, and guide the setup of local.properties for configuration.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/posthog/instrument-integration/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip instrument-integration.zip -d .agents/skills

Documentation by PostHog

Add PostHog SDK integration

Use this skill to add the PostHog SDK to an application. Use it when setting up PostHog for the first time, or reviewing PRs that need PostHog initialization. Covers SDK installation, provider setup, and basic configuration. Supports any framework or language.

Supported frameworks and languages: Next.js, React, React Router, Vue, Nuxt, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, PHP, Ruby on Rails, Go, Elixir, Android, iOS, Swift, Flutter, React Native, Expo, Node.js, and vanilla JavaScript.

Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the platform.

Look for dependency files (package.json, pubspec.yaml, Podfile, Package.swift, requirements.txt, Gemfile, composer.json, go.mod, mix.exs, etc.) to determine the framework and language.

Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) to determine the package manager.

  • Check for existing PostHog setup. If PostHog is already installed and initialized, do not modify its code. Inform the user and skip to verification.

STEP 2: Research integration. 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and configuration patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.

STEP 3: Install the PostHog SDK.

  • Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.

STEP 4: Initialize PostHog.

  • Follow the framework reference for where and how to initialize. This varies significantly by framework (e.g., instrumentation-client.ts for Next.js 15.3+, AppConfig.ready() for Django, create_app() for Flask).

  • Set up the PostHog provider/wrapper component if the framework requires one.

STEP 5: Identify users.

  • Add PostHog identify() calls on the client side during login and signup events.

  • If both frontend and backend exist, pass the client-side session and distinct ID using X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to the server-side code.

STEP 6: Set up environment variables.

  • Check if the project already has PostHog environment variables configured (e.g. in .env, .env.local, or framework-specific env files). If valid values already exist, skip this step.

  • If the PostHog project token is missing, use the PostHog MCP server's projects-get tool to retrieve the project's api_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.

  • For the PostHog host URL: check the projects-get MCP response for a region field — US maps to https://us.i.posthog.com, EU maps to https://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.

  • Write these values to the appropriate env file (e.g. .env.local for Next.js, .env for others) using the framework's naming convention.

  • Reference these environment variables in code instead of hardcoding them.

STEP 7: Verify and clean up.

  • Check the project for errors. Look for type checking or build scripts in package.json.

  • Ensure any components created were actually used.

  • Run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Never run formatting or linting across the entire project's codebase.

Reference files

  • references/EXAMPLE-next-app-router.md - next-app-router example project code

  • references/EXAMPLE-next-pages-router.md - next-pages-router example project code

  • references/EXAMPLE-react-react-router-6.md - react-react-router-6 example project code

  • references/EXAMPLE-react-react-router-7-framework.md - react-react-router-7-framework example project code

  • references/EXAMPLE-react-react-router-7-data.md - react-react-router-7-data example project code

  • references/EXAMPLE-react-react-router-7-declarative.md - react-react-router-7-declarative example project code

  • references/EXAMPLE-react-vite.md - react-vite example project code

  • references/EXAMPLE-nuxt-3-6.md - nuxt-3-6 example project code

  • references/EXAMPLE-nuxt-4.md - nuxt-4 example project code

  • references/EXAMPLE-vue-3.md - vue-3 example project code

  • references/EXAMPLE-react-tanstack-router-file-based.md - react-tanstack-router-file-based example project code

  • references/EXAMPLE-react-tanstack-router-code-based.md - react-tanstack-router-code-based example project code

  • references/EXAMPLE-tanstack-start.md - tanstack-start example project code

  • references/EXAMPLE-sveltekit.md - sveltekit example project code

  • references/EXAMPLE-astro-static.md - astro-static example project code

  • references/EXAMPLE-astro-view-transitions.md - astro-view-transitions example project code

  • references/EXAMPLE-astro-ssr.md - astro-ssr example project code

  • references/EXAMPLE-astro-hybrid.md - astro-hybrid example project code

  • references/EXAMPLE-angular.md - angular example project code

  • references/EXAMPLE-javascript-node.md - javascript-node example project code

  • references/EXAMPLE-javascript-web.md - javascript-web example project code

  • references/EXAMPLE-django.md - django example project code

  • references/EXAMPLE-flask.md - flask example project code

  • references/EXAMPLE-fastapi.md - fastapi example project code

  • references/EXAMPLE-python.md - python example project code

  • references/EXAMPLE-laravel.md - laravel example project code

  • references/EXAMPLE-php.md - php example project code

  • references/EXAMPLE-ruby-on-rails.md - ruby-on-rails example project code

  • references/EXAMPLE-ruby.md - ruby example project code

  • references/EXAMPLE-android.md - android example project code

  • references/EXAMPLE-swift.md - swift example project code

  • references/EXAMPLE-react-native.md - react-native example project code

  • references/EXAMPLE-expo.md - expo example project code

  • references/next-js.md - Next.js

  • references/react.md - React

  • references/react-router-v6.md - React router v6

  • references/react-router-v7-framework-mode.md - React router v7 framework mode (remix v3)

  • references/react-router-v7-data-mode.md - React router v7 data mode

  • references/react-router-v7-declarative-mode.md - React router v7 declarative mode

  • references/nuxt-js-3-6.md - Nuxt.js (v3.0 to v3.6)

  • references/nuxt-js.md - Nuxt.js

  • references/vue-js.md - Vue.js

  • references/tanstack-start.md - Tanstack start

  • references/svelte.md - Svelte

  • references/astro.md - Astro

  • references/angular.md - Angular

  • references/js.md - JavaScript web

  • references/posthog-js.md - PostHog JavaScript web SDK

  • references/node.md - Node.js

  • references/posthog-node.md - PostHog Node.js SDK

  • references/django.md - Django

  • references/flask.md - Flask

  • references/python.md - Python

  • references/posthog-python.md - PostHog python SDK

  • references/dotnet.md - .net

  • references/elixir.md - Elixir

  • references/go.md - Go

  • references/laravel.md - Laravel

  • references/php.md - Php

  • references/ruby-on-rails.md - Ruby on rails

  • references/ruby.md - Ruby

  • references/android.md - Android

  • references/ios.md - Ios

  • references/usage.md - Ios SDK usage

  • references/configuration.md - Ios SDK configuration

  • references/flutter.md - Flutter

  • references/react-native.md - React native

  • references/identify-users.md - Identify users

  • references/COMMANDMENTS.md - Framework-specific rules the integration must follow

Each framework reference contains SDK-specific installation, initialization, and usage patterns. Find the one matching the user's stack.

Key principles

  • Environment variables: Always use environment variables for PostHog keys. Never hardcode them.

  • Minimal changes: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.

  • Match the example: Your implementation should follow the example project's patterns as closely as possible.

  • Analytics contract: Treat event names, property names, and feature flag keys as part of an analytics contract. Reuse existing names and patterns found in the project. When introducing new ones, make them clear, descriptive, and consistent with existing conventions.

Files

references/posthog-python.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

PostHog Python SDK

SDK Version: 7.86.0

Integrate PostHog into any python application.

Categories

  • Initialization

  • Identification

  • Capture

  • Error Tracking

  • Feature flags

  • Tracing

  • Contexts

  • Events

  • Client management

PostHog

This is the SDK reference for the PostHog Python SDK. You can learn more about example usage in the Python SDK documentation. You can also follow Flask and Django guides to integrate PostHog into your project. For long-running applications, create one client during application startup and reuse it for the lifetime of the process. This keeps background queues predictable and makes shutdown flushing straightforward. Multiple clients are still supported for intentional multi-project or multi-host setups.

Initialization methods
Client()

Release Tag: public

Initialize a new PostHog client instance.

Parameters
  • project_api_key? (str) - PostHog project API key/token.

  • host (any) - PostHog host. Defaults to the US ingestion endpoint when not set. App hosts such as https://us.posthog.com are mapped to the corresponding ingestion host.

  • debug (bool) - Enable verbose SDK logging and re-raise errors from public API methods.

  • max_queue_size (int) - Maximum number of events buffered before upload.

  • send (bool) - If False, queueing succeeds but events are not sent.

  • on_error (any) - Optional callback invoked by background consumers when an upload fails. Keep it short and non-blocking. Calling lifecycle methods directly is safe and deferred, but do not start another thread or task that calls flush(), join(), or shutdown() and then wait for it from the callback.

  • flush_at (int) - Number of queued events that triggers a batch upload.

  • flush_interval (float) - Maximum seconds a background consumer waits before flushing a partial batch.

  • gzip (bool) - Whether to gzip event upload payloads.

  • max_retries (int) - Number of upload retries. Values below 0 are treated as 0.

  • sync_mode (bool) - If True, send each event synchronously instead of using background worker threads. This blocks the calling thread; in asyncio applications such as FastAPI, use AsyncPosthog instead.

  • timeout (float) - HTTP request timeout in seconds for event uploads.

  • thread (int) - Number of background consumer threads.

  • poll_interval (int) - Seconds between local feature flag definition refreshes.

  • personal_api_key (any) - Deprecated alias for secret_key. Still honored for backwards compatibility; prefer secret_key, which also accepts a Project Secret API Key.

  • disabled (bool) - If True, disable captures and API requests. Useful in tests.

  • disable_geoip (bool) - Whether to disable server-side GeoIP enrichment. Defaults to True.

  • is_server (bool) - Whether events are emitted from a server-side runtime. Defaults to True; set to False when using the SDK as a client/CLI so the device OS is attributed to the person normally.

  • historical_migration (bool) - Mark events as historical migration imports.

  • feature_flags_request_timeout_seconds (float) - Timeout in seconds for feature flag and remote config requests.

  • feature_flags_request_max_retries (int) - Number of retries for feature flag requests after network, transport, or timeout failures. Defaults to 1. Set to 0 to disable retries.

  • super_properties (any) - Properties merged into every captured event.

  • enable_exception_autocapture (bool) - Automatically capture uncaught exceptions.

  • log_captured_exceptions (bool) - Also log exceptions captured by error tracking.

  • project_root (any) - Root path used to determine in-app stack frames for captured exceptions. Defaults to the current working directory.

  • privacy_mode (bool) - For AI observability, capture usage metadata without prompt inputs or outputs.

  • before_send (any) - Optional callback that can modify or drop events before upload. Return None to drop an event.

  • flag_fallback_cache_url (any) - Optional feature flag fallback cache URL, such as memory://local/?ttl=300&size=10000 or a Redis URL.

  • enable_local_evaluation (bool) - Whether to poll feature flag definitions for local evaluation when a personal API key is configured.

  • flag_definition_cache_provider? (FlagDefinitionCacheProvider) - Optional external cache provider for sharing feature flag definitions across workers.

  • capture_exception_code_variables (bool) - Capture local variable values on exception stack frames.

  • code_variables_mask_patterns (any) - Variable-name patterns to mask when capturing code variables.

  • code_variables_ignore_patterns (any) - Variable-name patterns to omit when capturing code variables.

  • code_variables_mask_url_credentials (any) - Scrub credentials embedded in URLs/DSNs (e.g. user:pass@host) from captured code variables, regardless of the surrounding variable name. Defaults to True.

  • code_variables_detect_secrets (any) - Last-resort entropy-based detection that redacts high-entropy secret-looking values (API keys, tokens, strong passwords) sitting in innocuously-named variables, after the name and URL checks. Skips structured ids (UUIDs, ObjectIds, hashes). Defaults to True.

  • in_app_modules (UnionType[list[str], any]) - Module/package prefixes treated as in-app frames in captured exceptions.

  • enable_exception_autocapture_rate_limiting (bool) - Rate limit autocaptured exceptions client-side with a token bucket per exception type. Disabled by default.

  • exception_autocapture_bucket_size (int) - Maximum burst of autocaptured exceptions allowed per exception type (token bucket size, clamped to 0-100).

  • exception_autocapture_refill_rate (int) - Tokens restored per refill interval for each exception type's bucket.

  • exception_autocapture_refill_interval_seconds (int) - Seconds between token refills for autocaptured exception rate limiting.

  • capture_mode (CaptureMode) - Capture wire protocol to use. Defaults to CaptureMode.V0 (legacy /batch/). Set CaptureMode.V1 (or pass the string "v1") to opt into /i/v1/analytics/events. When omitted, the POSTHOG_CAPTURE_MODE env var is consulted, then V0.

  • capture_compression (CaptureCompression) - Request-body compression for capture-v1 uploads (ignored in V0, which uses gzip). CaptureCompression.GZIP or DEFLATE (or the strings "gzip"/"deflate"). When omitted, the POSTHOG_CAPTURE_COMPRESSION env var is consulted, then the legacy gzip flag, then no compression.

  • secret_key (any) - A Personal API Key or Project Secret API Key, used to authenticate local feature flag evaluation, remote config payloads, and decrypted flag payloads. Example:: posthog.Client(project_api_key, secret_key="phx_...")

  • metrics? (dict)

  • enable_full_ai_capture (bool) - Route PostHog AI wrapper events through the dedicated AI capture endpoint and capture full AI content: skips string truncation and passes media (base64/data URIs) through unredacted. privacy_mode always wins. Defaults to False.

  • capture_trace_context (bool) - When OpenTelemetry is installed and a valid span is active at capture time, add its trace and span IDs as $trace_id and $span_id properties to events captured with capture() and capture_ai(), so they can be correlated with backend traces. Explicit $trace_id/$span_id values passed in properties win. Exception events (capture_exception) always attach these IDs regardless of this setting. Defaults to False.

  • _use_ai_lane (bool)

  • _enable_multimodal_capture (bool)

  • traces? (dict) - Config dict for distributed tracing: service_name, service_version, environment, resource_attributes, flush_interval (5 s), max_queue_size (2048), max_export_batch_size (512), max_live_spans (10000), max_span_age (3600 s), max_attributes_per_span (128), max_events_per_span (128), max_attribute_value_length (8192). before_span_send is a callable, or a list run in order, that receives each finished span as a dict (trace_id, span_id and parent_span_id are read-only) and returns it, edited, or None to drop it; a hook that raises drops the span. Tracing is off until this is provided. Spans export on a background timer even with sync_mode; serverless handlers should call flush() before returning. Defaults to None.

  • app_host? (str) - Your PostHog app host, such as https://posthog.example.com. emails sends there. Needed only when host is not PostHog Cloud, for example a reverse proxy, which must not receive the secret key.

  • email_request_timeout_seconds (float) - Timeout in seconds for each email send request. Defaults to 15.

  • email_request_max_retries (int) - Number of retries for an email send after a network error, a rate limit, or an unavailable service. Defaults to 2. Set to 0 when a job runner already retries the send.

  • migrated_from? (str) - The email provider you moved from, such as "resend". emails sends it with every request.

Returns
  • None

Examples
from posthog import Posthog

posthog = Posthog('<ph_project_api_key>', host='<ph_app_host>')

Identification methods
alias()

Release Tag: public

Create an alias between two distinct IDs.

Parameters
  • previous_id? (Number) - The previous distinct ID. Required - the call is dropped with a warning if it is missing or empty.

  • distinct_id? (str) - The new distinct ID to alias to. Falls back to the context distinct ID; the call is dropped with a warning if neither is available.

  • timestamp (datetime) - The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.

  • uuid? (str) - A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID.

  • disable_geoip? (bool) - Whether to disable GeoIP for this event.

Returns
  • Optional[str]

Examples
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')

group_identify()

Release Tag: public

Identify a group and set its properties.

Parameters
  • group_type? (str) - The type of group (e.g., 'company', 'team'). Required - the call is dropped with a warning if it is missing or empty.

  • group_key? (str) - The unique identifier for the group. Required - the call is dropped with a warning if it is missing or empty.

  • properties? (dict[str, Any]) - A dictionary of properties to set on the group.

  • timestamp (datetime) - The timestamp of the event. UTC is preferred; non-UTC datetimes and parseable ISO timestamp strings are converted to UTC.

  • uuid (str) - A unique identifier for the event. If provided, it must be a valid UUID string or uuid.UUID instance; invalid values are ignored and replaced with a newly generated UUID.

  • disable_geoip? (bool) - Whether to disable GeoIP for this event.

  • distinct_id (Number) - The distinct ID of the user performing the action.

Returns
  • Optional[str]

Examples
posthog.group_identify('company', 'company_id_in_your_db', {
    'name': 'Awesome Inc.',
    'employees': 11
})

set()

Release Tag: public

Set properties on a person profile.

Parameters
  • kwargs? (Unpack[OptionalSetArgs])

Returns
  • Optional[str]

Examples
# Set with distinct id
posthog.set(distinct_id='user123', properties={'name': 'Max Hedgehog'})

set_once()

Release Tag: public

Set properties on a person profile only if they haven't been set before.

Parameters
  • kwargs? (Unpack[OptionalSetArgs])

Returns
  • Optional[str]

Examples
posthog.set_once(distinct_id='user123', properties={'initial_signup_date': '2024-01-01'})

Capture methods
capture()

Release Tag: public

Captures an event manually. Learn about capture best practices

Parameters
  • event? (str) - The event name to capture.

  • kwargs? (Unpack[OptionalCaptureArgs])

Returns
  • Optional[str]

Examples
Anonymous event
# Anonymous event
posthog.capture('some-anon-event')
Context usage
# Context usage
from posthog import identify_context, new_context
with new_context():
    identify_context('distinct_id_of_the_user')
    posthog.capture('user_signed_up')
    posthog.capture('user_logged_in')
    posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')
Set event properties
# Set event properties
posthog.capture(
    "user_signed_up",
    distinct_id="distinct_id_of_the_user",
    properties={
        "login_type": "email",
        "is_free_trial": "true"
    }
)
Page view event
# Page view event
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})

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 queued on an isolated AI lane 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)

  • kwargs? (Unpack[OptionalCaptureArgs])

Returns
  • Optional[str]


Error Tracking methods
capture_exception()

Release Tag: public

Capture an exception for error tracking. When OpenTelemetry is installed and a valid span is active, its trace and span IDs are added as $trace_id and $span_id event properties.

Parameters
  • exception? (BaseException) - The exception to capture.

  • kwargs? (Unpack[OptionalCaptureArgs])

Returns
  • Optional[str]

Examples
try:
    # Some code that might fail
    pass
except Exception as e:
    posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)

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 :meth:capture via the flags option so events carry the exact flag values the code branched on. Prefer this over repeated get_feature_flag() calls and over capture(send_feature_flags=True) — it consolidates flag evaluation into a single /flags request per incoming request. Local evaluation is transparent: when the poller resolves a flag, the snapshot's $feature_flag_called events are tagged locally_evaluated=True and reason "Evaluated locally".

Parameters
  • distinct_id (Number) - The user's distinct ID. If None, falls back to the context distinct_id. If still unresolvable, returns an empty snapshot.

  • groups? (Mapping[str, Union[str, int]]) - Mapping of group type to group key.

  • person_properties? (dict[str, Any]) - Person properties to use for evaluation.

  • group_properties? (dict[str, dict[str, Any]]) - Group properties keyed by group type.

  • only_evaluate_locally (bool) - If True, never fall back to remote evaluation — flags that can't be evaluated locally are omitted from the snapshot and listed with a reason in its unresolved_flags.

  • disable_geoip? (bool) - Whether to disable GeoIP lookup.

  • flag_keys? (list[str]) - Optional list that scopes local evaluation, the underlying /flags request, and the returned snapshot. When omitted or None, all flags are evaluated. An empty list returns an empty snapshot without evaluating flags. A requested key absent from loaded local definitions is included in one remote fallback per evaluate_flags call unless only_evaluate_locally is True. If the server also does not know the key, it is omitted from the snapshot.

  • device_id? (str) - Optional device ID override. If not provided, falls back to the context device_id (which may be set via tracing headers). Used by experience-continuity flags to match users across distinct_id changes.

Returns
  • FeatureFlagEvaluations

Examples
flags = posthog.evaluate_flags(
    "user_123",
    person_properties={"plan": "enterprise"},
)
if flags.is_enabled("new-dashboard"):
    render_new_dashboard()
posthog.capture("page_viewed", distinct_id="user_123", flags=flags)

feature_enabled()

Release Tag: public

Check if a feature flag is enabled for a user.

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[bool]

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')

feature_flag_definitions()

Release Tag: public

Return feature flag definitions loaded for local evaluation. Returns: The currently loaded feature flag definitions, or None before local evaluation has loaded definitions.

Returns
  • None


get_all_flags()

Release Tag: public

Get all feature flags 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.

  • only_evaluate_locally (bool) - Whether to only evaluate locally.

  • 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
  • Optional[dict[str, Union[bool, str]]]

Examples
posthog.get_all_flags('distinct_id_of_your_user')

get_all_flags_and_payloads()

Release Tag: public

Get all feature flags and their 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.

  • only_evaluate_locally (bool) - Whether to only evaluate locally.

  • 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
posthog.get_all_flags_and_payloads('distinct_id_of_your_user')

get_feature_flag()

Release Tag: public

Get multivariate feature flag value for a user.

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
  • Union[bool, str, any]

Examples
enabled_variant = posthog.get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key': # replace 'variant-key' with the key of your variant
    # 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_flag_evaluation_runtime()

Release Tag: public

Return where a locally loaded feature flag is meant to be evaluated.

Parameters
  • key? (str) - The feature flag key.

Returns
  • Optional[FeatureFlagEvaluationRuntime]

Examples
from posthog import FeatureFlagEvaluationRuntime

runtime = posthog.get_feature_flag_evaluation_runtime("my-flag")
if runtime is FeatureFlagEvaluationRuntime.SERVER:
    ...

get_feature_flag_keys_by_evaluation_runtime()

Release Tag: public

Return the keys of locally loaded flags that a runtime can evaluate. A flag set to FeatureFlagEvaluationRuntime.ALL suits either runtime, so it is returned for CLIENT and for SERVER, and asking for ALL returns every loaded flag. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.

Parameters
  • evaluation_runtime? (FeatureFlagEvaluationRuntime) - The runtime to match, as a FeatureFlagEvaluationRuntime or its string value.

Returns
  • list[str]

Examples
from posthog import FeatureFlagEvaluationRuntime

client_keys = posthog.get_feature_flag_keys_by_evaluation_runtime(
    FeatureFlagEvaluationRuntime.CLIENT
)

get_feature_flag_payload()

Release Tag: public

Get the payload for a feature flag.

Parameters
  • key? (str) - The feature flag key.

  • distinct_id? (Number) - The distinct ID of the user.

  • match_value (bool) - The specific flag value to get payload for.

  • 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) - 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, ended spans and autocaptured metrics, 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 values the code branched on. Prefer this over repeated get_feature_flag() calls and over capture(send_feature_flags=True) — it consolidates flag evaluation into a single /flags request per incoming request.

Parameters
  • distinct_id (Number) - The user's distinct ID. If None, falls back to the context distinct_id. If still unresolvable, returns an empty snapshot.

  • groups? (Mapping[str, Union[str, int]]) - Mapping of group type to group key.

  • person_properties? (dict[str, Any]) - Person properties to use for evaluation.

  • group_properties? (dict[str, dict[str, Any]]) - Group properties keyed by group type.

  • only_evaluate_locally (bool) - If True, never fall back to remote evaluation and omit flags that cannot be evaluated locally. The snapshot's unresolved_flags lists them with a reason.

  • disable_geoip? (bool) - Whether to disable GeoIP lookup.

  • flag_keys? (list[str]) - Optional list that scopes local evaluation, the underlying /flags request, and the returned snapshot. When omitted or None, all flags are evaluated. An empty list returns an empty snapshot without evaluating flags. A requested key absent from loaded local definitions is included in one remote fallback per evaluate_flags call unless only_evaluate_locally is True. If the server also does not know the key, it is omitted from the snapshot.

  • device_id? (str) - Optional device ID override. If not provided, falls back to the context device_id (which may be set via tracing headers). Used by experience-continuity flags to match users across distinct_id changes.

Returns
  • FeatureFlagEvaluations

Examples
from posthog import evaluate_flags, capture
flags = evaluate_flags("user_123", person_properties={"plan": "enterprise"})
if flags.is_enabled("new-dashboard"):
    render_new_dashboard()
capture("page_viewed", distinct_id="user_123", flags=flags)

feature_enabled()

Release Tag: public

Use feature flags to enable or disable features for users.

Notes:

You can call posthog.load_feature_flags() before to make sure you're not doing unexpected requests.

Parameters
  • key? (str) - The feature flag key

  • distinct_id? (Number) - The user's distinct ID

  • groups? (Mapping[str, Union[str, int]]) - Groups mapping

  • person_properties? (dict[str, Any]) - Person properties

  • group_properties? (dict[str, dict[str, Any]]) - Group properties

  • only_evaluate_locally (bool) - Whether to evaluate only locally

  • send_feature_flag_events (bool) - Whether to send feature flag events

  • disable_geoip? (bool) - Whether to disable GeoIP lookup

  • device_id? (str) - Optional device ID override for experience-continuity flags

Returns
  • Optional[bool]

Examples
# Boolean feature flag
from posthog import feature_enabled, get_feature_flag_payload
is_my_flag_enabled = feature_enabled('flag-key', 'distinct_id_of_your_user')
if is_my_flag_enabled:
    matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')

feature_flag_definitions()

Release Tag: public

Returns loaded feature flags.

Notes:

Returns loaded feature flags, if any. Helpful for debugging what flag information you have loaded.

Returns
  • None

Examples
from posthog import feature_flag_definitions
definitions = feature_flag_definitions()

get_all_flags()

Release Tag: public

Get all flags for a given user.

Notes:

Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False.

Parameters
  • distinct_id? (Number) - The user's distinct ID

  • groups? (Mapping[str, Union[str, int]]) - Groups mapping

  • person_properties? (dict[str, Any]) - Person properties

  • group_properties? (dict[str, dict[str, Any]]) - Group properties

  • only_evaluate_locally (bool) - Whether to evaluate only locally

  • disable_geoip? (bool) - Whether to disable GeoIP lookup

  • device_id? (str) - Optional device ID override for experience-continuity flags

  • flag_keys_to_evaluate? (list[str]) - Optional list of flag keys to evaluate (evaluates all if None)

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

Examples
# All flags for user
from posthog import get_all_flags
get_all_flags('distinct_id_of_your_user')

get_all_flags_and_payloads()

Release Tag: public

Get all feature flag values and payloads for a user.

Parameters
  • distinct_id? (Number) - The user's distinct ID.

  • groups? (Mapping[str, Union[str, int]]) - Mapping of group type to group key.

  • person_properties? (dict[str, Any]) - Person properties to use for evaluation.

  • group_properties? (dict[str, dict[str, Any]]) - Group properties keyed by group type.

  • only_evaluate_locally (bool) - Whether to evaluate only locally.

  • disable_geoip? (bool) - Whether to disable GeoIP lookup.

  • device_id? (str) - Optional device ID override for experience-continuity flags.

  • flag_keys_to_evaluate? (list[str]) - Optional list of flag keys to evaluate. Evaluates all flags when omitted.

Returns
  • FlagsAndPayloads


get_feature_flag()

Release Tag: public

Get feature flag variant for users. Used with experiments.

Notes:

groups are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. group_properties take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}.

Parameters
  • key? (str) - The feature flag key

  • distinct_id? (Number) - The user's distinct ID

  • groups? (Mapping[str, Union[str, int]]) - Groups mapping from group type to group key

  • person_properties? (dict[str, Any]) - Person properties

  • group_properties? (dict[str, dict[str, Any]]) - Group properties in format { group_type_name: { group_properties } }

  • only_evaluate_locally (bool) - Whether to evaluate only locally

  • send_feature_flag_events (bool) - Whether to send feature flag events

  • disable_geoip? (bool) - Whether to disable GeoIP lookup

  • device_id? (str) - Optional device ID override for experience-continuity flags

Returns
  • Union[bool, str, any]

Examples
# Multivariate feature flag
from posthog import get_feature_flag, get_feature_flag_payload
enabled_variant = get_feature_flag('flag-key', 'distinct_id_of_your_user')
if enabled_variant == 'variant-key':
    matched_flag_payload = get_feature_flag_payload('flag-key', 'distinct_id_of_your_user')

get_feature_flag_evaluation_runtime()

Release Tag: public

Return where a locally loaded feature flag is meant to be evaluated.

Notes:

Reads the evaluation_runtime each flag definition carries, so no extra request is made. Returns None when local evaluation has not loaded a definition for this key. A definition that carries no runtime reports FeatureFlagEvaluationRuntime.ALL, the default PostHog applies.

Parameters
  • key? (str)

Returns
  • Optional[FeatureFlagEvaluationRuntime]

Examples
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_evaluation_runtime
runtime = get_feature_flag_evaluation_runtime("my-flag")

get_feature_flag_keys_by_evaluation_runtime()

Release Tag: public

Return the keys of locally loaded flags that a runtime can evaluate.

Notes:

A flag set to FeatureFlagEvaluationRuntime.ALL suits either runtime, so it is returned for CLIENT and for SERVER. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.

Parameters
  • evaluation_runtime? (FeatureFlagEvaluationRuntime)

Returns
  • list[str]

Examples
from posthog import FeatureFlagEvaluationRuntime, get_feature_flag_keys_by_evaluation_runtime
client_keys = get_feature_flag_keys_by_evaluation_runtime(FeatureFlagEvaluationRuntime.CLIENT)

get_feature_flag_payload()

Release Tag: public

Get the payload associated with a feature flag value. Deprecated for new code. Prefer evaluate_flags() and flags.get_flag_payload(key) so flag evaluation happens once per request.

Parameters
  • key? (str) - The feature flag key.

  • distinct_id? (Number) - The user's distinct ID.

  • match_value (bool) - Optional flag value to use when selecting a payload.

  • groups? (Mapping[str, Union[str, int]]) - Mapping of group type to group key.

  • person_properties? (dict[str, Any]) - Person properties to use for evaluation.

  • group_properties? (dict[str, dict[str, Any]]) - Group properties keyed by group type.

  • only_evaluate_locally (bool) - Whether to evaluate only locally.

  • send_feature_flag_events (bool) - Whether to send a $feature_flag_called event.

  • disable_geoip? (bool) - Whether to disable GeoIP lookup.

  • device_id? (str) - Optional device ID override for experience-continuity flags.

Returns
  • Optional[object]


load_feature_flags()

Release Tag: public

Load feature flag definitions from PostHog.

Returns
  • None

Examples
from posthog import load_feature_flags
load_feature_flags()

Client management methods
flush()

Release Tag: public

Attempt immediate delivery of queued events and ended spans, keeping the global client reusable. Call flush() before a short-lived request or serverless invocation returns when using the shared module-level client. Use shutdown() only for final process cleanup or 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 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, waiting up to this many seconds for an in-flight flush before starting a fresh drain budget. A lock wait timeout leaves the in-flight flush 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. The last span request is not cut short and is bounded by the client's timeout in seconds, so this is 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
import posthog
posthog.capture('event_name', distinct_id='user_id')
# Before a serverless invocation returns; keep the global client open.
posthog.flush(timeout_seconds=10)

join()

Release Tag: public

Attempt to process queued events and stop the client's background workers. Use shutdown() directly in most cases. 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
from posthog import join
join()

shutdown()

Release Tag: public

Attempt final delivery and permanently shut down the global client. Call this for final process cleanup, not at the end of each request or serverless invocation that shares the module-level client. Use flush() before returning from those invocations instead. Shutdown closes capture lanes, stops background workers and the feature flag poller, and tears down integrations. The global client is not recreated automatically after shutdown. This normally 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 a 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. Unsent queued spans and still-open spans are discarded with a warning. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. Calls made directly from SDK callbacks such as on_error are deferred to avoid deadlocking the worker. If blocking completion is required, signal an application-owned thread, return from the callback, and call shutdown() from that thread. Do not wait inside a callback for another thread or task calling a lifecycle method.

Returns
  • any

Examples
from posthog import shutdown
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.

  • 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
import posthog
posthog.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()}

Other methods
get_feature_flag_result()

Release Tag: public

Get a FeatureFlagResult object which contains the flag result and payload. This method evaluates a feature flag and returns a FeatureFlagResult object containing: - enabled: Whether the flag is enabled - variant: The variant value if the flag has variants - payload: The payload associated with the flag (automatically deserialized from JSON) - key: The flag key - reason: Why the flag was enabled/disabled

Parameters
  • key? (str) - The feature flag key.

  • distinct_id? (Number) - The user's distinct ID.

  • groups? (Mapping[str, Union[str, int]]) - Mapping of group type to group key.

  • person_properties? (dict[str, Any]) - Person properties to use for evaluation.

  • group_properties? (dict[str, dict[str, Any]]) - Group properties keyed by group type.

  • only_evaluate_locally (bool) - Whether to evaluate only locally.

  • send_feature_flag_events (bool) - Whether to send a $feature_flag_called event.

  • disable_geoip? (bool) - Whether to disable GeoIP lookup.

  • device_id? (str) - Optional device ID override for experience-continuity flags.

Returns
  • Optional[FeatureFlagResult]


get_remote_config_payload()

Release Tag: public

Get the payload for a remote config feature flag.

Parameters
  • key? (str) - The key of the feature flag

Returns
  • None


set_code_variables_mask_url_credentials_context()

Release Tag: public

Whether to scrub credentials embedded in URLs/DSNs (e.g. user:pass@host) from captured code variables for the current context.

Parameters
  • enabled? (bool)

Returns
  • None


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]


new_context()

Release Tag: public

Create a new context scope that will be active for the duration of the with block.

Parameters
  • fresh (bool) - Whether to start with a fresh context (default: False)

  • capture_exceptions? (bool) - Whether to capture exceptions raised within the context. If omitted, defaults to the relevant client's exception autocapture setting.

  • client? (Client) - Optional Posthog client instance to use for this context (default: None)

Returns
  • None

Examples
from posthog import new_context, tag, capture
with new_context():
    tag("request_id", "123")
    capture("event_name", properties={"property": "value"})

scoped()

Release Tag: public

Decorator that creates a new context for the function.

Parameters
  • fresh (bool) - Whether to start with a fresh context (default: False)

  • capture_exceptions? (bool) - Whether to capture and track exceptions with posthog error tracking. If omitted, defaults to the global exception autocapture setting.

Returns
  • None

Examples
from posthog import scoped, tag, capture
@scoped()
def process_payment(payment_id):
    tag("payment_id", payment_id)
    capture("payment_started")

set_capture_exception_code_variables_context()

Release Tag: public

Override code-variable capture for exceptions in the current context.

Parameters
  • enabled? (bool) - Whether exceptions captured in this context should include local variable values from stack frames.

Returns
  • None


set_code_variables_detect_secrets_context()

Release Tag: public

Whether to apply entropy-based secret detection as a last-resort redaction of high-entropy values (API keys, tokens, strong passwords) in captured code variables for the current context.

Parameters
  • enabled? (bool)

Returns
  • None


set_code_variables_ignore_patterns_context()

Release Tag: public

Override code-variable ignore patterns for exceptions in the current context.

Parameters
  • ignore_patterns? (list[str]) - Variable-name patterns that should be omitted entirely when code variables are captured.

Returns
  • None


set_code_variables_mask_patterns_context()

Release Tag: public

Override code-variable mask patterns for exceptions in the current context.

Parameters
  • mask_patterns? (list[str]) - Variable-name patterns whose values should be replaced with *** when code variables are captured.

Returns
  • None


set_context_device_id()

Release Tag: public

Set the device ID for the current context, associating all feature flag requests in this or child contexts with the given device ID.

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

Returns
  • None

Examples
from posthog import set_context_device_id
set_context_device_id("device_123")

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
  • None

Examples
from posthog import set_context_session
set_context_session("session_123")

tag()

Release Tag: public

Add a tag to the current context.

Parameters
  • name? (str) - The tag key

  • value? (Any) - The tag value

Returns
  • None

Examples
from posthog import tag
tag("user_id", "123")

Initialization methods
setup()

Release Tag: public

Create or return the global PostHog client configured by module settings. Most applications should either instantiate Posthog directly or set posthog.api_key/other module settings before calling top-level helpers. setup() is called automatically by global APIs such as capture(). Returns: The global Client instance. If both api_key and project_api_key are missing or blank, the client is disabled and module-level calls become no-ops.

Returns
  • Client


Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/omnibus/instrument-integration · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by PostHog or PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-integration.zip