-
Notifications
You must be signed in to change notification settings - Fork 70
feat(ai): warn when AI wrapper is pointed at the PostHog AI Gateway #658
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
richardsolomou
wants to merge
2
commits into
main
Choose a base branch
from
posthog-code/warn-ai-gateway
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog: minor | ||
| --- | ||
|
|
||
| Warn when an AI wrapper's `base_url` points at the PostHog AI Gateway. The gateway emits its own `$ai_generation`, so each call would be captured (and billed) twice. The wrapper only warns and never drops the event. Detection covers the wrapper funnels (OpenAI, Anthropic, LangChain) and the OTel span path. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| # Warn when a wrapper's base_url points at the PostHog AI Gateway: the gateway | ||
| # emits its own $ai_generation, so each call would be captured (and, for billable | ||
| # products, billed) twice. We only warn — the wrapper's event carries data the | ||
| # gateway never sees (groups, custom properties, trace hierarchy). | ||
|
|
||
| import logging | ||
| import re | ||
| from typing import Any, Mapping, Optional | ||
| from urllib.parse import urlparse | ||
|
|
||
| log = logging.getLogger("posthog") | ||
|
|
||
| # Keep in sync with the gateway's deployed hosts (see services/llm-gateway in the | ||
| # main repo). gateway.us.posthog.com is live today; the rest are listed ahead of | ||
| # any traffic moving to them. | ||
| POSTHOG_AI_GATEWAY_HOSTS = [ | ||
| "gateway.posthog.com", | ||
| "gateway.us.posthog.com", | ||
| "gateway.eu.posthog.com", | ||
| "ai-gateway.us.posthog.com", | ||
| "ai-gateway.eu.posthog.com", | ||
| ] | ||
|
|
||
| # Swap for the dedicated AI Gateway page once it ships. | ||
| _GATEWAY_DOCS_URL = "https://posthog.com/docs/ai-observability" | ||
|
|
||
| _SCHEME_RE = re.compile(r"^[a-z][a-z0-9+.-]*://", re.IGNORECASE) | ||
|
|
||
| # OTel spans don't pass through the capture funnels, so detect the gateway from | ||
| # the span's host/URL attributes instead. These follow the GenAI / HTTP semantic | ||
| # conventions: `server.address` is a bare host, `url.full` a full URL, both of | ||
| # which is_posthog_ai_gateway_url accepts. | ||
| _OTEL_GATEWAY_URL_ATTRIBUTES = ("server.address", "url.full") | ||
|
|
||
|
|
||
| def _extract_host(base_url: str) -> Optional[str]: | ||
| try: | ||
| # Tolerate bare hosts that omit a scheme, e.g. "gateway.us.posthog.com/v1". | ||
| url = base_url if _SCHEME_RE.match(base_url) else f"https://{base_url}" | ||
| host = urlparse(url).hostname | ||
| return host.lower() if host else None | ||
| except Exception: | ||
| return None | ||
|
|
||
|
|
||
| def is_posthog_ai_gateway_url(base_url: Any) -> bool: | ||
| """Return True if base_url points at a known PostHog AI Gateway host.""" | ||
| if not base_url: | ||
| return False | ||
| host = _extract_host(str(base_url)) | ||
| return host is not None and host in POSTHOG_AI_GATEWAY_HOSTS | ||
|
|
||
|
|
||
| def warn_if_posthog_ai_gateway(base_url: Any) -> None: | ||
| """ | ||
| Warn when an AI wrapper is pointed at the PostHog AI Gateway. | ||
|
|
||
| Warns on every gateway call by design: the misconfiguration is impossible to | ||
| miss that way, and a doubled bill is worse than noisy logs. We only warn and | ||
| never drop the event, because the wrapper event carries data the gateway | ||
| never sees (groups, custom properties, trace hierarchy). | ||
| """ | ||
| if not is_posthog_ai_gateway_url(base_url): | ||
| return | ||
| log.warning( | ||
| "[PostHog] The PostHog AI wrapper is pointed at the PostHog AI Gateway. " | ||
| "Both capture $ai_generation, so every call is double-counted and " | ||
| "double-billed. Use one or the other — see %s.", | ||
| _GATEWAY_DOCS_URL, | ||
| ) | ||
|
|
||
|
|
||
| def warn_if_posthog_ai_gateway_otel_attributes( | ||
| attributes: Optional[Mapping[str, Any]], | ||
| ) -> None: | ||
| """Warn at most once per span when its host/URL attributes point at the gateway.""" | ||
| if not attributes: | ||
| return | ||
| for key in _OTEL_GATEWAY_URL_ATTRIBUTES: | ||
| value = attributes.get(key) | ||
| if isinstance(value, str) and is_posthog_ai_gateway_url(value): | ||
| warn_if_posthog_ai_gateway(value) | ||
| return | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import logging | ||
|
|
||
| import pytest | ||
|
|
||
| from posthog.ai.gateway import ( | ||
| POSTHOG_AI_GATEWAY_HOSTS, | ||
| is_posthog_ai_gateway_url, | ||
| warn_if_posthog_ai_gateway, | ||
| warn_if_posthog_ai_gateway_otel_attributes, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("host", POSTHOG_AI_GATEWAY_HOSTS) | ||
| def test_detects_every_gateway_host(host): | ||
| assert is_posthog_ai_gateway_url(f"https://{host}/v1") is True | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "url", | ||
| [ | ||
| "https://gateway.us.posthog.com/v1", | ||
| "https://gateway.us.posthog.com/signals/v1", | ||
| "https://gateway.us.posthog.com/anthropic", | ||
| ], | ||
| ) | ||
| def test_detects_live_host_with_route_prefix(url): | ||
| assert is_posthog_ai_gateway_url(url) is True | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "label,url", | ||
| [ | ||
| ("http scheme", "http://gateway.us.posthog.com/v1"), | ||
| ("uppercase host", "https://GATEWAY.US.POSTHOG.COM/v1"), | ||
| ("missing scheme", "gateway.us.posthog.com/v1"), | ||
| ("port", "http://gateway.us.posthog.com:443/anthropic"), | ||
| ], | ||
| ) | ||
| def test_matches_gateway_host_variants(label, url): | ||
| assert is_posthog_ai_gateway_url(url) is True | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "label,url", | ||
| [ | ||
| ("ingestion host", "https://us.i.posthog.com"), | ||
| ("app host", "https://eu.posthog.com"), | ||
| ("openai", "https://api.openai.com/v1"), | ||
| ("anthropic", "https://api.anthropic.com"), | ||
| ("look-alike domain", "https://gateway.us.posthog.com.evil.example/v1"), | ||
| ], | ||
| ) | ||
| def test_does_not_match_non_gateway_url(label, url): | ||
| assert is_posthog_ai_gateway_url(url) is False | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "label,value", | ||
| [ | ||
| ("empty string", ""), | ||
| ("none", None), | ||
| ("malformed", "::::not a url"), | ||
| ], | ||
| ) | ||
| def test_does_not_match_empty_or_malformed(label, value): | ||
| assert is_posthog_ai_gateway_url(value) is False | ||
|
|
||
|
|
||
| def _warnings(caplog): | ||
| return [r for r in caplog.records if r.levelno == logging.WARNING] | ||
|
|
||
|
|
||
| def test_warns_with_double_counting_message(caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| warn_if_posthog_ai_gateway("https://gateway.us.posthog.com/v1") | ||
|
|
||
| warnings = _warnings(caplog) | ||
| assert len(warnings) == 1 | ||
| message = warnings[0].getMessage() | ||
| assert "[PostHog]" in message | ||
| assert "PostHog AI Gateway" in message | ||
| assert "$ai_generation" in message | ||
| assert "double-counted and double-billed" in message | ||
| assert "https://posthog.com/docs/ai-observability" in message | ||
|
|
||
|
|
||
| def test_warns_on_every_gateway_call(caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| for _ in range(5): | ||
| warn_if_posthog_ai_gateway("https://gateway.us.posthog.com/v1") | ||
|
|
||
| assert len(_warnings(caplog)) == 5 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "base_url", | ||
| ["https://api.openai.com/v1", None, ""], | ||
| ) | ||
| def test_does_not_warn_for_non_gateway(base_url, caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| warn_if_posthog_ai_gateway(base_url) | ||
|
|
||
| assert _warnings(caplog) == [] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "label,attributes", | ||
| [ | ||
| ("server.address bare host", {"server.address": "gateway.us.posthog.com"}), | ||
| ( | ||
| "url.full full URL", | ||
| {"url.full": "https://gateway.us.posthog.com/v1/chat/completions"}, | ||
| ), | ||
| ], | ||
| ) | ||
| def test_otel_attributes_warn_when_gateway_detected(label, attributes, caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| warn_if_posthog_ai_gateway_otel_attributes(attributes) | ||
|
|
||
| assert len(_warnings(caplog)) == 1 | ||
| assert "PostHog AI Gateway" in _warnings(caplog)[0].getMessage() | ||
|
|
||
|
|
||
| def test_otel_attributes_warn_at_most_once_per_span(caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| warn_if_posthog_ai_gateway_otel_attributes( | ||
| { | ||
| "server.address": "gateway.us.posthog.com", | ||
| "url.full": "https://gateway.us.posthog.com/v1", | ||
| } | ||
| ) | ||
|
|
||
| assert len(_warnings(caplog)) == 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "label,attributes", | ||
| [ | ||
| ("none", None), | ||
| ("empty", {}), | ||
| ("non-gateway", {"server.address": "api.openai.com"}), | ||
| ], | ||
| ) | ||
| def test_otel_attributes_silent_for_non_gateway(label, attributes, caplog): | ||
| with caplog.at_level(logging.WARNING, logger="posthog"): | ||
| warn_if_posthog_ai_gateway_otel_attributes(attributes) | ||
|
|
||
| assert _warnings(caplog) == [] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.