: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(wizard): pin the allowed models and efforts at mint (#96851)
Brandonb14801e00891
diff --git a/docs/internal/wizard-gateway-mint.md b/docs/internal/wizard-gateway-mint.mdnew file mode 100644index 000000000000..2bb98133d10e--- /dev/null+++ b/docs/internal/wizard-gateway-mint.md@@ -0,0 +1,67 @@+# Wizard gateway mint++The wizard CLI does not hold a long-lived model credential. It calls+`POST /api/wizard/gateway_token/` once per run, Django decides what that run may+spend and reach, and Django mints a short-lived scoped token from the Go+ai-gateway. Every limit below is applied at mint time, so a token that is already+issued carries its own ceiling and cannot be widened by a later request.++Code: `posthog/api/wizard/http.py` (the endpoint and its gates),+`posthog/llm/wizard_gateway_token.py` (posture, limits, and the mint call),+`posthog/rate_limit.py` (the mint reservation).++## Mint request++Django posts to `{WIZARD_GATEWAY_URL}/v1/tokens` with+`Authorization: Bearer {WIZARD_GATEWAY_MINT_KEY}`:++| Field | Meaning |+| ----------------- | ------------------------------------------- |+| `cap_usd` | Fixed-point spend ceiling for this token |+| `ttl_seconds` | Token lifetime, clamped to 1800-86400 |+| `product` | Product node, `wizard:<program id>` |+| `obo` | The organization the spend is attributed to |+| `user` | The user the run belongs to |+| `allowed_models` | Models this token may reach |+| `allowed_efforts` | Reasoning efforts this token may declare |++`allowed_models` and `allowed_efforts` come from `WIZARD_MODEL_ALLOWLIST`, which+is the canonical table. The wizard CLI's own model constants follow that table+rather than the other way round. A gateway that predates either field ignores it+and mints an unpinned token, so Django can send both before the gateway enforces+them.++## Limits++A mint resolves an organization's posture first: `new` (younger than 7 days with+no ingested event), `active` (has ingested an event), or `paid`. The posture+picks a tier of `cap_usd`, `max_cap_usd`, `mints_per_week`, and `ttl_seconds`+from `WIZARD_GATEWAY_TIERS`, falling back per field to the in-code floor for that+posture rather than to the flat setting, whose cap is wider than every tier.++The cap resolves in order: the limit-override flag, then the program's own cap+bounded by the posture's ceiling, then the posture's cap, then+`WIZARD_GATEWAY_TOKEN_CAP_USD`. The flat setting applies only when no posture+resolved. Every value passes a contract check bounded by `_MAX_CAP_USD`.++Mints are metered per user, per program, per week. The reservation is atomic and+charged immediately before the mint, so a run refused by an earlier gate spends+nothing, and a failure that proves no token was issued returns the slot.++A value rejected as out of contract is logged and counted on+`posthog_wizard_gateway_config_rejects_total{field}`, because the mint otherwise+degrades toward a floor with nothing to alert on.++## Refusals++The endpoint answers one outcome per request, counted on+`posthog_wizard_gateway_token_requests_total{outcome}`: `unconfigured`,+`invalid_token`, `not_wizard_app`, `scope_missing`, `team_ambiguous`,+`team_missing`, `unauthorized`, `blocked`, `not_rolled_out`, `program_unknown`,+`throttled`, `mint_failed`, or `minted`.++Refusals that an older CLI absorbed by falling back to the legacy gateway+(`unconfigured`, `not_rolled_out`, `program_unknown`) answer 403 with a reason+only to a client that sent `reads_refusal_reason: true`. Any other client still+receives 404, which is the signal its fallback depends on. That branch retires+once those builds are gone.diff --git a/posthog/api/wizard/http.py b/posthog/api/wizard/http.pyindex 88eb3af10bfa..0251ad40f0e7 100644--- a/posthog/api/wizard/http.py+++ b/posthog/api/wizard/http.py@@ -90,9 +90,9 @@ WIZARD_EMAIL_UNVERIFIED_DETAIL = (WIZARD_GATEWAY_TOKEN_REQUESTS_TOTAL = Counter("posthog_wizard_gateway_token_requests_total",- "Wizard gateway-token mint requests, by outcome (minted/unconfigured/not_wizard_app/"- "scope_missing/team_ambiguous/team_missing/unauthorized/blocked/program_unknown/"- "not_rolled_out/mint_failed)",+ "Wizard gateway-token mint requests, by outcome (minted/unconfigured/invalid_token/"+ "not_wizard_app/scope_missing/team_ambiguous/team_missing/unauthorized/blocked/"+ "program_unknown/not_rolled_out/throttled/mint_failed)",labelnames=["outcome"],)diff --git a/posthog/llm/test_wizard_gateway_token.py b/posthog/llm/test_wizard_gateway_token.pyindex ce2546fb91f1..dcb8dd58aadb 100644--- a/posthog/llm/test_wizard_gateway_token.py+++ b/posthog/llm/test_wizard_gateway_token.py@@ -12,11 +12,17 @@ import requestsfrom posthog.llm.wizard_gateway_token import (_TIER_FLOORS,NO_OVERRIDE,+ WIZARD_DECLARABLE_EFFORTS,+ WIZARD_EFFORT_LEVELS,WIZARD_GATEWAY_CONFIG_REJECTS,+ WIZARD_MODEL_ALLOWLIST,WizardGatewayMintError,WizardLimitOverride,WizardTierLimits,+ allowed_efforts,+ allowed_models,mint_wizard_gateway_token,+ normalize_model,parse_limit_override,wizard_gateway_base_url,wizard_gateway_configured,@@ -72,10 +78,44 @@ class TestMintWizardGatewayToken:"product": "wizard","obo": "org_1","user": "user_1",+ # Derived: this case pins that the mint carries the pins, not which+ # models are on the table. TestWizardModelAllowlist owns the contents.+ "allowed_models": allowed_models(),+ "allowed_efforts": allowed_efforts(),}assert post.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_wizard_secret"}assert post.call_args.kwargs["timeout"] > 0++class TestWizardModelAllowlist:+ def test_the_allowlist_is_never_empty(self):+ # The gateway refuses an explicit [] at mint, so an empty table would+ # refuse every wizard run rather than pin nothing.+ assert allowed_models()+ assert allowed_efforts()+ assert all(efforts for efforts in WIZARD_MODEL_ALLOWLIST.values())++ def test_models_are_sent_lowercased_and_stripped_of_the_openai_prefix(self):+ table = {"OpenAI/GPT-5.6-Luna": ("low",), "gpt-5.6-luna": ("medium",), " Claude-Sonnet-5 ": ("none",)}+ with patch("posthog.llm.wizard_gateway_token.WIZARD_MODEL_ALLOWLIST", table):+ assert allowed_models() == ["gpt-5.6-luna", "claude-sonnet-5"]++ def test_efforts_cover_what_the_cli_can_declare_not_what_the_table_measured(self):+ # A flag payload or a remote prompt can name any declarable level with+ # no deploy here, so a pin built from the table would refuse those runs.+ table = {"a": ("high", "none")}+ with patch("posthog.llm.wizard_gateway_token.WIZARD_MODEL_ALLOWLIST", table):+ assert allowed_efforts() == ["none", "minimal", "low", "medium", "high", "xhigh"]++ def test_the_effort_pin_withholds_the_level_the_cli_cannot_send(self):+ assert "max" not in allowed_efforts()+ assert set(WIZARD_DECLARABLE_EFFORTS) <= set(WIZARD_EFFORT_LEVELS)++ def test_every_effort_in_the_table_is_gateway_vocabulary(self):+ for model, efforts in WIZARD_MODEL_ALLOWLIST.items():+ assert set(efforts) <= set(WIZARD_EFFORT_LEVELS), model+ assert normalize_model(model) == model, model+@override_settings(WIZARD_GATEWAY_URL="https://ai-gateway.us.posthog.com/v1/")def test_version_suffixed_setting_does_not_double_up(self):# The setting may carry /v1; both the mint path and the base handed to thediff --git a/posthog/llm/wizard_gateway_token.py b/posthog/llm/wizard_gateway_token.pyindex cacad86cef02..7083cf1b3e96 100644--- a/posthog/llm/wizard_gateway_token.py+++ b/posthog/llm/wizard_gateway_token.py@@ -47,6 +47,51 @@ _CAP_QUANTUM = Decimal("0.000001")WIZARD_PRODUCT = "wizard"+# The gateway's effort vocabulary, in order; the pin sent at mint is a subset.+WIZARD_EFFORT_LEVELS: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh", "max")++# What the CLI can ask for, not what it was measured asking for: a flag payload+# or a remote prompt's frontmatter can name any of these with no deploy here,+# while widening this needs one. "none" is a call with no effort parameter,+# which is also the CLI's "off". "max" is absent because the CLI cannot send it,+# so the pin refuses it and the escalation stays out of reach.+WIZARD_DECLARABLE_EFFORTS: tuple[str, ...] = ("none", "minimal", "low", "medium", "high", "xhigh")++# Every (model, effort) pair the wizard CLI dispatches; "none" is a request with+# no effort parameter. Wizard-wide rather than per program: the CLI picks models+# per switchboard flag. The keys mirror the CLI's own model constants (wizard+# src/lib/constants.ts, the *_MODEL exports), so widen here when one is added.+WIZARD_MODEL_ALLOWLIST: dict[str, tuple[str, ...]] = {+ "claude-sonnet-5": ("none", "high"),+ "claude-haiku-4-5": ("none",),+ "gpt-5.6-luna": ("low",),+ "gpt-5.6-sol": ("medium",),+ "gpt-5.6-terra": ("low", "medium", "high"),+}++# pi sends the provider-prefixed id for OpenAI models; the gateway pins the bare model.+_STRIPPED_MODEL_PREFIXES = ("openai/",)+++def normalize_model(model: str) -> str:+ normalized = model.strip().lower()+ for prefix in _STRIPPED_MODEL_PREFIXES:+ if normalized.startswith(prefix):+ return normalized[len(prefix) :]+ return normalized+++def allowed_models() -> list[str]:+ """The allowlist's models as the gateway spells them, deduplicated, in table order."""+ return list(dict.fromkeys(normalize_model(model) for model in WIZARD_MODEL_ALLOWLIST))+++def allowed_efforts() -> list[str]:+ """Every effort the CLI can declare, in vocabulary order. Flat per token: a+ per-model pin is a gateway follow-up."""+ return [level for level in WIZARD_EFFORT_LEVELS if level in WIZARD_DECLARABLE_EFFORTS]++# An organization's standing at mint time, which picks its tier of limits.WizardPosture = Literal["new", "active", "paid"]_NEW_ORGANIZATION_AGE = timedelta(days=7)@@ -361,6 +406,9 @@ def mint_wizard_gateway_token("product": product,"obo": obo,"user": user,+ # A gateway that predates either field ignores it and mints unpinned.+ "allowed_models": allowed_models(),+ "allowed_efforts": allowed_efforts(),}try:response = requests.post(