Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

5.1 KB
Raw Blame
# ruff: noqa: T201
"""Route the reviewer's LLM calls through PostHog's internal Go ai-gateway.

Gated on AI_GATEWAY_URL + AI_GATEWAY_API_KEY; a bad/half-set config falls back to
the direct provider key instead of failing the review. The gateway is slugless, so the
product rides on a header, not the path.
"""

import os
import json
from urllib.parse import urlparse

# aio_ matches the other cutovers; no $ai_ prefix (gateway strips those).
AI_PRODUCT = "aio_stamphog"

REVIEWER_MODEL = "gpt-6.1-sol"
REVIEWER_EFFORT = "low"

# The Claude Agent SDK reviewer stays in the engine as the rollback. The worker selects it with
# STAMPHOG_REVIEWER_ENGINE=claude, which the hosted server forwards into the sandbox.
CLAUDE_REVIEWER_MODEL = "claude-opus-5-5"
CLAUDE_ENGINE = "claude"

# Lives here so the hosted server can read it without the LLM SDKs: its fast refusal summary calls
# the Anthropic Messages API through the same gateway, so it needs a Claude model.
SUMMARY_MODEL = "claude-sonnet-5-5"


def reviewer_engine() -> str:
    """The reviewer engine for this run: "claude" for the rollback reviewer, otherwise "openai"."""
    return CLAUDE_ENGINE if os.environ.get("STAMPHOG_REVIEWER_ENGINE", "").strip() == CLAUDE_ENGINE else "openai"


def analytics_extra_properties() -> dict[str, object]:
    """Extra analytics properties the hosted stamphog server injects, or {}.

    The hosted server sets STAMPHOG_EXTRA_PROPERTIES (a JSON object with runtime/team/run-id
    context) in the sandbox env so hosted events and LLM traces carry its context. The Action
    never sets it, so Action telemetry is unchanged (no prop = action runtime). Anything
    unparseable degrades to {} — telemetry must never fail a review.
    """
    raw = os.environ.get("STAMPHOG_EXTRA_PROPERTIES", "")
    if not raw:
        return {}
    try:
        parsed = json.loads(raw)
    except ValueError:
        return {}
    return parsed if isinstance(parsed, dict) else {}


def _misconfig(url: str, api_key: str) -> str | None:
    if not (url and api_key):
        return "AI_GATEWAY_URL and AI_GATEWAY_API_KEY must be set together"
    parsed = urlparse(url)
    # Require an absolute URL: a schemeless value parses all into .path and would
    # pass the /v1 check, arming a broken base instead of falling back.
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        return "AI_GATEWAY_URL must be an absolute http(s) URL, e.g. https://<host>/v1"
    # A query/fragment survives /v1 stripping and would corrupt the base URL.
    if parsed.query or parsed.fragment:
        return "AI_GATEWAY_URL must not contain a query string or fragment"
    if not parsed.path.rstrip("/").endswith("/v1"):
        return "AI_GATEWAY_URL must include the OpenAI base path, e.g. https://<host>/v1"
    return None


def resolve_gateway_config() -> tuple[str, str] | None:
    """Validated (base_url, phs_api_key), or None to use the direct provider key.

    Trailing /v1 is stripped; the Agent SDK re-appends /v1/messages.
    """
    url = os.environ.get("AI_GATEWAY_URL", "").strip()
    api_key = os.environ.get("AI_GATEWAY_API_KEY", "").strip()
    if not (url or api_key):
        return None
    reason = _misconfig(url, api_key)
    if reason:
        print(f"⚠️  ai-gateway misconfigured, falling back to the direct provider key: {reason}")
        return None
    # Rebuild from parsed components (not raw-string slicing) so nothing past the
    # path can leak into the base; _misconfig already rejected query/fragment.
    parsed = urlparse(url)
    path = parsed.path.rstrip("/")
    if path.endswith("/v1"):
        path = path[: -len("/v1")]
    return f"{parsed.scheme}://{parsed.netloc}{path}", api_key


def _properties_json(properties: dict[str, object]) -> str:
    # Single X-PostHog-Properties JSON blob: the slugless Go gateway merges it onto
    # $ai_generation and ignores per-property x-posthog-property-* headers. None
    # dropped; newlines collapsed so a value can't break the header block.
    clean: dict[str, object] = {}
    for key, value in properties.items():
        if value is None:
            continue
        clean[key] = value.replace("\r", " ").replace("\n", " ") if isinstance(value, str) else value
    if not clean:
        return ""
    return json.dumps(clean, separators=(",", ":"))


def _properties_header(properties: dict[str, object]) -> str:
    value = _properties_json(properties)
    return f"X-PostHog-Properties: {value}" if value else ""


def gateway_env(base_url: str, api_key: str, properties: dict[str, object]) -> dict[str, str]:
    # phs_ secret on both auth vars (SDK sends it as Bearer or x-api-key).
    return {
        "ANTHROPIC_BASE_URL": base_url,
        "ANTHROPIC_AUTH_TOKEN": api_key,
        "ANTHROPIC_API_KEY": api_key,
        "ANTHROPIC_CUSTOM_HEADERS": _properties_header({"ai_product": AI_PRODUCT, **properties}),
    }


def openai_gateway_headers(properties: dict[str, object]) -> dict[str, str]:
    """The analytics header for an OpenAI SDK client, with the same content gateway_env sends."""
    return {"X-PostHog-Properties": _properties_json({"ai_product": AI_PRODUCT, **properties})}