NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI, #472 most downloaded on PyPI
Integrate PostHog into any python application.
Latest stable
8.1.0
Last release 2 days ago
20 Nov 2026
Ships on a steady schedule
a new release about every 8 days
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
7 years old
391 releases · first in 2020
Drag across the ruler to compare, or tap a release to open it.
7eece541 Update and delete offline experiment items, reported scores, and payloads from sync and async clients using the current revision. — Thanks @R
f6e999cc Use canonical numeric group keys for local feature-flag bucketing and fall back to remote evaluation for unsupported key types. — Thanks @Kay
posthog.emails sends emails, uploads attachments and reads email statuses through /api/messaging/..., which takes the project from the project secret API key. It no longer calls /api/projects/@current/messaging/..., since PostHog is removing the @current alias. Needs PostHog Cloud, or a self-hosted PostHog from 2026-11-18 or later. Older self-hosted versions answer these calls with a 404. — Thanks @rafaeelaudibert!posthog.exception_utils: only mark frames as in_app when their path is inside the project root directory, so sibling directories sharing the root's name as a prefix (e.g. /work/app-shared for root /work/app) are no longer treated as application code. — Thanks @MaiAditya!Your coding agent can read these notes before it upgrades. Set up the MCP server →
2eb7b9fa PostHogSpanProcessor no longer breaks export of spans started inside a PostHog context on opentelemetry-sdk 1.20 and 1.21. The span copy that
PostHogSpanProcessor no longer breaks export of spans started inside a PostHog context on opentelemetry-sdk 1.20 and 1.21. The span copy that carries the context's distinct ID, session ID and tags held plain dicts and tuples, but those SDK versions' OTLP encoder reads .dropped from its attributes, events and links and failed with AttributeError. The copy now also keeps the counts of attributes, events and links the SDK dropped under its span limits, which it previously reported as 0. — Thanks @fahad2932 for your first contribution 🎉!posthog.ai.openai: report OpenAI cache-write tokens as $ai_cache_creation_input_tokens, for streaming and non-streaming calls. OpenAI reports them in input_tokens_details.cache_write_tokens (Responses) or prompt_tokens_details.cache_write_tokens (Chat Completions) and bills them above the input rate, but the wrapper read only cached_tokens, so cache writes were costed as plain input tokens. — Thanks @alexeichhorn for your first contribution 🎉!…path is removed. See the migration guide for breaking changes. — Thanks @eli-r-ph !
$session_id or $window_id that is not a string is not sent, because capture v1 would reject the whole batch, and the SDK logs a warning for each one. The warning names the key and the value's type, not the value. None counts as unset and drops without a warning. An empty string is sent. In posthog-python 7.x.x these values were sent as properties. — Thanks @eli-r-ph!$trace_id and $span_id that the SDK takes from the active OpenTelemetry span now fill after the call's properties, context tags and super_properties, and before before_send. A $trace_id or $span_id in a context tag or super_properties now replaces the span's IDs, and setting either key stops the SDK adding both. AsyncPosthog follows the same rules. — Thanks @eli-r-ph!capture_exception takes a level= argument on Client, AsyncPosthog and the module, which sets $exception_level (default "error"). Reserved exception properties passed in properties, such as $exception_list and $exception_level, are now ignored. In posthog-python 7.x.x they overrode the SDK's values with a DeprecationWarning. AsyncPosthog.capture_exception now sends $exception_level. — Thanks @eli-r-ph!capture for a client object without capture_ai. Creating an OpenAI, Anthropic or Gemini wrapper, the LangChain CallbackHandler, or the OpenAI Agents or Claude Agent SDK processor with such a client now logs one error and captures no AI events. Provider calls still work. The error shows up when you set the integration up, and not after a provider call. A Client or AsyncPosthog instance, and the default global client, work as before. — Thanks @eli-r-ph!$lib and $lib_version as they are at send time, whoever set them. If no $lib is set in the call's properties, a context tag or super_properties, the SDK sets both to posthog-python and the installed version. If $lib is posthog-python and $lib_version is missing, the SDK fills in the version. A $lib that names another library is sent with whatever $lib_version it has, so set both when you override them. Only a non-empty string counts as set. In posthog-python 7.x.x the SDK overwrote a $lib or $lib_version set in a call or a context tag. before_send can still change or remove both, and AsyncPosthog follows the same rules. — Thanks @eli-r-ph!distinct_id after before_send, is dropped locally, an event that cannot be serialized is dropped alone (a non-finite float such as NaN is still sent as null), and a property key JSON cannot represent is dropped from its event. The analytics per-event limit is now capture's 10 MiB request limit instead of 900 KiB. A personal API key (phx_...) disables the client like an empty key. The SDK's own log lines no longer include event content or invalid timestamp values. AsyncPosthog follows the same rules. — Thanks @eli-r-ph!disable_geoip argument to a call now counts as a value of that event. It wins over a $geoip_disable in context tags or super_properties, and a $geoip_disable in the call's own properties still wins over it. disable_geoip=False now sends $geoip_disable: false, so it turns GeoIP lookup on for that event even when a context tag or super_properties turns it off. The client's disable_geoip setting keeps its place below every caller value. AsyncPosthog follows the same rules. — Thanks @eli-r-ph!group_identify falls back to the context distinct ID and then to $<group_type>_<group_key> instead of a random ID, and no longer adds the context session ID. alias() no longer takes its target from the context distinct ID. Context tags and options now apply to alias and group_identify, but context tags, context options, super_options and super_properties do not set process_person_profile on identify-style events ($identify, $create_alias, $merge_dangerously, $groupidentify, $set and $set_once) whose distinct ID the SDK did not generate. Those events default to True unless the call sets it. An empty or whitespace-only distinct_id counts as missing, and generated personless distinct IDs are UUIDv7. AsyncPosthog follows the same rules. — Thanks @eli-r-ph!307 or 308 redirect only to the origin of host, at most 5 times, for the sync and async clients. Any other redirect fails the batch and reaches on_error. In posthog-python 7.x.x the sync client followed redirects to any origin and resent the event batch there. — Thanks @eli-r-ph!path in posthog.request.post and after host in posthog.request.flags are keyword-only. With gzip removed, a posthog-python 7.x.x call that passed them by position bound them to the wrong parameter. It now raises TypeError. — Thanks @eli-r-ph!uuid is still replaced with a generated one, but the SDK now logs one warning instead of an error, and the warning no longer includes the value. An empty string uuid counts as unset, so the SDK generates one without logging. AsyncPosthog follows the same rules. — Thanks @eli-r-ph!posthog.mcp.instrument() and PostHogMCP changed $lib on every event the client sent, including the app's own, and the SDK name in its request headers, feature flag requests included. instrument() without a client relabeled the global client. Now only MCP analytics events report posthog-python-mcp, and everything else reports posthog-python. The label is set in each MCP event's own properties, so a $lib in super_properties no longer replaces it. before_send can. — Thanks @eli-r-ph!PostHogMCP capture methods and McpAnalytics.capture take an event_options argument, and MCPAnalyticsOptions(event_options=...) sets options on every event instrument() captures automatically, from a function of (request, extra) like event_properties. An event without an identity still always sends process_person_profile: False. PostHogMCP.capture() keeps the core client's options argument. — Thanks @eli-r-ph!AsyncPosthog.capture_exception now adds the active OpenTelemetry span's $trace_id and $span_id, like Client.capture_exception, even when capture_trace_context is off. — Thanks @eli-r-ph!set_context_option before a task is published apply to every event captured while the task runs. propagate_context=False sends none of them. — Thanks @eli-r-ph!posthog_properties also takes posthog_options (OpenAI, Anthropic, Gemini, sync and async, and the Claude Agent SDK query() and PostHogClaudeSDKClient), and the Gemini clients take it as a default for every call. LangChain's CallbackHandler and PostHogMiddleware, and instrument() and the tracing processors for OpenAI Agents and the Claude Agent SDK, take options=. LangChain also reads posthog_options from run metadata. These options win over context options and super_options. An event without a distinct ID still always sends process_person_profile: False, and a value that is not a dict is logged and ignored. — Thanks @eli-r-ph!cacdb6f6 AI integrations (LLM wrappers, embeddings, LangChain and OpenAI Agents) treat an empty or whitespace-only distinct_id as missing, as the client does: the event uses its trace or run ID and is personless. Before, an empty ID gave streaming calls, embeddings and LangChain the trace or run ID with person processing on, so PostHog created a person for each trace or run. Non-streaming wrapper calls used a random personless ID, and OpenAI Agents already treated an empty ID as missing. A whitespace-only ID was sent as given. — Thanks @eli-r-ph!
cacdb6f6 Capture timestamps always have six fractional-second digits, even on a whole second: 2026-01-02T03:04:05.000000+00:00, not 2026-01-02T03:04:05+00:00. This applies to the event timestamp, the batch created_at and the PostHog-Request-Timestamp header. The timestamp that before_send receives has the same format. — Thanks @eli-r-ph!
cacdb6f6 Capture retry waits now vary randomly by up to 25%, so many clients do not retry at the same moment. — Thanks @eli-r-ph!
cacdb6f6 Capture retries 404 and 429 responses like 408 and 500, 502, 503, 504, with the same backoff and Retry-After handling. — Thanks @eli-r-ph!
cacdb6f6 Capture makes one connection try per attempt, so every physical request carries its own attempt number and request timestamp. posthog-python 7.x.x also retried a failed connection up to twice inside each attempt, reusing the request timestamp, which shifted the events' stored time by the time spent connecting.
When before_send raises, the error line names the event and the exception type, not the exception message. The traceback is logged at debug level.
Events without NaN or Infinity are encoded once, without first copying them to replace non-finite numbers. Events that contain them still send those values as null. — Thanks @eli-r-ph!
cacdb6f6 Capture keeps the first event for each uuid in a request and drops the later copies. on_error now reports each dropped copy in CaptureError.drops as (uuid, "duplicate_event_uuid"), and the SDK does not resend it. Each entry of CaptureError.drops is a CaptureDroppedEvent from posthog.capture_send, a tuple that also has uuid and details fields. verdict_summary() counts each drop by its own reason. — Thanks @eli-r-ph!
8a88a289 Exception autocapture now sends a truncated string for source lines over 1024 bytes in a frame's context_line , pre_context and post_context
context_line, pre_context and post_context. Before, those lines were sent as null. — Thanks @Toraastrta for your first contribution 🎉!5b7a91a3 capture_exception() called without an exception now marks the exception it takes from sys.exc_info() as captured, so a later automatic captur
capture_exception() called without an exception now marks the exception it takes from sys.exc_info() as captured, so a later automatic capture of the same exception no longer sends a second $exception event. — Thanks @MaiAditya for your first contribution 🎉!84158304 Honor GEMINI_API_KEY when initializing the synchronous and asynchronous Gemini clients, after GOOGLE_API_KEY and before the legacy API_KEY fa
GEMINI_API_KEY when initializing the synchronous and asynchronous Gemini clients, after GOOGLE_API_KEY and before the legacy API_KEY fallback. — Thanks @pcbeingused333!posthog.ai.anthropic: messages.stream() (sync and async) now captures an $ai_generation event with $ai_is_error when the initial request fails, for example with a 401 or a connection error. Before, only messages.create(stream=True) captured that failure, so errors raised on entering the stream() context manager were never reported. — Thanks @pcbeingused333!error event inside a stream, such as overloaded_error, is no longer recorded with $ai_http_status: 200. The anthropic SDK raises it with the stream's 200 status, so $ai_http_status now comes from the error type (529 for overloaded_error, 429 for rate_limit_error), or is 0 for an unknown type. This applies to the LangChain callback handler and to every capture that reads the status through _get_http_status. — Thanks @jaeminbird!$ai_output_choices. — Thanks @MaiAditya for your first contribution 🎉!3511570b Treat server-marked failed feature flag records as unevaluated: direct result, value, enabled and payload getters return None rather than a d
cd821fbe A code send with posthog.emails.send takes cc , bcc and attachments : at most 10 files and 40 MB per message after Base64 encoding, about 29
posthog.emails.send takes cc, bcc and attachments: at most 10 files and 40 MB per message after Base64 encoding, about 29 MB of files, with the HTML counted twice when there is no text, since PostHog derives the text from it. An attachment is a filename and its content, as bytes or a Base64 string, with an optional content_type and content_id. The client checks the limits before any request, uploads each file PostHog doesn't hold yet straight to PostHog's file storage over https, never following a redirect, then sends the email with each file's SHA-256. A refused or redirected upload raises EmailError with the code attachment_upload_failed, and an unreachable storage network_error with field naming the attachment. Either way no email is sent. — Thanks @Silthus!dd7577bc posthog.mcp : a failed tool call now sets $mcp_error_status to the HTTP status behind it, read from the raised exception or its cause chain (
posthog.mcp: a failed tool call now sets $mcp_error_status to the HTTP status behind it, read from the raised exception or its cause chain (status_code, statusCode or status, on the exception or its response, as httpx.HTTPStatusError and requests.HTTPError carry it). Failures from an upstream API now group by status in MCP Analytics instead of landing in "unknown". — Thanks @lucasheriques!posthog.mcp: on mcp 1.x (1.10 and later), a tool registered with the low-level Server's @server.call_tool() decorator that raises now reports the exception it raised, with its cause chain, stack frames and $mcp_error_status, and $mcp_error_type names its class. Before, the decorator converted the exception into an error result first, so the failure was a generic Error with no frames and no status. — Thanks @lucasheriques!posthog.mcp: a failed tool call on a standalone FastMCP server now reports the exception the tool raised, with its cause chain and stack frames, and $mcp_error_type names its class. Before, FastMCP converted the exception into an error result first, so the failure was a generic Error with no frames. — Thanks @lucasheriques!capture_engagement is deprecated in favor of tracking={"engagement": False} . It keeps working, but PostHog refuses a send that sets both.
ac25b4bf A send with template_key now takes tracking and sensitive. The template form doesn't take either one.
tracking chooses what PostHog tracks for the email. tracking=True turns on opens, clicks and engagement events. tracking=False turns them all off. A dict such as {"clicks": True} or {"engagement": False} turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive.
sensitive marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless tracking turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose template_key matches a template saved in PostHog follows that template's setting, and any other send is sensitive. A send that sets neither option works exactly as before.
posthog.emails.send(
to="user@example.com",
template_key="newsletter",
subject="What's new at Acme",
html=rendered_html,
sensitive=False,
)capture_engagement is deprecated in favor of tracking={"engagement": False}. It keeps working, but PostHog refuses a send that sets both.
tracking and sensitive need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one. — Thanks @Silthus!
9636fa20 Support versioned composite scorers for offline evaluations, including formula validation, dependency metadata, explicit server calculations,
5378ece8 Keep frozenset and deque property values when cleaning events instead of replacing them with None. — Thanks @Ishkirat-Singh for your first co
frozenset and deque property values when cleaning events instead of replacing them with None. — Thanks @Ishkirat-Singh for your first contribution 🎉!c28716c2 Fix flag_fallback_cache_url for Redis URLs with an IPv6 host: the brackets are kept, so the Redis flag cache is no longer disabled. — Thanks
flag_fallback_cache_url for Redis URLs with an IPv6 host: the brackets are kept, so the Redis flag cache is no longer disabled. — Thanks @ioannisj!5febfd9b Send $experiment_exposure for config version 2 experiment splits, and send the reason code and rule attribution on $feature_flag_called for c
$experiment_exposure for config version 2 experiment splits, and send the reason code and rule attribution on $feature_flag_called for config version 2 flags in place of $feature_flag_reason. — Thanks @andehen!4d732304 The Anthropic wrapper now reports $ai_reasoning_tokens from usage.output_tokens_details.thinking_tokens, for both regular and streaming respo
$ai_reasoning_tokens from usage.output_tokens_details.thinking_tokens, for both regular and streaming responses. — Thanks @pcbeingused333!2m filter evaluated on March 31 resolved to January 31 and now resolves to January 28, and 4y on February 29 resolves to February 28 of the target year. — Thanks @luantaraschi!53770bc3 Events captured inside a Celery task now carry that task's own celery_* properties. Before, a task published from inside another task, such a
53770bc3 Events captured inside a Celery task now carry that task's own celery_* properties. Before, a task published from inside another task, such as a child task, a retry or a chord callback, reported the publishing task's celery_task_name, celery_task_id and celery_retry_count. — Thanks @eli-r-ph!
d572d099 AsyncPosthog no longer breaks two exception paths that read enable_exception_autocapture, a setting AsyncPosthog does not have:
$ai_generation, $ai_span or $ai_trace event. LangChain swallowed the error, so the event was never sent. The failed event is now sent without an $exception.new_context(client=<AsyncPosthog>) no longer raises AttributeError. Without capture_exceptions, it now leaves exceptions uncaptured; pass capture_exceptions=True to capture them. — Thanks @eli-r-ph!2c35f047 Capture an $ai_generation error event when create(stream=True) fails before the stream starts (bad key, rate limit, invalid model) in the Ope
$ai_generation error event when create(stream=True) fails before the stream starts (bad key, rate limit, invalid model) in the OpenAI chat, OpenAI Responses, Anthropic and Gemini wrappers, sync and async. Previously only errors raised mid-stream were captured. — Thanks @pcbeingused333!2a2e5788 An exception passed to capture_exception without being raised now gets its synthesized stack in outermost-first order, without the SDK's own
capture_exception without being raised now gets its synthesized stack in outermost-first order, without the SDK's own capture frames, and with mechanism.synthetic set to true. — Thanks @luantaraschi!3c398e59 With capture_mode="v1", capture now retries 404 and 429 responses like 408 and 500, 502, 503, 504, with the same backoff and Retry-After hand
capture_mode="v1", capture now retries 404 and 429 responses like 408 and 500, 502, 503, 504, with the same backoff and Retry-After handling. Before, both failed the batch at once. — Thanks @andehen!bf3adb3f A flag record that the server marks failed no longer returns a payload, even when the record still carries metadata.payload. A failed flag re
failed no longer returns a payload, even when the record still carries metadata.payload. A failed flag reads as disabled, so get_feature_flag_payload(), get_feature_flag_result().payload and a snapshot's get_flag_payload() now return None for it, and its $feature_flag_called events leave out $feature_flag_payload. get_all_flags_and_payloads() and get_feature_payloads() already left it out. This applies to responses from both /flags?v=4 and older servers. — Thanks @andehen!5f2ee56 posthog.mcp is now stable. From this release, a minor or patch release of posthog no longer makes breaking changes to the posthog.mcp API, ren…
0aa5df1 MCP analytics now matches the cross-SDK MCP spec ahead of 1.0:
instrument() sends $mcp_unknown_tool instead of a failed $mcp_tool_call and $exception when a tools/call names a tool your server never registered. Insights that count failed tool calls stop counting these. A call naming no tool sends nothing. A raw low-level server has no registry the SDK can read, so a failed call there stays a failed tool call.llm_model injection on standalone fastmcp.FastMCP.session_id now sends a fresh ses_ session id and uses it as the distinct_id, instead of no $session_id and an anonymous person.... marker included, so $mcp_tool_name and other names stop at 256 characters instead of 259. — Thanks @lucasheriques!5f2ee56 posthog.mcp is now stable. From this release, a minor or patch release of posthog no longer makes breaking changes to the posthog.mcp API, renames or removes a $mcp_* event or property, changes its type, or changes which requests send an event, so your saved insights keep working across upgrades. New events and properties can still arrive in minor releases. Upgrading needs no code change. — Thanks @lucasheriques!
posthog.mcp no longer tries to read the advertised tool schema on each call. FastMCP 2.x can only list tools through request middleware, which can spend rate limits, so the lookup failed and logged an error on every call. Argument names there stay redacted in $mcp_input_keys, as before. — Thanks @lucasheriques!778f386 MCP analytics tool definitions change in three ways:
778f386 MCP analytics tool definitions change in three ways:
get_more_tools and send_feedback declare readOnlyHint, destructiveHint, idempotentHint, and openWorldHint as false, because a call records data in your PostHog project. Their annotations no longer carry a title.context argument has a shorter description.llm_model argument is always optional.These changes alter your published tool definitions. If your server is listed in the ChatGPT or Claude directories, those platforms may re-review the updated tools. — Thanks @lucasheriques!
3f93a34 Exclude client-only feature flags from definition-load warnings about experience continuity and unsupported definitions, without changing loca
11585fb Stop retrying /flags requests when the connection is refused, so the flag error surfaces right away instead of after the retry backoff. — Than
/flags requests when the connection is refused, so the flag error surfaces right away instead of after the retry backoff. — Thanks @luantaraschi!f3116ff Reworded the descriptions of the injected conversation_id and llm_model arguments and the get_more_tools and send_feedback virtual tools so th
conversation_id and llm_model arguments and the get_more_tools and send_feedback virtual tools so they describe the field instead of instructing the model. This changes your published tool definitions; if your server is listed in the ChatGPT or Claude directories, those platforms may re-review the updated tools. — Thanks @lucasheriques!063f1ce posthog.emails.send() can now send email content your code rendered, such as HTML from Jinja or React Email. Give the email a template_key and
063f1ce posthog.emails.send() can now send email content your code rendered, such as HTML from Jinja or React Email. Give the email a template_key and a subject, and pass html, text or both.
posthog = Posthog("phc_...", secret_key="phs_...")
result = posthog.emails.send(
to="user@example.com",
distinct_id="user_123",
template_key="password-reset",
subject="Reset your password",
html=rendered_html,
)
# "delivered", "bounced", ...
status = posthog.emails.get(result.id).status
You need a project secret API key, the kind that starts with phs_. Create one under Project secret API keys in your project settings. Set its Transactional email scope to Write to send emails, or to Read for a key that only reads statuses. Pass it to the client as secret_key. Set app_host to your PostHog app URL when you self-host PostHog or send through a reverse proxy.
PostHog records each email's delivery, opens and clicks on the person with that distinct_id. It groups every email with the same template_key, so you see their metrics and logs in one place. The SDK retries a request that hits a network error, a rate limit or an outage twice by default. Every send carries an idempotency key, so a retry never sends the email twice. Pass your own idempotency_key, such as welcome:user_123, and your job runner's retries are safe too.
A send with your own content also takes from_, reply_to and capture_engagement=False. Set migrated_from on the client to tell PostHog which email provider you moved from. A failed call raises an EmailError with PostHog's code and the HTTP status_code.
Docs: Send transactional emails with Python and the transactional email overview. — Thanks @Silthus!
ChatAnthropic call that reads or writes the prompt cache. It took the raw Anthropic usage from response_metadata, whose input tokens already exclude the cache, and subtracted the cache tokens again, so a cached call usually reported 0 input tokens. It now reads LangChain's standard usage_metadata first, as it already did for streamed calls. — Thanks @jaeminbird for your first contribution 🎉!7cd0d8a Streaming Gemini calls that fail now record the HTTP status of the google-genai error (for example 429 or 503) in $ai_http_status. Before, cap
$ai_http_status. Before, capture_streaming_event read only status_code, so these events were captured with a status of 0. — Thanks @pcbeingused333!ae2dcf2 Local evaluation now respects early access feature enrollment. A flag with feature enrollment uses the $feature_enrollment/ person property wh
$feature_enrollment/<flag key> person property when you pass it, and otherwise falls back to the flags service. Before, it returned False for enrolled people who matched no release condition, while the flags service returned True. — Thanks @puemos for your first contribution 🎉!0c12ca1 PostHogMCP.prepare_tool_list now adds the context argument to MCP SDK 2.x Tool objects. It only added it to dicts and 1.x Tool objects before,
PostHogMCP.prepare_tool_list now adds the context argument to MCP SDK 2.x Tool objects. It only added it to dicts and 1.x Tool objects before, so $mcp_intent was never captured for 2.x tool objects. — Thanks @connor-grady!e094dc5 Request /flags?v=4 and read each flag's typed value, reason and metadata. They stay internal for now: this release adds no public methods, fie
/flags?v=4 and read each flag's typed value, reason and metadata. They stay internal for now: this release adds no public methods, fields or types for them, and repr, equality and dataclasses.asdict of a flag show only its existing fields. Servers that still send the older response keep working, and a flag record with a field of the wrong JSON type fails only that flag. For valid flag records, existing getters, callbacks and $feature_flag_called properties return the same values as before: a number or object value reads as True, with the value as its payload. Two things can differ: the human-readable reason text of a config version 2 flag is the one the server sends at v4, and a record with a known field of the wrong JSON type (for example a string reason) now reads as a failed flag instead of being read anyway or failing the whole response. The SDK logs once per client when a server sends a response without typed values. FlagMetadata.id and FlagMetadata.version are None when a record has none, instead of 0, so their type is now Optional[int]. — Thanks @andehen!57b9db8 Count Gemini URL context tool use prompt tokens as input tokens in captured generations; Google Search retrieval is not billed as input and st
9ebfb87 Fix a race condition where concurrent feature flag fallback-cache eviction could raise KeyError instead of returning a cache miss, including d
regex and not_regex matching, so booleans, lists, and objects match the same way they do on the flags service. — Thanks @luantaraschi!b10c38a Add a per-read send_feature_flag_events option to FeatureFlagEvaluations.is_enabled() and get_flag(). Pass send_feature_flag_events=False to r
send_feature_flag_events option to FeatureFlagEvaluations.is_enabled() and get_flag(). Pass send_feature_flag_events=False to read a flag from an evaluate_flags() snapshot without sending $feature_flag_called. The read leaves the dedupe cache alone, so a later read that sends events still reports the flag, and the key still counts as accessed for only_accessed(). The option defaults to True, as on get_feature_flag(). — Thanks @andehen!$feature_flag_id and $feature_flag_version to $feature_flag_called events for locally evaluated flags in get_feature_flag(), feature_enabled() and get_feature_flag_result(), and $feature_flag_version for locally evaluated flags in evaluate_flags(), taken from the flag definition. Remotely evaluated flags already sent both. — Thanks @andehen!f20066e emails.send() now sends the template ID and distinct ID as top-level fields in the request body. — Thanks @mayteio!
emails.send() now sends the template ID and distinct ID as top-level fields in the request body. — Thanks @mayteio!be77b83 Keep the choices of a streamed OpenAI chat completion with n > 1 apart in $ai_output_choices, as a non-streamed one already does. Their text a
n > 1 apart in $ai_output_choices, as a non-streamed one already does. Their text and tool calls were interleaved into one choice. — Thanks @jaeminbird for your first contribution 🎉!01e91db Send transactional email from PostHog email templates with client.emails.send() on Posthog and AsyncPosthog, or with Emails and AsyncEmails fr
client.emails.send() on Posthog and AsyncPosthog, or with Emails and AsyncEmails from posthog.emails in a process that only sends email. A send needs a project secret API key, goes to the app host, sends an idempotency key, and retries network errors, rate limits and an unavailable service with the same key. Set app_host, email_request_timeout_seconds and email_request_max_retries on the client to configure sends, or max_retries on one send. Errors raise EmailError with PostHog's error code and a category name. Read what happened to a sent email with client.emails.get(message_id), which returns an EmailStatus with status, created_at, status_at and reason for 30 days after the send. — Thanks @mayteio for your first contribution 🎉!4d6e447 Report cached input tokens from OpenAI Agents generation and response spans, which nest them under the usage details fields, and declare them
ad1b1cb Capture an $ai_embedding event with $ai_is_error and $ai_error when an OpenAI embeddings.create() call fails, in the sync and async wrappers.
$ai_embedding event with $ai_is_error and $ai_error when an OpenAI embeddings.create() call fails, in the sync and async wrappers. Before, a failed embeddings call left no event. — Thanks @pcbeingused333!1625f4f Fix streaming OpenAI chat completions when stream_options is None or NOT_GIVEN (it raised a TypeError), and stop adding include_usage to the s
stream_options is None or NOT_GIVEN (it raised a TypeError), and stop adding include_usage to the stream_options dict the caller passed in. — Thanks @pcbeingused333!febb3ed Add metrics={"autocapture": True} (alpha): HTTP, database and runtime metrics from the official OpenTelemetry instrumentations, with no instru
febb3ed Add metrics={"autocapture": True} (alpha): HTTP, database and runtime metrics from the official OpenTelemetry instrumentations, with no instrumentation code. Install posthog[metrics] and run opentelemetry-bootstrap -a install to add the instrumentors for your libraries. Create the client before your web app (Django: in AppConfig.ready()): apps created earlier are not measured. For Flask, use module lookup as below, or import the Flask class only after the client starts; an earlier from flask import Flask alias is not instrumented. Already-served Flask apps are not re-instrumented after shutdown; create a new app for a replacement client. Autocapture does not start when the app already set up OpenTelemetry; export those metrics to PostHog instead. Raw URLs and paths, client addresses, user agents and captured headers are never recorded. metrics.before_send also applies to autocaptured measurements: it can change their value and attributes, or drop them.
import flask
from posthog import Posthog
client = Posthog("phc_...", metrics={"autocapture": True})
app = flask.Flask(__name__)
— Thanks @DanielVisca!
bb2b9d6 Report flags that local evaluation could not resolve on evaluate_flags() snapshots. FeatureFlagEvaluations.unresolved_flags maps each such fla
bb2b9d6 Report flags that local evaluation could not resolve on evaluate_flags() snapshots. FeatureFlagEvaluations.unresolved_flags maps each such flag to an UnresolvedFlagReason (experience_continuity, unsupported_definition, unresolved_dependency or missing_context), and reading one reports the local_evaluation_inconclusive error instead of flag_missing. When definitions load, log one warning per flag that local evaluation can never resolve (experience continuity, a static cohort, an unknown operator, a malformed value, or a missing or circular flag dependency), and again only when its definition changes. AsyncClient evaluates only remotely, so its snapshots have no unresolved flags.
Behavior changes:
only_evaluate_locally=True.false locally instead of falling back to a remote request.only_evaluate_locally=True.$feature_flag_called events from an evaluate_flags() snapshot, $feature_flag_error is now local_evaluation_inconclusive instead of flag_missing for a flag that has a loaded definition but that local evaluation could not resolve.get_all_flags(), get_all_flags_and_payloads() and evaluate_flags() no longer log an error with a traceback when a flag needs the server (for example, a static cohort). They fall back to a remote request without logging, as get_feature_flag() already did. — Thanks @gustavohstrassburger!351da59 Add a send_tools_list_event option to MCP analytics. It is on by default. Set it to False to stop sending $mcp_tools_list. — Thanks @gesh!
send_tools_list_event option to MCP analytics. It is on by default. Set it to False to stop sending $mcp_tools_list. — Thanks @gesh!d8a1b97 Add a send_initialize_event option to MCP analytics. It is on by default. Set it to False to stop sending $mcp_initialize. — Thanks @gesh!
send_initialize_event option to MCP analytics. It is on by default. Set it to False to stop sending $mcp_initialize. — Thanks @gesh!b0a2b59 The LangChain callback handler now records $ai_web_search_count for Anthropic responses that report server_tool_use.web_search_requests, as th
$ai_web_search_count for Anthropic responses that report server_tool_use.web_search_requests, as the OpenAI, Anthropic and Gemini wrappers and posthog-js already do. — Thanks @pcbeingused333!284340d Add optional per-item model_version to offline evaluations and dataset conversion, preserving model attribution across serialization, retries,
04e6a4c Privacy mode now covers error text and the remaining content paths in the AI integrations.
04e6a4c Privacy mode now covers error text and the remaining content paths in the AI integrations.
$ai_error no longer carries the exception message when privacy mode is on. Provider errors and validation errors often quote the prompt or the model output, so the SDK now sends a summary built only from structured fields: the class name, HTTP status, provider error code, param, request ID and the class names of chained causes (for example BadRequestError: 400 invalid_request_error param=messages[3].content request_id=req_123). This applies to the OpenAI, Anthropic and Gemini wrappers (including Gemini embeddings), LangChain generations, spans and traces, and OpenAI Agents spans.$exception event for a failed run when privacy mode is on.$ai_tools masks the headers and authorization of MCP tool definitions (type: "mcp") with [REDACTED], with or without privacy mode. The tools you pass in are not modified.posthog_privacy_mode=False no longer turns off privacy mode set on the client, matching the OpenAI and Anthropic wrappers.$ai_trace_metadata and the prompt and instructions in transcription and speech span model_config.PostHogSpanProcessor and PostHogTraceExporter accept privacy_mode and client, and also honor the client's (or the module-level) privacy_mode. When on, exported spans drop prompt, completion, tool argument and tool result attributes, non-exception span events, exception messages and stack traces, and the span status description. — Thanks @carlos-marchal-ph!25d2767 Failed Gemini calls are now captured with the HTTP status of the error as $ai_http_status (for example 429 or 503) instead of 0. google-genai
$ai_http_status (for example 429 or 503) instead of 0. google-genai errors carry the status as code rather than status_code, which the OpenAI and Anthropic wrappers already read. — Thanks @pcbeingused333!8cd8eb5 MCP analytics now sends one $mcp_initialize for each initialize request that a client sends.
8cd8eb5 MCP analytics now sends one $mcp_initialize for each initialize request that a client sends.
Before, the SDK sent the event on the first request of each session, once per process. A stateless fleet sent one event for each pod that a session reached. A conversation-anchored session sent another event. A client that connected and sent no other request sent no event.
On MCP SDK 2.x, the event comes from Server.middleware on every transport. Requests on the 2026-07-28 spec, which has no initialize, no longer send one. On MCP SDK 1.x over HTTP, the event comes from PostHogMcpStatelessSessionMiddleware. The apps that instrument() autowires get this with no change. If you mount the middleware by hand, pass the server as server=. MCP SDK 1.x over stdio keeps the first request as the trigger.
The event now also has the handshake request as $mcp_parameters. On MCP SDK 2.x, it also has the server reply as $mcp_response. — Thanks @gesh!
48889b6 The Claude Agent SDK integration now takes the cumulative input and cache token counts from the final message_delta usage, which grow past the message_start values when server tools such as web search run, and sets $ai_web_search_count from server_tool_use.web_search_requests. Streamed generations used to under-report input tokens and cache writes and never recorded the web search count. — Thanks @pcbeingused333!
d58380e Defer feature flag regex patterns with unsupported syntax or incompatible matching semantics to server evaluation instead of returning incorre
ffde3c5 Streamed OpenAI-compatible chat completions whose tool call deltas carry no index are no longer dropped from $ai_output. A delta with a new id
index are no longer dropped from $ai_output. A delta with a new id starts a call, and one without an id continues the latest call. — Thanks @pcbeingused333!a95331f Retain the minimal-event gate and experiment metadata from the local definitions used by evaluate_flags(), including first-use loading and def
evaluate_flags(), including first-use loading and definition refreshes during evaluation. — Thanks @dustinbyrne!b3fcec6 Annotate timeout and feature_flags_request_timeout_seconds as float on Client, AsyncClient, Consumer and the request helpers, so type checkers
timeout and feature_flags_request_timeout_seconds as float on Client, AsyncClient, Consumer and the request helpers, so type checkers accept fractional timeouts such as timeout=2.5. The values were already passed straight to requests and httpx, which take floats, so runtime behaviour is unchanged. — Thanks @turnipdabeets!34ec4f8 Streamed Anthropic generations no longer stack output tokens when a stream emits more than one message_delta (server tools can send several).
message_delta (server tools can send several). Each delta's usage is cumulative, so the accumulator now keeps the latest total instead of adding every delta together. — Thanks @Harsh23Kashyap!a6ddc2e The LangChain callback handler now records $ai_http_status as an integer for failed generations. An error that carries a string code and no st
$ai_http_status as an integer for failed generations. An error that carries a string code and no status code (such as OpenAI's rate_limit_exceeded) gave a string status; it now gives 0, as an error without a status already did. — Thanks @pcbeingused333 for your first contribution 🎉!$ai_output_choices: the refusal text is recorded as a refusal content block, as it already is for streamed responses. — Thanks @pcbeingused333 for your first contribution 🎉!$ai_is_error and $ai_error (and the error's status code as $ai_http_status) instead of being recorded as a successful 200. The error is still re-raised to the caller, matching what non-streaming calls already did. — Thanks @pcbeingused333 for your first contribution 🎉!4697e6f Capture Chat Completions responses that contain custom tool calls instead of raising AttributeError from the wrapped create() call. — Thanks @
AttributeError from the wrapped create() call. — Thanks @mosafariuk!e9056e3 Fix local feature flag string and regex operators to match an explicit null property as "null", like the flags service. This can change flag v
5f01fe9 Add an optional OpenTelemetry span processor for PostHog request IDs and enrich active Django request spans after request context is available
b8879a7 Manage AI observability datasets and items through OfflineEvaluations.datasets and AsyncOfflineEvaluations.datasets, including history, tags,
OfflineEvaluations.datasets and AsyncOfflineEvaluations.datasets, including history, tags, and archive/restore operations. Pin a dataset snapshot for lazy, consistent reads and use EvaluationItem.from_dataset_item() to preserve case provenance across offline experiments and scorers. Item creates with a caller-supplied client_item_id support safe retries; updates use explicit version checks. — Thanks @Radu-Raicea!57d1607 Streamed Anthropic generations now take the input and cache token counts from the final message_delta usage, which is cumulative. With server
message_delta usage, which is cumulative. With server tools such as web search, those counts grow past the message_start values, so streamed calls under-reported input tokens and cache writes. — Thanks @pcbeingused333 for your first contribution 🎉!openai.Stream API on sync OpenAI chat completions and Responses streams, so with, close() and attributes such as .response work as they do without PostHog. — Thanks @mosafariuk for your first contribution 🎉!One column per quarter.