Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions openfeature-provider/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@ All notable changes to `openfeature-provider-posthog` are documented here. This
file is maintained by [Sampo](https://github.com/bruits/sampo) from changesets in
`.sampo/changesets/` that target `pypi/openfeature-provider-posthog`.

## 0.1.140 β€” 2026-11-02

### Patch changes

- Updated dependencies: posthog@7.82.2

## 0.1.139 β€” 2026-11-02

### Patch changes

- Updated dependencies: posthog@7.82.1

## 0.1.138 β€” 2026-11-02

### Patch changes

- Updated dependencies: posthog@7.82.0

## 0.1.137 β€” 2026-11-02

### Patch changes

- Updated dependencies: posthog@7.81.2

## 0.1.136 β€” 2026-10-30

### Patch changes
Expand Down
2 changes: 1 addition & 1 deletion openfeature-provider/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "openfeature-provider-posthog"
version = "0.1.136"
version = "0.1.140"
description = "Official PostHog provider for the OpenFeature Python SDK."
readme = "README.md"
authors = [{ name = "PostHog", email = "engineering@posthog.com" }]
Expand Down
30 changes: 30 additions & 0 deletions posthog/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
# posthog

## 7.82.2 β€” 2026-11-02

### Patch changes

- [57b9db8](https://github.com/posthog/posthog-python/commit/57b9db8493bc06dc448bda244020eea1e0ed1ec5) Count Gemini URL context tool use prompt tokens as input tokens in captured generations; Google Search retrieval is not billed as input and stays out of the total. β€” Thanks @pcbeingused333!

## 7.82.1 β€” 2026-11-02

### Patch changes

- [9ebfb87](https://github.com/posthog/posthog-python/commit/9ebfb87ce3eefb2f3672c99e1b4f083013fe864b) Fix a race condition where concurrent feature flag fallback-cache eviction could raise KeyError instead of returning a cache miss, including during request failures. β€” Thanks @Sarbajit-Sengupta for your first contribution πŸŽ‰!
- [5b50683](https://github.com/posthog/posthog-python/commit/5b506837995c1ddbb007e8822221552c21b06748) Stringify non-string properties as compact JSON for local `regex` and `not_regex` matching, so booleans, lists, and objects match the same way they do on the flags service. β€” Thanks @luantaraschi!
- [a239479](https://github.com/posthog/posthog-python/commit/a239479585d5c5367843ec088e49f52010223d08) Serialize UUID values in feature flag request bodies instead of failing the evaluation, so a UUID distinct id, group key, or flag property reaches the flags service. β€” Thanks @luantaraschi!

## 7.82.0 β€” 2026-11-02

### Minor changes

- [b10c38a](https://github.com/posthog/posthog-python/commit/b10c38ac3928f3b1cef743dab234e17720c81f08) Add a per-read `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!

### Patch changes

- [e24100b](https://github.com/posthog/posthog-python/commit/e24100b413d8f1a4f14c49dbee3391c8675fb2ff) Add `$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!

## 7.81.2 β€” 2026-11-02

### Patch changes

- [f20066e](https://github.com/posthog/posthog-python/commit/f20066e7f2826dab701a8d73fbfd5780c4ccd49a) `emails.send()` now sends the template ID and distinct ID as top-level fields in the request body. β€” Thanks @mayteio!

## 7.81.1 β€” 2026-10-30

### Patch changes
Expand Down
7 changes: 6 additions & 1 deletion posthog/ai/gemini/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
extract_gemini_embedding_token_count as extract_gemini_embedding_token_count,
extract_gemini_stop_reason_from_chunk,
extract_gemini_usage_from_chunk,
has_gemini_url_context,
format_gemini_streaming_output as format_gemini_streaming_output,
)

Expand Down Expand Up @@ -267,10 +268,14 @@ def generator():
nonlocal accumulated_content
nonlocal stop_reason
stream_error: Optional[BaseException] = None
url_context_seen = False
try:
for chunk in response:
# Extract usage stats from chunk
chunk_usage = extract_gemini_usage_from_chunk(chunk)
url_context_seen = url_context_seen or has_gemini_url_context(chunk)
chunk_usage = extract_gemini_usage_from_chunk(
chunk, url_context_seen=url_context_seen
)

if chunk_usage:
# Gemini reports cumulative totals, not incremental values
Expand Down
7 changes: 6 additions & 1 deletion posthog/ai/gemini/gemini_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
extract_gemini_embedding_token_count as extract_gemini_embedding_token_count,
extract_gemini_stop_reason_from_chunk,
extract_gemini_usage_from_chunk,
has_gemini_url_context,
format_gemini_streaming_output as format_gemini_streaming_output,
)

Expand Down Expand Up @@ -254,10 +255,14 @@ async def async_generator():
nonlocal stop_reason

stream_error: Optional[BaseException] = None
url_context_seen = False
try:
async for chunk in response:
# Extract usage stats from chunk
chunk_usage = extract_gemini_usage_from_chunk(chunk)
url_context_seen = url_context_seen or has_gemini_url_context(chunk)
chunk_usage = extract_gemini_usage_from_chunk(
chunk, url_context_seen=url_context_seen
)

if chunk_usage:
# Gemini reports cumulative totals, not incremental values
Expand Down
43 changes: 38 additions & 5 deletions posthog/ai/gemini/gemini_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,19 +517,42 @@ def extract_gemini_web_search_count(response: Any) -> int:
return 0


def _extract_usage_from_metadata(metadata: Any) -> TokenUsage:
def has_gemini_url_context(response: Any) -> bool:
"""Whether a response or chunk carries URL context retrieval metadata."""
candidates = getattr(response, "candidates", None)
if not isinstance(candidates, (list, tuple)):
return False
return any(getattr(c, "url_context_metadata", None) for c in candidates)


def _extract_usage_from_metadata(
metadata: Any, bill_tool_use_tokens: bool = False
) -> TokenUsage:
"""
Common logic to extract usage from Gemini metadata.
Used by both streaming and non-streaming paths.

Args:
metadata: usage_metadata from Gemini response or chunk
bill_tool_use_tokens: whether tool_use_prompt_token_count is billed as
input (URL context). Google Search retrieval is not billed as input.

Returns:
TokenUsage with standardized usage
"""
input_tokens = getattr(metadata, "prompt_token_count", 0)

# Built-in tools report the retrieved content separately from
# prompt_token_count. URL context content is billed as input; Google Search
# retrieval is not, so only add it when the response used URL context.
# (A response that used both tools cannot be split from these counts.)
if bill_tool_use_tokens:
tool_use_tokens = getattr(metadata, "tool_use_prompt_token_count", 0)
if isinstance(tool_use_tokens, int) and tool_use_tokens > 0:
input_tokens += tool_use_tokens

usage = TokenUsage(
input_tokens=getattr(metadata, "prompt_token_count", 0),
input_tokens=input_tokens,
output_tokens=getattr(metadata, "candidates_token_count", 0),
)

Expand Down Expand Up @@ -573,7 +596,9 @@ def extract_gemini_usage_from_response(response: Any) -> TokenUsage:
if not hasattr(response, "usage_metadata") or not response.usage_metadata:
return TokenUsage()

usage = _extract_usage_from_metadata(response.usage_metadata)
usage = _extract_usage_from_metadata(
response.usage_metadata, bill_tool_use_tokens=has_gemini_url_context(response)
)

# Add web search count if present
web_search_count = extract_gemini_web_search_count(response)
Expand All @@ -583,12 +608,17 @@ def extract_gemini_usage_from_response(response: Any) -> TokenUsage:
return usage


def extract_gemini_usage_from_chunk(chunk: Any) -> TokenUsage:
def extract_gemini_usage_from_chunk(
chunk: Any, url_context_seen: bool = False
) -> TokenUsage:
"""
Extract usage statistics from a Gemini streaming chunk.

Args:
chunk: Streaming chunk from Gemini API
url_context_seen: whether an earlier chunk of the same stream carried
URL context metadata. Tool indicators can arrive on a different
chunk than the final usage_metadata, so callers carry this flag.

Returns:
TokenUsage with standardized usage statistics
Expand All @@ -605,7 +635,10 @@ def extract_gemini_usage_from_chunk(chunk: Any) -> TokenUsage:
if not hasattr(chunk, "usage_metadata") or not chunk.usage_metadata:
return usage

usage_from_metadata = _extract_usage_from_metadata(chunk.usage_metadata)
usage_from_metadata = _extract_usage_from_metadata(
chunk.usage_metadata,
bill_tool_use_tokens=url_context_seen or has_gemini_url_context(chunk),
)

# Merge the usage from metadata with any web search count we found
usage.update(usage_from_metadata)
Expand Down
20 changes: 16 additions & 4 deletions posthog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4415,12 +4415,18 @@ def _get_feature_flag_result(
# Source the gate the same way as has_experiment above; see
# _capture_feature_flag_called_if_needed for why.
minimal_flag_called_events = self._minimal_flag_called_events
# Remotely-evaluated flags carry id and version in the response metadata;
# locally-evaluated flags read them from the definition that produced the value.
local_flag_id: Optional[int] = None
local_flag_version: Optional[int] = None
if flag_was_locally_evaluated:
local_def = (self.feature_flags_by_key or {}).get(key)
local_def = snapshot["flags_by_key"].get(key)
if isinstance(local_def, dict):
has_experiment = _parse_has_experiment(
local_def.get("has_experiment")
)
local_flag_id = local_def.get("id")
local_flag_version = local_def.get("version")
elif isinstance(flag_details, FeatureFlag):
has_experiment = _metadata_has_experiment(flag_details.metadata)
minimal_flag_called_events = remote_minimal_flag_called_events
Expand All @@ -4439,6 +4445,8 @@ def _get_feature_flag_result(
feature_flag_error,
has_experiment,
minimal_flag_called_events,
local_flag_id=local_flag_id,
local_flag_version=local_flag_version,
)

return flag_result
Expand Down Expand Up @@ -4728,6 +4736,8 @@ def _capture_feature_flag_called(
feature_flag_error: Optional[str] = None,
has_experiment: Optional[bool] = None,
minimal_flag_called_events: bool = False,
local_flag_id: Optional[int] = None,
local_flag_version: Optional[int] = None,
):
properties: dict[str, Any] = {
"$feature_flag": key,
Expand All @@ -4752,6 +4762,10 @@ def _capture_feature_flag_called(
properties["$feature_flag_version"] = flag_details.metadata.version
if flag_details.metadata.id:
properties["$feature_flag_id"] = flag_details.metadata.id
if local_flag_version:
properties["$feature_flag_version"] = local_flag_version
if local_flag_id:
properties["$feature_flag_id"] = local_flag_id
if feature_flag_error:
properties["$feature_flag_error"] = feature_flag_error

Expand Down Expand Up @@ -5181,9 +5195,7 @@ def evaluate_flags(
variant=value if isinstance(value, str) else None,
payload=_parse_flag_payload(local_payloads.get(key)),
id=flag_def.get("id"),
# The local-evaluation flag definition does not carry a version field;
# only the remote ``/flags`` response does via ``metadata.version``.
version=None,
version=flag_def.get("version"),
reason="Evaluated locally",
locally_evaluated=True,
has_experiment=_parse_has_experiment(flag_def.get("has_experiment")),
Expand Down
4 changes: 2 additions & 2 deletions posthog/emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,12 +242,12 @@ def _prepare_send(
raise ValueError("max_retries must be a nonnegative integer.")

payload: dict[str, Any] = {
"template": {"id": str(template_uuid)},
"template_id": str(template_uuid),
"to": to,
"message_data": clean(dict(template_data or {})),
}
if distinct_id is not None:
payload["identifiers"] = {"distinct_id": distinct_id}
payload["distinct_id"] = distinct_id
return _PreparedSend(
path=_SEND_PATH,
body=json.dumps(payload, cls=DatetimeSerializer).encode("utf-8"),
Expand Down
29 changes: 24 additions & 5 deletions posthog/feature_flag_evaluations.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,13 @@ def __init__(
unresolved_flags or {}
)

def is_enabled(self, key: str, default_value: bool = False) -> bool:
def is_enabled(
self,
key: str,
default_value: bool = False,
*,
send_feature_flag_events: bool = True,
) -> bool:
"""Return whether the flag is enabled. Fires ``$feature_flag_called`` on the
first access per (distinct_id, flag, value) tuple, deduped via the SDK's cache.

Expand All @@ -105,23 +111,31 @@ def is_enabled(self, key: str, default_value: bool = False) -> bool:
the key was not part of the evaluated set, or the evaluation itself
came back empty (failed ``/flags`` request, quota limit, or no
resolvable ``distinct_id``). Defaults to ``False``.
send_feature_flag_events: Whether this read sends ``$feature_flag_called``.
When ``False``, no event is sent and the dedupe cache is left alone,
but the key still counts as accessed for :meth:`only_accessed`.

A flag that has a value always wins over ``default_value``, including a
disabled flag, which returns ``False`` even when ``default_value=True``.
"""
flag = self._flags.get(key)
self._record_access(key)
self._record_access(key, send_feature_flag_events)
return bool(flag.enabled) if flag else default_value

def get_flag(self, key: str) -> Optional[FlagValue]:
def get_flag(
self, key: str, *, send_feature_flag_events: bool = True
) -> Optional[FlagValue]:
"""Return the flag value. Fires ``$feature_flag_called`` on first access.

Returns the variant string for multivariate flags, ``True`` for enabled flags
without a variant, ``False`` for disabled flags, and ``None`` for flags that
were not returned by the evaluation.

Pass ``send_feature_flag_events=False`` to skip the event for this read, as
with :meth:`is_enabled`.
"""
flag = self._flags.get(key)
self._record_access(key)
self._record_access(key, send_feature_flag_events)
if not flag:
return None
if not flag.enabled:
Expand Down Expand Up @@ -236,9 +250,14 @@ def _clone_with(
accessed=set(self._accessed),
)

def _record_access(self, key: str) -> None:
def _record_access(self, key: str, send_feature_flag_events: bool) -> None:
self._accessed.add(key)

# A suppressed read skips the dedupe cache too, so a later read that sends
# events still reports this flag.
if not send_feature_flag_events:
return

# Empty snapshots (no resolvable distinct_id) are returned by ``evaluate_flags()``
# as a safety fallback. Firing $feature_flag_called for them would emit events
# with an empty distinct_id, polluting analytics β€” short-circuit here.
Expand Down
4 changes: 3 additions & 1 deletion posthog/feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -1264,7 +1264,9 @@ def compute_exact_match(value, override_value):
return matched

if operator in ("regex", "not_regex"):
property_string = "null" if override_value is None else str(override_value)
property_string = _value_to_string(
override_value, UnresolvedFlagReason.MISSING_CONTEXT
)
regex_match = _match_regex(str(value), property_string)
if regex_match is None:
return False
Expand Down
5 changes: 3 additions & 2 deletions posthog/mcp/session_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
So at ``initialize`` we mint that header as a token carrying the session id and
client identity -- any pod can read them back from the header alone.

The token is unsigned: it holds only what the client already self-reports. It is
wire-compatible with the TypeScript SDK (same short keys ``sid``/``cn``/``cv``/``pv``),
The token is unsigned, so clients can change its contents. Use decoded values
for analytics, not authentication or authorization. It is wire-compatible with
the TypeScript SDK (same short keys ``sid``/``cn``/``cv``/``pv``),
so a token minted by one SDK decodes in the other.
"""

Expand Down
3 changes: 3 additions & 0 deletions posthog/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from dataclasses import dataclass
from datetime import date, datetime, timezone
from typing import Any, List, Optional, Tuple, Union, cast
from uuid import UUID

import requests
from requests.adapters import HTTPAdapter
Expand Down Expand Up @@ -460,6 +461,8 @@ class DatetimeSerializer(json.JSONEncoder):
def default(self, obj: Any):
if isinstance(obj, (date, datetime)):
return obj.isoformat()
if isinstance(obj, UUID):
return str(obj)

return json.JSONEncoder.default(self, obj)

Expand Down
Loading
Loading