# Model gateways Pi can route model calls through an authenticated gateway instead of holding provider keys. Set `MODEL_GATEWAY_URL`, `MODEL_GATEWAY_API_KEY`, and `MODEL_GATEWAY_API_KEY_HEADER`. The key stays server-side. No model list is required. Gateway requests also say which work they serve, so the gateway can attribute spend: `x-qm-session-id` (the session the call works for, including helper calls), `x-qm-actor` (a keyed hash of the principal the work is for, the one QM's budget charges), `x-qm-scope` (the scope the work runs in, with a personal scope's person replaced by the same hash), `x-qm-origin` (`conversation`, `cron`, `webhook`, `monitor`, `loop` or `swarm`, inherited by subagents from their parent session) and `x-qm-purpose` (`turn`, `detect`, `compaction`, `title`, `judge`, `ambient_judge`, `approval_summary`, `security_screen`, `ack_emoji`, `memory_capture`, `memory_classification`, `embedding`, `decision`, `browser`, `probe` or `sandbox`). A value is sent only when it is known and is 1 to 256 printable ASCII characters without spaces. Requests sent directly to a provider with a user's or the organization's own key never carry them, and neither does model discovery. Pi's own `x-session-affinity` cache hint is no substitute: helper calls give it a throwaway session id, and calls made outside a Pi agent session, such as compaction, embeddings and decisions, never send it. The hash is the same one sandbox code's requests carry as their end user: the first 32 hex characters of an HMAC-SHA256 of the principal id, keyed with `CAPABILITY_SECRET` (or `CORE_SIGNING_SECRET` when that is unset), so one person has one value on every path and the gateway never receives an identity. Without either secret, neither the actor nor a personal scope is sent. To find who a hash belongs to, an org admin reads the roster (`GET /v1/admin/users`, the admin Users page's data): each person carries `gatewayActor`, the hash the gateway receives for them. Channel, group and project scope ids are sent as they are, so a gateway must not forward client `x-` headers upstream. `MODEL_GATEWAY_API_KEY_HEADER` cannot be any of these header names, in any letter case. QM discovers models using authenticated `GET /v1/models` and `GET /model_group/info`, the end-user metadata endpoint implemented by LiteLLM. A base URL ending in `/v1` is supported; both endpoints retain any preceding path prefix. Discovery uses the same key as inference, rejects redirects, and ignores upstream credential and endpoint fields. Only models listed by both endpoints, marked as chat models with tool support, and carrying valid context, output and pricing metadata are offered. Discovered IDs are namespaced as `gateway/`. Groups whose metadata identifies only Anthropic providers use native Messages, preserving signed thinking blocks across tool calls. Groups whose providers are exclusively OpenAI or Azure use Responses, including native file inputs. Other groups use OpenAI-compatible streaming chat completions. Reasoning controls follow the group's `supports_reasoning` flag on every protocol. Chat-completion groups send `reasoning_effort` when `supported_openai_params` lists it, and a group that advertises `supported_reasoning_efforts` receives only those levels: a requested level it lacks moves to the next higher level it takes, or to the highest below it when none is higher. The gateway owns provider translation and group capabilities. QM selects the protocol from provider metadata, never model names. Gateways must expose `/v1/messages` for Anthropic groups and `/v1/responses` for OpenAI/Azure groups. PDF inputs on chat-completion routes require vision capability and a provider set consisting only of Anthropic, OpenAI, Azure, Gemini or Vertex. Unknown or mixed unsupported provider groups use bounded text extraction. Availability refreshes on demand every five minutes and before inference when expired. Successful refreshes replace the catalog, including an empty catalog. After discovery has succeeded, a failed refresh disables gateway routes until recovery without interrupting independent direct providers, with retries after thirty seconds. In-flight requests are not cancelled; the gateway still enforces its key permissions on every call. Retired selections remain in conversation history but cannot issue a new request through a different provider. Each model id has one route. `gateway//` ids always use the gateway, and `custom//` ids use that custom provider's key. A plain id such as `claude-opus-5-5` that the gateway maps uses the gateway until an admin saves the organization's own key for that provider (Anthropic, OpenAI or OpenRouter), then it uses that key; memory embeddings follow the same rule. Saving the key also moves the organization's base model and its fallback, cron, subagent and app-edit models off the gateway when they still use it, to that provider's default model. The admin sees what moved. Moving back is an admin choice: pick a gateway model as the default again. Turns on a personal AI account don't give sandbox code gateway access. Deployment environment keys do not change routing. `MODEL_GATEWAY_MODELS` is optional and accepts the existing `local-id=upstream-id` pairs. These provide compatibility aliases using QM's existing native model definitions; they do not limit discovered models. After discovery succeeds, aliases are usable only while their upstream IDs remain advertised. Gateways without the discovery endpoints can continue to use explicit mappings. Before the first successful discovery, failures leave those configured routes available. This compatibility fallback never restores a route removed by a successful discovery. For LiteLLM deployments, allow the two authenticated GET endpoints alongside inference paths. Do not expose administrative `/model/info` or key-management routes to enable discovery. Gateways implementing only the OpenAI model-list endpoint can use explicit mappings or implement the metadata contract below. The metadata endpoint returns `{"data": [...]}` with one object per model group. QM uses `model_group`, `mode`, `supports_function_calling`, `max_input_tokens`, `max_output_tokens`, `input_cost_per_token`, and `output_cost_per_token`. Optional fields include `providers`, `supports_vision`, `supports_reasoning`, `supports_adaptive_thinking`, `supported_openai_params`, `supported_reasoning_efforts`, `cache_read_input_token_cost`, and `cache_creation_input_token_cost`. Prices are per token and converted to per-million-token prices for QM. Missing cache prices use the input rate. Input capacity is used conservatively as the context budget; output capacity must be smaller. LiteLLM group metadata may combine capabilities and maximum limits from multiple deployments. It is a gateway contract, not a guarantee that every backing deployment has identical capabilities. ## Browser agent The browse skill follows the user's saved AI access and default model. Company access uses the configured model gateway, or the deployment's default provider credentials when no gateway is configured; ChatGPT access uses the user's connected OpenAI account, including refreshed subscription access; Claude access supports API keys. Claude subscription access is unavailable for the inner browser agent and returns an actionable error. No account silently falls back to another. Kernel, Anchor, Browserbase and Browser Use still use their own credentials for browser sessions. Core gives internal, non-strict turns a one-hour capability bound to the account, model and conversation scope. The sandbox sends OpenAI-compatible, non-streaming chat completions to `/v1/browser-model/chat/completions`; core reloads the saved selection and credentials for each request. Changing the account or model requires a fresh turn. Credentials stay on core. Without a gateway, company inference reloads the same provider credentials as normal agent inference, including administrator changes and configured provider endpoints. No separate browser model key is needed. Missing credentials fail closed. Personal inference uses native provider transports, bypassing organization endpoint overrides, and converts structured browser responses and screenshots through the existing model runtime. Company browser inference uses the same gateway key permissions and budgets as other company model calls. The selected model must be in the gateway catalog or configured aliases. Private gateways need no public listener. The endpoint accepts up to 16 MiB for screenshot history, rejects provider overrides, and rechecks scope membership, strict posture and gateway availability. Gateway budget exhaustion is returned as HTTP 429; missing or retired models fail closed. The managed browse runner needs browser-use 0.12.9 with `ChatOpenAI.default_headers` support. It never requests separate browser model credentials or falls back to them on account or gateway errors. ## Sandbox code Code the agent runs in its sandbox reaches the company's models through core instead of holding a provider key. Internal turns outside strict posture get `MODEL_GATEWAY_URL`, which points at core's `/v1/sandbox-model` prefix, and `MODEL_GATEWAY_TOKEN`, a capability token bound to the turn's actor and conversation scope that expires with the turn's other sandbox tokens. The agent is told both are set. Scheduled and other background turns get them too, without a grant: the token authorizes model inference and nothing else. Strict posture issues neither. No provider or gateway key enters the sandbox. `GET /v1/models` lists what the company's turns can use, by the same IDs the model picker uses, with `owned_by` saying who bills each: `gateway` or `organization`. A model the gateway names is forwarded to it as described below. Every other listed model carries `endpoints: ["/v1/chat/completions"]`: core resolves it with the same model route a turn would use (a saved provider key, a deployment key, a custom provider, a company subscription, or a gateway model the gateway does not name directly) and translates OpenAI chat completions (text, inline data-URL images passed to the provider as sent, function tools with `tool_choice` and `parallel_tool_calls`, the assistant `tool_calls` and `tool` messages that carry a tool loop, and an optional `json_schema` response format; no streaming) into the route's protocol through the same code the browser model uses, returning a non-streamed completion whose message carries any `tool_calls` the model made. Other paths and streaming are refused for these with a 400 that says so, and provider errors come back with their text. Calls billed to the organization are charged to the actor's QM budget, since no gateway meters them. For gateway models, core exposes only `GET /v1/models` and `POST` to `/v1/chat/completions`, `/v1/messages`, `/v1/responses`, and `/v1/embeddings`, with no query parameters. It accepts the token as `Authorization: Bearer`, `x-api-key`, or `x-agent-capability`, only on these routes, and passes on `accept`, `content-type`, `anthropic-version` and `anthropic-beta`. Every `POST` body must be a JSON object naming a listed string `model`; core rewrites it to the gateway's upstream ID and replaces the end user (`user`, or `metadata.user_id` for `/v1/messages`) with a keyed hash of the actor, so the gateway can attribute spend without receiving identities and the client cannot name someone else. Requests also carry the request context headers above with purpose `sandbox`, and `x-qm-actor` is that same hash. Core adds the gateway key and streams the response back; a client disconnect cancels the upstream call. Strict posture and an exhausted per-actor QM budget refuse requests; the budget is checked but not charged. Upstream 401 and 403 responses are reported as 502; other errors keep their status and `retry-after`, with the gateway key redacted. In addition to core's route and model allowlists, give the gateway a key scoped to inference on the offered models, never a master or admin key, and keep client-side credentials and endpoint overrides disabled on it (LiteLLM's default). ## Ultrafast Pi offers `gpt-6.2-astra-ultrafast`, `gpt-6.2-sol-ultrafast`, `gpt-6-astra-ultrafast` and `gpt-6.1-sol-ultrafast`, each labeled **Ultrafast (6× cost)**. These are QM selection identifiers: requests use the corresponding base model (`gpt-6.2-astra`, `gpt-6.2-sol`, `gpt-6-astra` or `gpt-6.1-sol`) with `service_tier: "ultrafast"` through the Responses API. Ultrafast has its own pricing card, including cached input, cache writes, and long-context rates. OpenAI bills each call at the tier its response's `service_tier` reports, which can be lower than the one requested, and QM prices calls the same way with pi-ai's tier rates (flex ½×, priority and fast 2×). An Ultrafast request served at another tier is priced from the base model's card at that tier, and a Fast request whose response reports no tier is priced at the Fast rate. Use an OpenAI API key or explicitly map the Ultrafast model ID to your gateway's corresponding base-model group in `MODEL_GATEWAY_MODELS`. The gateway must support Responses and forward `service_tier`. The choice is supported in Pi only, and is unavailable with ChatGPT subscription authentication. It is never selected as the default merely by enabling Fast. OpenAI supports Ultrafast for Astra 6.2, Sol 6.2, Astra and Sol 6.1 with separate rate limits. QM prices the 6.2 variants at OpenAI's 6× list rate; OpenAI bills them at 3× through February 28, 2027, so recorded costs for those calls are double the bill until then. See [Ultrafast availability](https://developers.openai.com/api/docs/guides/ultrafast-mode) and [pricing](https://developers.openai.com/api/docs/pricing?latest-pricing=ultrafast). In the web picker, select Astra 6.2, Sol 6.2, Astra or Sol 6.1 and use the Ultrafast switch. The picker shows a distinct active badge and the 6× cost before enabling it. Fast and Ultrafast are mutually exclusive, and both speeds share one preset per base model. The internal model IDs above preserve routing, authorization, pricing, and saved selections.