# Agent Keys Source: https://docs.flexinference.com/agent-keys Most tools build their own request body and give you nowhere to put `start_within`. An agent key holds the deadline itself, so every request the tool makes routes by it. ## Create the key 1. Open the [dashboard](https://www.flexinference.com/dashboard) and go to **API**, then **FlexInference keys** 2. Press **Create agent key** 3. Pick the deadline 4. Turn on **Store traces** if you want this key's requests kept in your logs 5. Press create, then copy the secret. The dashboard shows it once * **Flex race** tries the cheaper tier for a duration you set, from 5 seconds to 10 minutes, then falls back to standard. It costs less and starts later, so a tool you sit and watch usually wants a tier instead. * **Standard** serves the normal tier. It works with every model and every route. * **Priority** starts sooner and costs more. Worth it when a person waits on the answer. * **Auto** lets the provider pick. Not available on Gemini models. **Priority** and **Auto** need a BYOK organization. [Managed Keys](/billing#managed-keys) doesn't offer either tier, so creation refuses them with `400 invalid_key_defaults`. A key can also carry an [upstream retries](/upstream-retries) policy. Leave it unset unless you have a reason, because most tools retry on their own and the two stack. **Store traces** puts [`trace_storage: true`](/trace-storage) on every request through the key, so the request and response show up in your dashboard logs. It only works on managed serving. The toggle is off until you turn it on, and a request that sets `trace_storage` itself still wins. ## The request always wins We fill a stored field into any request that arrives without it. We never replace a value the request sent, even a wrong one, so an explicit bad `start_within` still fails. Every response we filled in carries `x-flexinference-defaults-applied`. Most tools don't show response headers, so read the request in the dashboard under **Logs** to confirm the key applied. ## A key duration falls back instead of failing A duration in a request body fails on a model that can't race. The same duration on a key falls back to its tier instead, so the key always has an answer. That fallback is also why a key duration never races Claude's cheaper tier. Send the duration in the request body when you want that race. ## Edit or revoke Edit the deadline on the key row. Live traffic picks it up within seconds, and you keep the same key. Revoking a key clears its defaults with it. ## Per-tool guides * [Codex](/coding-agents) * [Cursor](/cursor) * [Claude Code](/claude-code) * [Claude Cowork](/claude-cowork) * [OpenCode](/opencode) * [OpenWork](/openwork) * [OpenScience](/openscience) * [OpenWorker](/openworker) * [OpenClaw](/openclaw) ## Troubleshooting These come up in every tool, so they live here once. Each tool's page keeps only what's specific to it, and [errors](/errors) carries every refusal we return. **[`400 missing_start_within`](/errors#missing_start_within) on every request.** The key came from **Create key** rather than **Create agent key**, so it holds no deadline. Create an agent key and swap it in. A key made without defaults can't gain them later. **[`400 unsupported_parameter`](/errors#unsupported_parameter).** The tool sent a Chat Completions parameter only OpenAI serves, on a model OpenAI doesn't run. The full list is `seed`, `stop`, `presence_penalty`, `frequency_penalty`, `logit_bias`, `logprobs`, `top_logprobs`, `prediction`, `audio`, `modalities`, and `web_search_options`. Switch to a `gpt-*` model or remove the parameter. **[`400 key_default_not_applicable`](/errors#key_default_not_applicable).** Your key holds a duration and the request sent something a race can't go with: one of those parameters, or a pinned cloud route. Edit the key to a tier, or remove the conflict from the request. **[`400 flex_unsupported_for_anthropic`](/errors#flex_unsupported_for_anthropic).** A duration in the tool's config reached a `claude-*` model on your own Anthropic key, and that race takes managed keys. Remove the duration from the config and let the key hold the deadline, which falls back instead. **Every request spends a full retry budget.** The tool retries on its own, and a key retry policy stacks with it. Leave `retry` off a key an agent uses. **The cursor sits waiting.** **Flex race** costs less and starts later, which you feel in an interactive loop. Edit the key to **Priority** or **Standard**. The next request picks it up with no restart. **Does the tool need to know it holds an agent key?** No. It authenticates the same way as any key, and every key starts with `flex_live_`. **Can one key serve a tool and my own code?** Yes. Your code sends `start_within` and wins. The tool sends nothing and takes the key's deadline. **What does this cost?** Nothing from us on your own provider key, and your provider bills the tokens. On [Managed Keys](/billing#managed-keys) each request draws your balance. # Authentication Source: https://docs.flexinference.com/authentication Two kinds of key matter. Your FlexInference key says who you are. Your provider keys pay for the tokens. ## Your FlexInference key Create it in the [dashboard](https://www.flexinference.com/dashboard). It starts with `flex_live_` and you see it once, so copy it then. Send it as a bearer token. ```bash theme={null} curl https://api.flexinference.com/v1/responses \ -H "Authorization: Bearer flex_live_..." \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5-nano", "input": "ping", "start_within": "default" }' ``` A malformed or unknown key returns `401 invalid_api_key`. A revoked key returns `401 revoked_api_key`, so you can tell the two apart. ## What a key can carry A plain key holds your identity and nothing else, so each request sends `start_within` itself. An agent key also holds a duration, plus a retry policy when you ask for one. We fill in whichever field the request left out, and a value in the body always beats the key. The response header `x-flexinference-defaults-applied` lists what the key filled in. Edit those defaults in the dashboard and live traffic picks them up within seconds. You keep the same key. Revoking a key clears its defaults with it. ## Your provider keys We don't resell inference. Add each provider key once in the dashboard, and your provider bills you for the tokens. * `openai` takes an OpenAI key, `sk-` prefix. * `google` takes a Gemini API key from Google AI Studio. * `anthropic` takes an Anthropic key, `sk-ant-` prefix. * `vertex` takes a Vertex express key, `AQ.` prefix. * `bedrock` takes a Bedrock inference key, `ABSK` prefix, plus a region. * `foundry` takes an Azure AI Foundry key, plus its resource name. * `cloudflare` takes a Workers AI token, plus your account id. We store every provider key encrypted, never log one, and never return one. You never send one on a request. Every route you name in a [backup chain](/backup-providers) needs its own key. We refuse a missing key before any upstream call, and we never fall through to the next route. Rather not paste provider keys at all? [Managed Keys](/billing#managed-keys) serves on ours and your balance pays. # Backup Providers Source: https://docs.flexinference.com/backup-providers You can give us an ordered list of routes for your model with the `provider` array. The first route is the primary and the only one that can run a Flex Race. The rest are backups for the same model. We try them in order when a route fails. ```json theme={null} { "start_within": "default", "provider": ["anthropic", "bedrock"] } ``` Leave the array out and we use the model's own direct route. * `gpt-*` and `o*` run on `openai`, with `foundry` on Azure AI Foundry as the backup. * `gemini-*` runs on `google`, with `vertex` on Google Vertex AI as the backup. * `claude-*` runs on `anthropic`, with `bedrock` on Amazon Bedrock as the backup. * The open-source families run on `cloudflare` or `deepinfra`. Most run on one of them. Two run on both. A backup changes the route and nothing else. Your model and your tier stay the same, and a backup route always runs a standard call. We move to a backup on a `429`, a `5xx`, a connection error, or a timeout, and only before the response commits. A chain that used up its routes on faults returns `502 all_routes_failed`. When the last failure was a `429`, you get that `429` back instead. Every route you name needs its own key. We refuse a missing key before any upstream call, and we never fall through to the next route, because that would put you on a provider you didn't choose. ## Claude on Bedrock We address every Claude model on Bedrock through a global inference profile, so it can run in any AWS region. A request is not guaranteed to run in the region your Bedrock key names. Bedrock can carry a model and still refuse it for your AWS account, which returns `403 bedrock_model_access_denied`. Grant the model in the Amazon Bedrock console under Model access. The five newest Claude models need two more one-time steps on the AWS account: `claude-opus-5`, `claude-sonnet-5`, `claude-fable-5`, `claude-opus-4-8`, and `claude-opus-4-7`. Run both with an administrator's credentials. The first command opts the whole AWS account into provider data sharing, Amazon requires it for these models, and it stays on until you turn it off. The Bedrock inference key you added in the dashboard can't run them. ```bash theme={null} aws bedrock put-account-data-retention --mode provider_data_share ``` ```bash theme={null} aws bedrock list-foundation-model-agreement-offers --model-id anthropic.claude-opus-5 aws bedrock create-foundation-model-agreement \ --model-id anthropic.claude-opus-5 \ --offer-token OFFER_TOKEN_FROM_THE_PREVIOUS_COMMAND ``` Until both are done those models return `403 bedrock_model_access_denied`. Amazon requires this, not us. ## GPT on Foundry The `foundry` route runs GPT through Azure AI Foundry instant access, with no Azure deployment step. Add your resource name and one of its API keys under API, then Provider keys. Create the resource in West US 3, the one instant-access region during the preview. Azure decides which part of the GPT catalog instant access carries. A model it lacks returns `404 foundry_model_unavailable`. ## Open source on DeepInfra The `deepinfra` route runs open-source models. Add your DeepInfra token under API, then Provider keys. DeepInfra sells a flex tier. We don't race it. The route never tells us when it has read your prompt but hasn't started writing yet. So a race we lose has already paid to read your prompt, then pays again in full. That costs more than a standard call, so we send you standard. `gemma-4-26b-a4b-it` and `llama-4-scout-17b-16e-instruct` run on both `cloudflare` and `deepinfra`. They go to Workers AI unless you name `deepinfra` first. # Billing Source: https://docs.flexinference.com/billing Your own provider keys don't touch billing. Everything below applies to Managed Keys. ## Managed Keys Turn Managed Keys on for a provider and we run that provider's requests on our own keys, so you don't need an account with them. We require you to prepay a balance, which is then used to pay off model costs for the provider chosen. You turn Managed Keys on for each provider separately. OpenAI can run managed while Anthropic stays on your own key. * OpenAI serves `gpt-*` and `o*` models. * Anthropic serves `claude-*` models. * Gemini serves `gemini-*` models. * Workers AI serves the [open-source families](/models#open-source-models). * Bedrock serves `claude-*` models only. * Vertex serves `gemini-*` models only. ## Refunds Ask for a refund of unspent cash on the dashboard **Billing** page. It goes back to the card you paid with. We keep the top-up fee and can't refund promo credits. Cash held by a request still in flight counts as spent until that request settles. ## When the balance runs out When the balance hits zero, managed requests stop and return [`402 insufficient_balance`](/errors#insufficient_balance) until you add funds. Your own key routes keep working. We send a low-balance notice at \$5, and auto-refill can top up for you. A [daily spending limit](/spending-limits) also caps how much a runaway loop can spend in one day. A disputed card payment stops everything, your own key routes included. That's [`403 payment_disputed`](/errors#payment_disputed), and adding funds doesn't lift it. Withdraw the dispute with your bank, or talk to us. ## Cost inside a stream A response you didn't stream reports its cost twice, in the `x-flexinference-cost` header and the `usage.cost` block. A streamed response can't use the header, so send `include_cost: true` to move the cost inside the stream. ```json theme={null} { "model": "gpt-5.5", "start_within": "00h-00m-30s", "stream": true, "include_cost": true, "input": "Summarize this contract." } ``` The cost then goes in the usage frame the endpoint already sends. On `/v1/chat/completions`, also send `"stream_options": {"include_usage": true}`, because OpenAI makes that frame opt-in there. A managed request reports what the provider charged us. An own-keys request reports the provider's list price at the tier that ran it. A request we can't price reports no `cost` block at all. ## Managing billing You add a card, top up, set auto-refill, and ask for refunds on the dashboard **Billing** page. # Claude Code Source: https://docs.flexinference.com/claude-code Point Claude Code at FlexInference with an agent key that carries the deadline. Claude Code speaks the Anthropic Messages API. We run that API at `POST /v1/messages`, so a base URL and a key are the whole integration. Claude Code gives you nowhere to set `start_within`, so the deadline goes on an [agent key](/agent-keys). An interactive session streams, and Claude's cheaper tier doesn't, so pick a tier rather than **Flex race**. The race rules are on [Flex Racing with Claude models](/deadline-routing#flex-racing-with-claude-models). Your organization needs Anthropic servable first: an Anthropic provider key on your own keys, or Anthropic turned on and funded on [Managed Keys](/billing#managed-keys). ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure Claude Code to send its requests to FlexInference, which serves the Anthropic Messages API. > > You will never see or handle my API key. Claude Code reads it from the `ANTHROPIC_AUTH_TOKEN` environment variable, and I export that myself. Do not ask me for the key, do not write it into any file, and do not read it from my environment. > > Ask me whether to configure this globally or for one project, then edit `~/.claude/settings.json` or `.claude/settings.json` accordingly. Create the file if it does not exist, and preserve every setting already in it. > > Add this `env` block, merging into any existing `env` rather than replacing it. Note that it carries no credential: > > { > "env": { > "ANTHROPIC_BASE_URL": "https://api.flexinference.com", > "ANTHROPIC_MODEL": "claude-opus-5", > "ANTHROPIC_SMALL_FAST_MODEL": "claude-haiku-4-5", > "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1" > } > } > > Then print this line for me to run in the shell I start Claude Code from. Do not run it and do not ask for the value: > > export ANTHROPIC_AUTH_TOKEN= > > Rules that matter, do not deviate: > - `ANTHROPIC_BASE_URL` must NOT end in `/v1`. Claude Code appends `/v1/messages` itself. > - The credential must arrive as `ANTHROPIC_AUTH_TOKEN`, never `ANTHROPIC_API_KEY`. The first sends `Authorization: Bearer`, which FlexInference requires. The second sends `x-api-key`, which it refuses with `401 missing_api_key`. > - Both model variables must be `claude-*` slugs. Claude Code sends Anthropic-native fields such as `output_config` on every request, and FlexInference refuses to mistranslate them onto a non-Claude model. > - `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` must be `"1"`. Without it Claude Code sends experimental beta fields such as `context_management`, FlexInference does not forward the `anthropic-beta` headers they need, and every request fails with `400 context_management: Extra inputs are not permitted`. > - Do not add a retry setting. Claude Code retries on its own and my key may carry its own policy. > > Finally, tell me that Anthropic must be servable on my FlexInference organization. On BYOK that means an Anthropic provider key on the API, then Provider keys tab. On Managed Keys it means Anthropic enabled and funded. Then start a new Claude Code session and report what you changed. > ``` ## Configure Claude Code 1. Create or open `~/.claude/settings.json`. A per-project file at `.claude/settings.json` works the same way. 2. Add an `env` block naming the router, your key, and both models. ```json theme={null} { "env": { "ANTHROPIC_BASE_URL": "https://api.flexinference.com", "ANTHROPIC_AUTH_TOKEN": "flex_live_...", "ANTHROPIC_MODEL": "claude-opus-5", "ANTHROPIC_SMALL_FAST_MODEL": "claude-haiku-4-5", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1" } } ``` 3. Start Claude Code. ```bash theme={null} claude ``` Export the same variables in your shell instead, to keep the secret out of a file. ```bash theme={null} export ANTHROPIC_BASE_URL=https://api.flexinference.com export ANTHROPIC_AUTH_TOKEN=flex_live_... export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 ``` Four rules make this work. **Omit the `/v1` suffix.** Claude Code appends `/v1/messages` to the base URL itself. **Use `ANTHROPIC_AUTH_TOKEN`, never `ANTHROPIC_API_KEY`.** The first sends `Authorization: Bearer`, which we require. The second sends `x-api-key`, which we refuse. **Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` to `1`.** Claude Code otherwise sends experimental beta fields such as `context_management`. We don't forward the `anthropic-beta` headers those fields need, so every request fails. **Set both model variables.** Claude Code runs a large main-loop model and a small background model against one key. Both must be `claude-*` slugs. ## Troubleshooting **`400 context_management: Extra inputs are not permitted`.** Claude Code sent an experimental beta field, and we don't forward the `anthropic-beta` header it needs. Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` and start a new session. The same flag clears any other `Extra inputs are not permitted` refusal naming a beta field. **[`401 missing_api_key`](/errors#missing_api_key).** You set `ANTHROPIC_API_KEY`, so the client sent `x-api-key`, which we don't read. Set `ANTHROPIC_AUTH_TOKEN` instead and unset `ANTHROPIC_API_KEY`. **[`400 unsupported_parameter`](/errors#unsupported_parameter) naming `output_config`.** A model variable points at a non-Claude slug, and Claude Code sends Anthropic-native fields we refuse to mistranslate. Set both model variables to `claude-*` slugs. **[`404 unknown_url`](/errors#unknown_url) naming `/v1/messages/count_tokens`.** We don't route that path. A `claude -p` run never calls it, though an interactive session may. Anything not specific to Claude Code is on [agent keys](/agent-keys#troubleshooting). # Claude Cowork Source: https://docs.flexinference.com/claude-cowork Point Claude Cowork at FlexInference through its gateway mode. Cowork reaches a third-party endpoint through gateway mode. The gateway must implement the Anthropic Messages API, which we run at `POST /v1/messages`. Cowork gives you nowhere to set `start_within`, so the deadline goes on an [agent key](/agent-keys). An interactive session streams, and Claude's cheaper tier doesn't, so pick a tier rather than **Flex race**. The race rules are on [Flex Racing with Claude models](/deadline-routing#flex-racing-with-claude-models). Your organization needs Anthropic servable first: an Anthropic provider key on your own keys, or Anthropic turned on and funded on [Managed Keys](/billing#managed-keys). Cowork keeps these settings behind menus, so this page has no agent setup prompt. Use **Export** below to push the same configuration across a fleet. ## Enable developer mode The **Developer** menu stays hidden until you turn it on. 1. Open Claude Desktop. 2. Go to **Help**, then **Troubleshooting**. 3. Press **Enable Developer Mode**. **Developer** then appears in the menu bar. ## Configure Cowork 1. Go to **Developer**, then **Configure Third-Party Inference...**. 2. Set **Inference provider** to **Gateway**. 3. Set **Gateway base URL** to the router, with no `/v1` suffix. ```text theme={null} https://api.flexinference.com ``` 4. Paste your agent key into **Gateway API key**. 5. Leave **Credential kind** on **Static API key**. 6. Leave **Gateway auth scheme** on **Bearer**. We refuse `x-api-key`. 7. Pick a `claude-*` model in the model picker. Cowork reads our `GET /v1/models` response to fill the picker. It lists only models it recognizes as Claude, which is what you want here. ## Deploy across a fleet Click **Export** in the same window for a `.mobileconfig` on macOS or a `.reg` on Windows, then push it with your MDM. Three keys hold the integration. | Key | Value | | - | - | | `inferenceGatewayBaseUrl` | `https://api.flexinference.com` | | `inferenceGatewayApiKey` | your agent key | | `inferenceGatewayAuthScheme` | `bearer`, which is the default | Set `inferenceModels` to an explicit list only if the picker misses a model you expect. ## Leave the beta features off Cowork turns Claude Code's experimental beta features off by default, because strict gateways reject the `anthropic-beta` headers and request fields they add. We're one of those gateways, and we don't forward those headers. Leave `toolSearchEnabled` unset for the same reason. Turning it on sends beta headers we don't forward, and requests then fail. ## Troubleshooting **There is no Developer menu.** Developer mode is off, and it hides the menu entirely. Turn it on under **Help**, then **Troubleshooting**, then **Enable Developer Mode**. **[`401 missing_api_key`](/errors#missing_api_key).** **Gateway auth scheme** is set to **x-api-key**, which we don't read. Switch it to **Bearer**. **The model picker is empty.** Cowork filters `GET /v1/models` down to ids it recognizes as Claude. Confirm your organization can run `claude-*` models, or set `inferenceModels` yourself. **`400` on every request after enabling tool search.** `toolSearchEnabled` makes Cowork send experimental `anthropic-beta` headers and fields that we don't forward. Leave it unset. **[`400 unsupported_parameter`](/errors#unsupported_parameter) naming `output_config`.** The picker selected a non-Claude model, and Cowork sends Anthropic-native fields we refuse to mistranslate. Pick a `claude-*` model. Anything not specific to Cowork is on [agent keys](/agent-keys#troubleshooting). # Codex Source: https://docs.flexinference.com/coding-agents Point Codex at FlexInference with a key that carries the deadline. [Codex](https://developers.openai.com/codex/cli) builds its own request body, so the deadline goes on an [agent key](/agent-keys). ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure the Codex CLI to send its requests to FlexInference. Do not change my existing Codex setup: create a separate profile I opt into per run. > > You will never see or handle my API key. The profile stores only the NAME of an environment variable, and I export the value myself. Do not ask me for the key, and do not read it from my environment. > > 1. Create `~/.codex/flexinference.config.toml` with exactly this content: > > model = "gpt-5.6-sol" > model_provider = "flexinference" > > [model_providers.flexinference] > name = "FlexInference" > base_url = "https://api.flexinference.com/v1" > wire_api = "responses" > env_key = "FLEX_API_KEY" > > 2. Tell me to export the key myself, in the shell I will run Codex from: > > export FLEX_API_KEY= > > Print that line for me to run. Do not run it, do not ask for the value, and do not add it to my shell profile. > > 3. Tell me to start Codex with `codex --profile flexinference`. > > Rules that matter, do not deviate: > - Keep the `model` line. Codex defaults to a slug ending in `-codex`, which FlexInference recognizes but holds no price for and never races. Use the full `gpt-5.6-sol`; the bare `gpt-5.6` alias makes Codex print a metadata warning. > - Keep `wire_api = "responses"`. FlexInference serves that surface at `/v1/responses`. > - Never add `service_tier`. FlexInference derives the tier from the key's deadline and returns `400 service_tier_not_allowed` if the request carries its own. > - `env_key` and `auth` are mutually exclusive. Use `env_key` unless I ask for a keychain helper. > - Do not set `request_max_retries`. My key may carry its own retry policy and the two stack. > > Verify by checking the file parses under `codex --profile flexinference --strict-config`, then report what you changed. > ``` ## Configure Codex Codex keeps each profile in its own file. This profile leaves your usual Codex setup alone, and you opt in per run with `--profile`. 1. Write the profile file. Paste this once: ```bash theme={null} mkdir -p ~/.codex && cat > ~/.codex/flexinference.config.toml <<'EOF' model = "gpt-5.6-sol" model_provider = "flexinference" [model_providers.flexinference] name = "FlexInference" base_url = "https://api.flexinference.com/v1" wire_api = "responses" env_key = "FLEX_API_KEY" EOF ``` 2. Export the key Codex reads. The profile file never holds it. ```bash theme={null} export FLEX_API_KEY=flex_live_... ``` 3. Start Codex with the profile. ```bash theme={null} codex --profile flexinference ``` That is the whole integration. Codex calls `/v1/responses`, sends the key as a bearer token, and the key supplies the deadline. The session header names the provider in use, so you can see the profile took. To reach us on every Codex run instead, put the same lines in `~/.codex/config.toml`. The top-level `model` and `model_provider` there set your default. `env_key` and `auth` rule each other out. `env_key` reads the key from your environment, which is the short path. Keep secrets in a keychain instead and you leave `env_key` out, then name a helper command in `auth`. Keep the `model` line. Codex otherwise defaults to a slug ending in `-codex`, which we hold no price for and never race. Use the full `gpt-5.6-sol`, because the bare `gpt-5.6` alias makes Codex print a metadata warning. ## Troubleshooting **Nothing reaches us at all.** You ran a plain `codex`, which uses your usual provider and account. Start it with `--profile flexinference`. Any error you saw is theirs, usage limits included, and the session header names the provider in use. **[`400 model_not_priced_for_managed`](/errors#model_not_priced_for_managed).** `model` is unset, so the request arrived on a `-codex` slug we hold no price for. Set `model = "gpt-5.6-sol"` in the profile. On your own provider key we run that slug instead, with no cost figure of ours. **[`400 service_tier_not_allowed`](/errors#service_tier_not_allowed).** The profile sets `service_tier`, and we read the tier from the deadline instead. Remove the line. Anything not specific to Codex is on [agent keys](/agent-keys#troubleshooting). # Cursor Source: https://docs.flexinference.com/cursor Point Cursor at FlexInference with an agent key that carries the deadline. Cursor sends chat completions to whatever base URL you set. The integration is two fields and a model name. Cursor gives you nowhere to set `start_within`, so the deadline goes on an [agent key](/agent-keys). Pick a tier rather than **Flex race**, because Cursor sends Chat Completions parameters a race refuses. Cursor keeps these settings in its own UI, with no config file to write, so this page has no agent setup prompt. The steps below take under a minute by hand. ## Configure Cursor 1. Open Cursor settings with `Cmd+,` on macOS, or `Ctrl+,` on Windows and Linux. 2. Click **Models** in the sidebar. 3. Enable **Override OpenAI Base URL**. Enter the router URL, including the `/v1` suffix. ```text theme={null} https://api.flexinference.com/v1 ``` 4. Paste your agent key into the **OpenAI API Key** field. ```text theme={null} flex_live_... ``` 5. Add `gpt-5.6-sol` to the model list. Cursor sends this name to us verbatim. 6. Click **Verify**. Cursor appends `/chat/completions` to the base URL and sends the key as a bearer token. The key supplies the deadline. ## Troubleshooting **A `401` that doesn't look like ours.** The base URL is blank or wrong, so Cursor sent your key to `api.openai.com` and OpenAI refused it. Set both the base URL and the key field. **`422` on Claude models.** That refusal isn't ours. We run `claude-*` on Chat Completions by translating the request onto Anthropic's Messages API, as long as the body has no native Chat parameter. Cursor's own Claude path through an overridden base URL fails this way on its side. Use a `gpt-*` slug to move on, or send the same request to us directly to see which side refuses it. **Claude worked yesterday, `422` today.** Turning Anthropic BYOK on in Cursor also turns the base URL override on without saying so. Turn one of the two off. **Tab autocomplete never appears in your logs.** Cursor runs Tab on its own backend, and the override applies to chat only. Nothing is wrong. **`Verify` passed but requests still fail.** **Verify** checks the key format and that the endpoint answers, not every feature path. Send one chat request to check it works. Anything not specific to Cursor is on [agent keys](/agent-keys#troubleshooting). # Flex Race Routing Source: https://docs.flexinference.com/deadline-routing Every request needs either a `start_within` duration or a tier name. A duration tells us how long we have to start your request with cheaper inference. It does not limit how long the response may take to finish. ## Starting a Flex Race Send a duration to start a race. ```json theme={null} { "start_within": "00h-00m-30s" } ``` Write the duration as `HHh-MMm-SSs`, with two digits for each field. The duration must be between 5 seconds and 10 minutes. Longer durations give the cheaper tier more time to start. ## Skipping the Flex Race Send a tier name when you want to use a specific tier without starting a race. * `default` uses the provider's normal real-time tier at its normal price. * `priority` uses the provider's fastest and most expensive tier. * `auto` lets the provider choose the tier. ## Flex Racing with Claude models Claude's cheaper tier returns the complete response at once instead of streaming it. Because this process takes minutes rather than seconds, Claude races follow different rules. A Claude race must meet these requirements: * `start_within` must be at least `00h-03m-00s`. * The request must not stream. * Your organization must use Anthropic through our managed keys. The duration has a different meaning for Claude. For GPT and Gemini, the cheaper tier only has to start within the duration, so the response may finish after it. For Claude, the complete response must arrive within the duration. ## Reading the result Check `service_tier` on the response to see which tier served your request. * `flex` means the cheaper tier served the request. * `default` or `standard` means we used the default tier. Every response also includes these headers: * `x-flexinference-flex-applied` is `true` only when the cheaper tier served the request. * `x-flexinference-flex-reason` is `not_requested`, `flex_committed`, or `flex_lost_race`. * `x-flexinference-cost` contains the request cost in millionths of a dollar, on responses you didn't stream. A stream carries the same number in `usage.cost` when you send `include_cost: true`. ## Setting the duration for Agent Keys Some tools cannot add fields to a request body. For these tools, create an agent key in the [dashboard](https://www.flexinference.com/dashboard) and assign a duration to it. This can then be used for tools like Codex or OpenClaw. ## We don't route to smaller models or change prompts We change only the service tier. We pass your prompt, model, the provider's response, and the provider's error text through unchanged. # Decision Models Source: https://docs.flexinference.com/decision-models A decision model answers questions about an input with probabilities. It writes no text. You send the input and named questions, and you get one answer back per question. ## Two endpoints * `POST /v1/decisions` takes OpenAI's Decisions format. * `POST /v1/systemone` takes the System One format, which Microsoft and Cloudflare use. Any decision model works on either endpoint. When the model speaks the other format, we translate your request and its answer. The answer always comes back in the format of the endpoint you called. ## The models | Model | Routes | Native format | Questions per request | | - | - | - | - | | `gpt-6-luna` | `openai`, `foundry` | Decisions | 1 to 400 | | `microsoft-decision-1` | `foundry` | System One | No stated limit | | `clef` | `cloudflare` | System One | 1 to 64 | | `clef-flash` | `cloudflare` | System One | 1 to 64 | `GET /v1/models` marks each one with a `decisions` block. It lists the routes, the question limit, and the price on each route. `gpt-6-luna` is also a text model, so it keeps serving the text endpoints. The other three write no text, so a text endpoint refuses them with `400 model_surface_mismatch`. A text model sent to a decision endpoint gets the same error. ## Your own keys only Decision models run on the provider keys you add in the dashboard. * `openai` uses your OpenAI key. * `foundry` uses your Azure AI Foundry key and resource. * `cloudflare` uses your Workers AI token and account ID. If your organization serves a route on managed keys, a decision request for that route returns `400 decisions_byok_only`. A missing key returns that route's own error, such as `400 no_foundry_key`. On Foundry, the `model` field names a deployment, and we send the model ID you used. Name the deployment after the model: `gpt-6-luna` or `microsoft-decision-1`. ## No Flex Race Decision requests never race. OpenAI's Decisions API refuses a flex tier, and System One has no tiers at all. * Send `"start_within": "default"` in the body, or `x-start-within: default` as a header. * A duration returns `400 flex_model_not_capable`. * `priority` or `auto` returns `400 tier_unsupported_on_decisions`. * An API key with a deadline default works. Its fallback tier applies. `x-flexinference-routing-reason` reads `tier_direct`, or `chain_advanced` when a backup served. Name backups in `provider`, the same as on the text endpoints. A route that answers `429`, `5xx`, or no connection passes the request to the next one. Neither endpoint streams. `"stream": true` returns `400 unsupported_parameter`. ## OpenAI's Decisions format ```bash theme={null} curl https://api.flexinference.com/v1/decisions \ -H "Authorization: Bearer $FLEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-6-luna", "start_within": "default", "input": "I was charged twice for my subscription and want a refund.", "questions": [ { "type": "predicate", "name": "billing", "instructions": "Is this about billing?" }, { "type": "choice", "name": "team", "instructions": "Which team should handle this?", "choices": [ { "value": "billing", "description": "Payments and refunds" }, { "value": "tech", "description": "Bugs and outages" } ] } ] }' ``` The answer looks like this: ```json theme={null} { "model": "gpt-6-luna", "answers": [ { "type": "predicate", "name": "billing", "probability": 1.0 }, { "type": "choice", "name": "team", "choice": "billing", "probabilities": [ { "value": "billing", "probability": 1.0 }, { "value": "tech", "probability": 0.0 } ], "confidence": 1.0 } ], "usage": { "input_tokens": 161, "output_tokens": 0, "total_tokens": 161 } } ``` ## The System One format ```bash theme={null} curl https://api.flexinference.com/v1/systemone \ -H "Authorization: Bearer $FLEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "clef", "start_within": "default", "state": "Checkout is down for all EU customers since 09:00.", "questions": { "outage": { "type": "noul", "instructions": "Is this an outage?" }, "severity": { "type": "score", "instructions": "How severe is this?", "criteria": ["Cosmetic", "Minor", "Major", "Critical"] } } }' ``` The answer looks like this: ```json theme={null} { "model": "clef", "answers": { "outage": { "type": "noul", "noul": 0.98 }, "severity": { "type": "score", "score": 2.7, "legend": { "0": "Cosmetic", "1": "Minor", "2": "Major", "3": "Critical" }, "probabilities": { "0": 0.01, "1": 0.04, "2": 0.2, "3": 0.75 }, "confidence": 0.6 } }, "usage": { "input_tokens": 120, "output_tokens": 0 } } ``` A score is the probability-weighted level, so it can land between two levels. ## How we translate * A noul is a predicate. Its answer is a probability in both formats. * A choice's `criteria` object becomes `choices`, one `value` per label. * A score's `criteria` list becomes `levels`. Each level's label is its position, `"0"`, `"1"`, and so on, the same key the answer's `legend` and `probabilities` use. * System One names each question with its key. OpenAI names it with `name` and answers in a list, in question order. * A noul's true and false `criteria` have no OpenAI field, so we add them to the instructions. * A System One question with no `instructions` gets one for its type, such as "Which option best fits the state?". OpenAI requires instructions. * Structured state becomes one `input_json` part. OpenAI's text and JSON parts join into one state string, and a single JSON part stays structured. * An OpenAI level becomes `"label: description"` in System One. * OpenAI can refuse to answer a question. On `/v1/systemone` that answer is `{ "type": "refusal" }` under the question's name. * For a System One model we drop `safety_identifier` and the three prompt-cache fields. None of them changes an answer. We refuse a request that can't be translated with `400 decision_translation_unsupported`, before we call the provider. * Images. Send them in the model's own format: `input_image` parts for `gpt-6-luna` on `/v1/decisions`, or `images` for `clef` on `/v1/systemone`. * A field the other format has no place for. * A choice with one option, or a score with one level, for an OpenAI model. OpenAI needs at least two. * More than 255 options for a System One model. When the request and the model share a format, we forward your body as you wrote it, minus our own fields: `start_within`, `provider`, `stream`, and `include_cost`. The answer is the provider's own body. ## What we check first `400 invalid_decision_request` names the field that breaks a rule of its format: * `input` or `state` is missing. * A question count is outside the model's range. * Two questions share a name. * A choice offers `true` and `"true"` as two options. * The body nests deeper than 64 levels, or holds a number JSON can't carry. ## Cost Decision models bill input tokens only. * `gpt-6-luna` on `openai`: $0.10 per million input tokens. Cache reads bill at $0.01 and cache writes at \$0.125. All three double above 272,000 input tokens. We report the cost in `x-flexinference-cost`. * `clef` costs $0.24 and `clef-flash` $0.038 per million input tokens on Cloudflare's price list. A serve on your own Cloudflare account carries no cost header, the same as every cloud route. * Microsoft publishes no rate for either Foundry model yet, so a Foundry serve carries no cost header. A translated answer also carries `usage.cost` and `usage.routing` in its body. A same-format answer is the provider's own body, so it reports cost on the header only. Errors on `/v1/systemone` come back as `{ "detail": "...", "param": ..., "flexinference": { ... } }`, where `param` names the field at fault. See [Errors](/errors) for every code. # Demos Source: https://docs.flexinference.com/demos These are some of the ways you could use FlexInference to drop your costs by about 48 percent for only about 20 percent higher latency. ## OpenScience When running OpenScience we were able to see 50.0% savings for an increase of 9.3% in time to first token. Run this from your terminal to add the skill to Claude Code. ```bash Install the OpenScience skill theme={null} mkdir -p ~/.claude/skills/openscience-flexinference && curl -fsSL https://flexinference.com/skills/openscience.skill.md -o ~/.claude/skills/openscience-flexinference/SKILL.md ``` > [accordion] Transcript > > FlexInference demo transcript: OpenScience > > Hi everyone, my name is Adi. I'm the founder of FlexInference, and here we have OpenScience, an open-source alternative to Claude Science. It's been changed to route all its requests through FlexInference, and you can have your OpenScience do the same: we've added a prompt right below this demo that you can copy and paste into any agentic coding tool you use, and it'll upgrade your OpenScience to also use FlexInference. For this demo we're using GPT 5.6 Terra. I'll set thinking to low, set a flex race so it searches for cheaper inference, and give it five seconds to find cheaper inference, otherwise upgrade to a default request. We're going to be looking at cost per one million tokens and time to first token, because in the background we spin up two parallel requests every time I ask a question. That's just so we can compare, and since the results could be non-deterministic, what we really care about is when the first token came back and how much each side costs per one million tokens. I'd like to say that FlexInference supports all Claude models, all Gemini models, and all GPT models you see here. > > Now let's ask it: I work in logistics and I own three trucks. I want my routing to be more efficient, to deliver faster and for cheaper. Find me research papers that are relevant. > > While this goes, we have two parallel processes running in the background to compare against. What we do guarantee is that within the time you set, we'll find you cheaper inference or escalate to a normal default request; in this case we're comparing against always asking default requests. We sometimes see that we're somehow faster, and obviously cheaper, but we don't guarantee the faster part. We do guarantee the cheaper part. You can obviously make default requests through us and get the speed you'd like, along with priority requests. > > Why would you want an SLA for a science-style hypothesis and repetitive process task? Having worked in research, there are often cases where you have ten hypotheses and a limited amount of API credits, dev time, or just time before a deadline. So you only try the top three and shelve the bottom seven. Eventually the top three fail to deliver the results you want, you start going through the rest, you get to the eighth one on that list, and you think, I wish I'd tried this sooner - it just didn't make sense in that moment. This way, the hypotheses you're considering that don't seem like a good return on investment can run cheaper in the background. Even if it takes a little longer, that's fine, because you weren't going to prioritize it anyway - but now you'll get the results sooner. And when you're doing research, or any open-ended task where you iterate and do trial and error, you're getting a bunch of people's inputs and you want to give them results too, but you can't dedicate time or API credits. You can push all their requests and hypotheses onto different OpenScience sessions, make sure it comes out in enough time, and they'll get their results much cheaper while you continue to prioritize. Your more prioritized requests you can keep doing through default or priority requests. > > As you can see, it completed, and we were able to complete our task with only thirty extra seconds - at fifty percent of the price. It makes sense to give up ten percent or less latency, in this case, for a fifty percent cost reduction. I hope you liked it and implement it in your own version of OpenScience. Thank you. ## OpenCode When running OpenCode we were able to see 50.0% savings and had a decrease of 37.5% in time to first token. Run this from your terminal to add the skill to Claude Code. ```bash Install the OpenCode skill theme={null} mkdir -p ~/.claude/skills/opencode-flexinference && curl -fsSL https://flexinference.com/skills/opencode.skill.md -o ~/.claude/skills/opencode-flexinference/SKILL.md ``` > [accordion] Transcript > > FlexInference demo transcript: OpenCode > > Hi, my name is Adi. I'm the founder of FlexInference, and here we have OpenCode, and it's been changed to route model requests through FlexInference. You can actually change it yourself: there's a prompt below this demo that you can copy and paste into any agentic coding tool, point it at your OpenCode, and say "I want to start using FlexInference," and it'll make it so you can have the same tool we have right here. It's already set to GPT 5.4; we'll set it to low thinking, flex on, five-second SLA, and I'll start the demo and explain how things are going. So we'll say: I'm having a hard time understanding derivatives. I would like a simple HTML page with dynamic visualizations that explain it to me. > > OpenCode is going to create this, and on the right-hand side a comparison will be running: the flex race rate, which is cost per one million tokens, then the default rate, and then flex race time to first token and default time to first token. On the front end, what you're seeing through this TUI is just what flex is responding with. On the back end, we're sending two parallel requests, so this is really an apples-to-apples comparison, and you can see the time-to-first-token and cost-per-one-million-token comparison as well. > > The point behind FlexInference is that we give you access to a flex race that searches for cheaper inference within the time you set, and we set it to five seconds; if that isn't fulfilled, we escalate it up. We can do every other type of request as well. In slash models you can see we support all major models. What sets us apart is the flex race. There are a lot of cases with non-latency-sensitive tasks where it's great. Imagine you get a page at 8 PM. It's a sev 4 and not the biggest deal. You think it would be nice if it could be implemented, but you're fine if it takes ten minutes longer. Those cases, it's great. Or cases where you have background projects you're interested in, but you don't want to spend all your API credits at once: you can queue up a bunch of tasks, they slowly churn out, and you spend a lot less. > > Now it's already created this derivatives HTML page, which we can open up, but what I'm interested in is the comparison. Time to first token was actually faster on GPT 5.4, which happens from time to time. We don't guarantee it'll be faster than default, but it does happen, and it's great in our case. Second, it is cheaper: a fifty percent cost reduction here. Setting up FlexInference within OpenCode itself means you or your devs can spend a lot more time trying out different projects and ideas without worrying whether your credits are getting used up in the wrong area, because now you have a fifty percent cost reduction. Hopefully you enjoy this and end up using it as well. Thank you. ## OpenWork When running OpenWork we were able to see 48.5% savings for an increase of 6.9% in time to first token. Run this from your terminal to add the skill to Claude Code. ```bash Install the OpenWork skill theme={null} mkdir -p ~/.claude/skills/openwork-flexinference && curl -fsSL https://flexinference.com/skills/openwork.skill.md -o ~/.claude/skills/openwork-flexinference/SKILL.md ``` > [accordion] Transcript > > FlexInference demo transcript: OpenWork > > Hi everyone, my name is Adi. I'm the founder of FlexInference, and here we have OpenWork, and it's been changed so that it uses FlexInference in the background for its router. There's a prompt down below that you can paste into any CLI or agentic coding tool you use, and it should change your OpenWork to start using FlexInference as well. Let's start the demo and I'll explain how it works. All of these models are supported through FlexInference, but let's say I want a task that needs a smart model: GPT 5.4. I'll set it to low thinking with flex on and give it a five-second SLA to find cheaper inference within, otherwise escalate to a default request. So let's say: I want you to use the browser tool to find the current price for Netflix and the week change as well, and tell me why it is rising or falling. > > While this is happening, I'll explain the cases where this is really helpful. Yes, you can use FlexInference for default requests, priority requests, auto requests, but what makes us different is the flex race, given an SLA you set. Think about cases where you have a daily brief in the morning: at 8 AM I want a stock market brief. Does it really matter if it created the brief within one minute compared to one minute and ten seconds? In my opinion, not really. If you're willing to give up that ten-second or five-second SLA, those cases are incredible, because you're going to save fifty percent for free, just by giving a few seconds here and there. > > In fact, in our case, the front end shows only the flex response, but on the back end, for every request in this demo, we send out two parallel requests - one default and one with the five-second SLA - and compare them on cost per one million tokens and time to first token. These are just really good comparison metrics, because the responses between the two requests could be different, but cost per one million tokens is fair, and time to first token is also fair. > > What we're seeing here is that you saved fifty percent, and all you really did was spend .08 extra seconds getting a response. You can imagine that aggregated across 365 days and all the asynchronous processes you might have running in the background that are not latency-sensitive, it's really helpful. And then you can think of the other use cases that start being helpful because of the fifty percent cost savings you get. So that's one of the great ways you can use FlexInference. We hope you like it, and be sure to copy the prompt down below and use it on your own OpenWork. Thank you. ## Gemini image classification When running image classification we were able to see 38.9% savings for an increase of 20.2% in time to first token. [The code is public.](https://github.com/FlexInference/flexinference-demos/tree/main/extras/gemini-image-pipeline) > [accordion] Transcript > > FlexInference demo transcript: Gemini image classification > > Hi everyone, my name is Adi. I'm the founder of FlexInference, and here we have an image classification demo. I'm going to start this and then explain what's going on. > > We have two parallel processes, both running Gemini 2.5 Flash, that are going to classify a dataset of fifty images of different colors, identifying what color each one is. We're not trying to compare which side classifies better; it's the same model on both sides, and both use FlexInference's SDK and router. The left-hand side has been given a ten-second SLA to find cheaper inference through the start\_within parameter. The right-hand side is also using the FlexInference SDK and router, but its start\_within parameter is set to default, which asks for an instant response. What we're trying to show is that given a small latency budget that you get to set, in this case ten seconds, you can get dramatically lower costs, approximately fifty percent. I'm going to fast-forward to when this dataset has been classified and completed, and then we can look at the trade-offs. > > Now that we're back, we can see that fifty out of fifty images have been classified. The total costs were about half: \$0.0183 compared to \$0.0304. Cost per one million tokens, input and output together, is \$0.58 versus \$0.95, which is also approximately half. The total latency given up was about twenty-seven seconds, roughly fifteen percent. Essentially, given a small latency budget, you were able to get dramatically lower costs. Thank you. ## OpenAI deep research When running deep research we were able to see 44.8% savings and had a decrease of 30.1% in time to first token. [The code is public.](https://github.com/FlexInference/flexinference-demos/tree/main/demos/05-deep-research-agents) > [accordion] Transcript > > FlexInference demo transcript: OpenAI deep research > > Hi everyone, my name is Adi. I'm the founder of FlexInference, and here is a demo for deep research. I'm going to start the demo as I explain how it works. We have two agents running as parallel processes, both using the FlexInference SDK and router, that are going to try to find public CPU companies with an edge in model training and inference. The topic itself is not that relevant: each agent creates some questions, does some web searches, and creates a report. What we're really looking at is that the left-hand agent has been given a ten-second SLA to find cheaper inference, and if it can't within that time, it escalates to a default request and still fulfills the request. The right-hand side's start\_within parameter is set to default instead of ten seconds, which asks for an instant response. What we're trying to see is that the left-hand side, given a small latency budget of up to ten seconds, has dramatically lower costs, about fifty percent lower. That makes FlexInference far cheaper and far more affordable for tasks without very low latency requirements. I'm now going to fast-forward to the very end so we can compare the trade-offs. > > Now we're back. Both reports have been made; the agents did web searches and some tertiary planning. The left-hand side, Flex, was not only cheaper but also completed faster, which sometimes happens. We do not guarantee that latency will be lower; we guarantee that within the SLA you set, we will either find you cheaper inference or escalate up to a default request. Here the left-hand side finished about sixty seconds faster, and cost per one million tokens was about twenty-six cents lower on GPT-5 Mini, nearly half the cost. We use cost per one million tokens because the two sides used a different number of tokens and citations, so it is a more accurate comparison. Total cost came out to about a \$0.0265 difference. Thank you. ## OpenAI browser agent When running the browser agent we were able to see 51.5% savings for an increase of 9.7% in time to first token. [The code is public](https://github.com/FlexInference/flexinference-demos/tree/main/demos/04-browser-agents), and one command, `./dev.sh`, runs the whole thing. > [accordion] Transcript > > FlexInference demo transcript: OpenAI browser agent > > Hi everyone, my name is Adi. I'm the founder of FlexInference, and here we have a browser agent demo. I'm going to start this demo as I explain how it works. On the back end we have an e-commerce clone, and our agents are going to try to accomplish the task of buying one Medusa T-shirt in size M, color black. On the left-hand side we have GPT-5 being routed through FlexInference's SDK and router, given ten seconds to find cheaper inference; if it does, it fulfills the request that way, and otherwise it escalates to a default request. On the right-hand side we also have GPT-5 using the FlexInference SDK and router, but the start\_within parameter is set to default, so its requests are fulfilled instantly. The goal is to show that on the left-hand side you can get the same task done, giving up a small latency budget, for dramatically lower total cost and cost per one million tokens. We look at total cost and cost per one million tokens because step counts can vary, since this task is non-deterministic. These are two parallel processes, and input prompt caching is turned off. Now I'm going to fast-forward to the very end so we can compare costs and latency and see the trade-offs. > > Coming back to this, what we notice is that by giving up about fifteen extra seconds, roughly ten percent more latency, we were able to reduce total costs by about half, and cost per one million tokens by slightly more. There is a difference in step count, but generally speaking this is what you see from FlexInference: dramatically lower costs for a slight increase in latency. Thank you. Seven more workloads and the harness behind all ten live in [flexinference-demos](https://github.com/FlexInference/flexinference-demos). # Errors Source: https://docs.flexinference.com/errors Every error carries a code. Search this page for yours. Seeing 5xx errors or timeouts? Check [status.flexinference.com](https://status.flexinference.com) first. ## Find your code | Class | What it means | Retry the same request? | | - | - | - | | [validation](#validation) | Something in the request is wrong. | No | | [authentication](#authentication) | A key is missing, wrong, or rejected. | No | | [permission](#permission) | The key is fine. This request isn't allowed. | No | | [billing](#billing) | Your balance ran out. | No | | [quota](#quota) | You hit a rate, concurrency, or spend ceiling. | Yes, after a wait | | [capability](#capability) | This model or route can't do what you asked. | No | | [upstream](#upstream) | The fault is between us and the provider. | Yes | | [internal](#internal) | The fault is on our side. | Yes | | [canceled](#canceled) | You went away before the response finished. | No | Every error body carries the same machine-readable block, described in [the error body](#the-error-body). One case returns `200` with the failure inside the body. See [a stream that fails after it starts](#a-stream-that-fails-after-it-starts). ## validation Something in the request is wrong. Fix it and resend. | Code | Status | What it means and what to do | | - | - | - | | `invalid_json` | `400` | The body isn't valid JSON. The usual cause is a trailing comma or an unquoted key. | | `invalid_body` | `400` | The body parsed, but it isn't a JSON object. Wrap your fields in one `{...}`. | | `missing_model` | `400` | The `model` field is missing, empty, or not a string. Send something like `"model": "gpt-5.5"`. | | `missing_start_within` | `400` | The request has no `start_within`, and your key carries no default for it. It sets how long you'll wait for the request to start. Use `default`, `priority`, `auto`, or a duration like `00h-00m-30s`. | | `invalid_start_within` | `400` | `start_within` isn't one of the four accepted forms, or the duration is outside 5 to 600 seconds. `"00h-00m-30s"` is thirty seconds; `"default"` skips the race. | | `invalid_stream` | `400` | `stream` isn't a boolean. Send `"stream": true` or leave it out. | | `invalid_retry` | `400` | `retry` is malformed. It's an object like `{"count": 2}`. `count` is 1 to 5 and sets how many times we re-hit the tier on a transient 429 or 5xx. Optional: `backoff` (`"exponential"` or `"linear"`) and `jitter` (boolean). `error.message` names the exact fault. | | `invalid_provider_chain` | `400` | The `provider` array is empty, too long, or holds a duplicate or unknown name. Valid names are `openai`, `anthropic`, `google`, `vertex`, `bedrock`, `foundry`, `cloudflare`, and `deepinfra`. Element 0 runs first and the rest are fallbacks. Drop the field for the model's native route. | | `service_tier_not_allowed` | `400` | The request set `service_tier`. We set the tier from `start_within`, so remove `service_tier` and say it there instead. | | `invalid_decision_request` | `400` | A decision request breaks a rule of its own format. The message names the field. The usual causes are a missing `state` or `input`, a question count outside the range, two questions with one name, or a choice with `true` and `"true"` as two options. See [decision models](/decision-models). | | `key_default_not_applicable` | `400` | Your request left a field out, our key default filled it in, and validation refused the combination. The message names the field and the value. Send the field in the body (the body always wins), or edit the key defaults under API -> FlexInference keys. | | `request_too_large` | `413` | The body is over 50 MB, and the usual cause is a large inline base64 file. Shrink it, or point to a hosted URL. | | `model_not_found` | `404` | You asked `GET /v1/models/{id}` for an id we don't list for your key. Call `GET /v1/models` to see your ids. | | `previous_response_not_found` | `404` | A continuation named a response id your organization has no record of. Chain only on an id we returned to you (on managed keys ours start with `resp_fx_`), copied exactly. Drop the field to start fresh. | | `unknown_url` | `404` | The path doesn't exist. Use `/v1/responses`, `/v1/chat/completions`, `/v1/interactions`, `/v1/messages`, `/v1beta/models/{model}:generateContent`, `/model/{modelId}/converse`, `/v1/decisions`, or `/v1/systemone`. Streaming siblings are `:streamGenerateContent?alt=sse` and `/converse-stream`. The catalog is `GET /v1/models`. | | `method_not_allowed` | `405` | The path exists but the method is wrong. Every serving endpoint takes `POST`. The model catalog is the one `GET`. | | `cloudflare_upstream_rejected` | `400` | Workers AI refused the request shape, and we pass its explanation through. The usual cause is a message order the chat template forbids, like a user turn right after a tool result. | ## authentication A key is missing, wrong, or refused. It's either your FlexInference key or a provider key you stored. | Code | Status | What it means and what to do | | - | - | - | | `missing_api_key` | `401` | The request has no `Authorization` header, or it isn't `Bearer `. | | `malformed_api_key` | `401` | The key isn't shaped like a FlexInference key (`flex_live_` plus 24 hex characters plus a 6-character checksum), so we didn't look it up. The usual cause is a truncated copy, a stray space or quote, or a key from another service. Copy it again. | | `invalid_api_key` | `401` | The key is shaped right but matches nothing on record. The usual cause is a regenerated or mistyped key. Copy the current one from API -> FlexInference keys. | | `revoked_api_key` | `401` | An org admin revoked this key, and revocation is permanent. Create a new key and send that. | | `key_record_unreadable` | `500` | We found your key's record and couldn't read it. Your key is fine; this is our fault. Retry in a few minutes, and contact support if it persists. | | `byok_key_undecryptable` | `500` | We couldn't decrypt a provider key your organization stored. Saving that provider key again under API -> Provider keys clears it. | | `no_byok_key` | `400` | Your organization stores no OpenAI key. Add one under API -> Provider keys. Every route you name in a `provider` chain needs its own key. | | `no_gemini_key` | `400` | Your organization stores no Gemini key, and the request named a `gemini-*` model. Add one under API -> Provider keys. | | `no_anthropic_key` | `400` | Your organization stores no Anthropic key, and the request named a `claude-*` model. Add one under API -> Provider keys. | | `no_bedrock_key` | `400` | Your organization stores no Bedrock key, and the `provider` chain names `bedrock`. Add one under API -> Provider keys. | | `no_vertex_key` | `400` | Your organization stores no Vertex key, and the chain names `vertex`. Vertex takes a Google express key, which starts with `AQ.`. Add it under API -> Provider keys. | | `no_foundry_key` | `400` | Your organization stores no Foundry key, and the chain names `foundry`. Add the Azure key and resource name under API -> Provider keys. | | `no_deepinfra_key` | `400` | Your organization stores no DeepInfra token, and the chain names `deepinfra`. Add it under API -> Provider keys. | | `no_cloudflare_key` | `400` | Your organization stores no Cloudflare key, and the request needs the `cloudflare` route. Add one under API -> Provider keys. | | `upstream_auth_failed` | `403` | The provider rejected the key your organization stored for it. Your FlexInference key is fine; that stored key expired or got revoked. Ask an org admin to update it under API -> Provider keys. `error.flexinference.provider` names the route. | ## permission Your key is valid, and this request still isn't allowed. Adding funds doesn't clear these. | Code | Status | What it means and what to do | | - | - | - | | `account_under_review` | `403` | A risk check paused managed access for your organization. Your own key routes keep working. Contact support. | | `payment_disputed` | `403` | A card payment was disputed, so serving stopped (own key routes too). Withdraw the dispute with your bank, or contact support. | | `moderation_blocked` | `403` | The moderation pre-pass called this request harmful. It only runs when your organization turns moderation on, or when the request sends `moderate: true`. Revise the prompt, or contact support if the flag is wrong. | | `bedrock_model_access_denied` | `403` | Amazon Bedrock refused the model for the AWS account behind your key. Grant the model in the Bedrock console under Model access. The newest Claude models also need [a one-time account setup](/backup-providers#claude-on-bedrock). | ## billing Your balance ran out. | Code | Status | What it means and what to do | | - | - | - | | `insufficient_balance` | `402` | Your managed balance no longer covers the request. Add funds on the [Billing](/billing) page and resend. | ## quota You hit a ceiling. The same request can succeed after a wait. | Code | Status | What it means and what to do | | - | - | - | | `rate_limit_exceeded` | `429` | Too many requests from your key, IP, or organization, or too many flex races in flight at once. Back off for the seconds in `Retry-After`. | | `spend_velocity_exceeded` | `429` | You hit your daily managed-spend limit. Wait for the UTC day to roll over, or ask an org admin to request a higher limit. | | `cloudflare_capacity` | `429` | Workers AI is at capacity. Nothing is wrong with your request. Wait briefly and resend, or try another open-source model. | | `race_budget_exhausted` | `429` | Your workspace opted out of the standard-rate fallback for Claude races, and the race budget has no margin left. Wait for the next recompute, or send `start_within: "default"` for a standard serve. | ## capability This model or route can't do what you asked. Something in the request has to change. | Code | Status | What it means and what to do | | - | - | - | | `unsupported_parameter` | `400` | A native field reached the wrong provider. Chat fields work on OpenAI models and Anthropic fields on Claude models, and each fails anywhere else. Drop the field named by `error.param`, or pick a model whose provider owns it. See [what passes through](/models#what-passes-through). | | `unsupported_value` | `400` | Chat Completions `n` was set to something other than `1`. We always produce one generation. Send `"n": 1` or leave it out. | | `unsupported_tool` | `400` | The `tools` array holds a built-in tool that makes the model emit something other than text (currently `image_generation`). We serve text only. Function tools and `web_search` work fine. | | `unsupported_media_type` | `400` | An attached file uses a media type the model can't read. Images must be JPEG, PNG, GIF, or WebP. Documents must be PDF. `error.param` is `image` or `input_file`. | | `unsupported_generation_config` | `400` | A `generation_config.*` field with no mapping was sent to a non-Gemini model on `/v1/interactions`. Remove it, or target a Gemini model. | | `gemini_search_function_conflict` | `400` | Gemini forbids a built-in tool and function tools in the same request. Send one or the other, or split them across two requests. | | `auto_unsupported_for_gemini` | `400` | You sent `start_within: "auto"` to a Gemini model, and Gemini has no auto tier. Use `default`, `priority`, or a duration. | | `model_not_carried` | `400` | We don't carry this model, on your own keys or managed. Check the name against `GET /v1/models`. | | `model_surface_mismatch` | `400` | You sent a decision model to a text endpoint, or a text model to a decision endpoint. Decision models go to `/v1/decisions` or `/v1/systemone`. `GET /v1/models` marks each one with a `decisions` block. | | `flex_unsupported_for_anthropic` | `400` | You sent a duration `start_within` to a `claude-*` model on your own Anthropic key. We race Claude's cheaper tier on managed keys only. Use `default`, `priority`, or `auto`, or switch Anthropic to managed. See [Flex racing with Claude models](/deadline-routing#flex-racing-with-claude-models). | | `flex_anthropic_streaming_unsupported` | `400` | You sent a duration `start_within` plus `stream: true` to a `claude-*` model. Claude's cheaper tier returns one complete message, so a win can't stream. Drop `stream` to race, or keep streaming with a tier. | | `flex_anthropic_deadline_too_short` | `400` | You sent a duration under 180 seconds to a `claude-*` model, and a Claude race needs at least three minutes. Ask for `00h-03m-00s` or more, or send a tier. | | `flex_model_not_capable` | `400` | You sent a duration `start_within` to an OpenAI or Gemini model that isn't on the flex list, or to a decision endpoint, where nothing races. Use a tier, or a [flex-capable model](/models#models-that-run-the-flex-race). | | `flex_unsupported_on_cloud` | `400` | You sent a duration `start_within` with a cloud route first in the chain, and `vertex`, `bedrock`, and `foundry` have no flex tier to race. Use `"start_within": "default"`, or put `openai` or `google` first. | | `tier_unsupported_on_cloud` | `400` | You sent `priority` or `auto` with a cloud route first in the chain, and cloud routes serve the provider default tier only. Use `"start_within": "default"`, or put a direct route first. | | `tier_unsupported_on_managed` | `400` | You sent `priority` or `auto` on managed keys, and managed serving offers `default` or a flex duration. Switch that provider to your own key to use the premium tiers. | | `tier_unsupported_on_decisions` | `400` | You sent `priority` or `auto` to a decision endpoint, and decision models serve the provider default tier only. Use `"start_within": "default"`. | | `decisions_byok_only` | `400` | Your organization serves this route on managed keys, and decision models run on your own provider keys only. Switch the route to your own key, or name a route you serve on your own key in `provider`. | | `decision_translation_unsupported` | `400` | The request is valid in its own format, but the model speaks the other one and part of it doesn't translate. The usual causes are images, a field the other format has no equivalent for, or a choice with one option sent to an OpenAI model. Send it to the endpoint in the model's own format. | | `provider_model_mismatch` | `400` | A route in the `provider` chain can't serve this model. `openai` and `foundry` serve GPT models, `google` and `vertex` serve Gemini, `anthropic` and `bedrock` serve Claude. Remove the route that doesn't match. | | `bedrock_model_unavailable` | `400` | Amazon Bedrock has no id for this model, so the `bedrock` route can't run it. Remove `bedrock` from the chain, or use a model it carries. | | `model_not_priced_for_managed` | `400` | A managed request named a model with no published rate. Pick a priced model, or switch the provider to your own key. | | `managed_family_restricted` | `400` | Managed Bedrock serves Claude models only and managed Vertex serves Gemini only. Pick a model in that route's family, another route, or your own key. | | `cloudflare_upstream_client_error` | `400` | Workers AI refused the request and the cause is permanent (a wrong request, an unknown model, or an oversized body). Fix the request, or use a direct provider. | | `foundry_model_unavailable` | `404` | Azure AI Foundry doesn't carry this model on your resource (its instant-access catalog is a subset of GPT models that changes over time). Remove `foundry` from `provider`, pick a model it carries, or create a deployment on your Azure resource. | ## upstream The fault is between us and the provider. Nothing is wrong with your request. | Code | Status | What it means and what to do | | - | - | - | | `upstream_unavailable` | `502` | We couldn't open a connection to the provider. Retry once. If one model keeps failing, the provider may be down, so try another model. | | `upstream_stream_failed` | `502` | The provider started a response and then its stream stopped, with no completion and no error to pass through. Retry once. On a stream that had already started, this arrives in the body. | | `upstream_error` | `502` | The provider answered HTTP 500 with no error code. `error.message` keeps the provider's own text. Retry once. | | `stream_idle_timeout` | `504` | The provider stopped feeding an open stream. Whatever text you received is the whole answer. Retry once. | | `upstream_timeout` | `504` | The provider didn't start responding before our timeout. It's almost always a passing slowdown. Retry once. | | `all_routes_failed` | `502` | Every route in your `provider` chain failed transiently (a 429, a 5xx, or a timeout), so no fallback was left. Retry once. If it persists, cut the chain down to healthy routes. | | `cloudflare_upstream_error` | `502` | Workers AI reported an internal error. The fault is on Cloudflare's side. Retry once, or try another open-source model. | | `managed_upstream_unavailable` | `502` | Our own managed connection to the provider is briefly unavailable. The failing key is ours, not yours. Retry shortly, and contact support if it keeps happening. | ## internal The fault is on our side. A repeat is worth reporting. | Code | Status | What it means and what to do | | - | - | - | | `internal_error` | `500` | Your request was valid and we still failed. Retry once, and contact support with the approximate time if it persists. | | `limits_unavailable` | `503` | `GET /v1/limits` couldn't read your records. Serving is unaffected. Retry in a few seconds. | | `server_misconfigured` | `500` | Our deployment is misconfigured. Retry shortly, and contact support if it persists. | | `pii_masking_failed` | `500` | PII masking failed, so we stopped the request. Retry once, or send `pii_mask: false` to run this one request unmasked. | ## canceled You went away before the response finished. | Code | Status | What it means and what to do | | - | - | - | | `client_closed_request` | `499` | Your client disconnected first (a closed tab, a cancelled fetch, or a client-side timeout). If you didn't mean to cancel, raise your client timeout. A flex request can take up to 10 minutes. | > [!NOTE] > > The `provider` array pins your route. `openai`, `anthropic`, `google`, > `cloudflare`, and `deepinfra` are direct routes. `vertex`, `bedrock`, and > `foundry` run the same models through Google Vertex AI, Amazon Bedrock, and > Azure AI Foundry on your own cloud key. See [backup > providers](/backup-providers). ## The error body Errors come in the shape of the endpoint you called. The OpenAI endpoints, `/v1/decisions` included, return the OpenAI shape and `/v1/messages` returns the Anthropic shape. The Google paths return the Google shape, the Converse paths return the AWS shape, and `/v1/systemone` returns the System One shape. Provider errors follow the same rule. ```json OpenAI shape (/v1/responses, /v1/chat/completions) theme={null} { "error": { "message": "The upstream provider rejected the API key your organization stored for it ...", "type": "permission_error", "code": "upstream_auth_failed", "param": null, "doc_url": "https://docs.flexinference.com/errors#upstream_auth_failed", "flexinference": { "code": "upstream_auth_failed", "class": "authentication", "origin": "provider", "status": 403, "provider": "openai", "provider_code": null, "retryable": false, "doc_url": "https://docs.flexinference.com/errors#upstream_auth_failed" } } } ``` ```json Anthropic shape (/v1/messages) theme={null} { "type": "error", "error": { "type": "authentication_error", "message": "...", "flexinference": { "...": "..." } } } ``` ```json Google shape (/v1/interactions, :generateContent) theme={null} { "error": { "code": 401, "message": "...", "status": "UNAUTHENTICATED", "flexinference": { "...": "..." } } } ``` ```json AWS shape (/model/{modelId}/converse) theme={null} { "message": "...", "flexinference": { "...": "..." } } ``` ```json System One shape (/v1/systemone) theme={null} { "detail": "...", "param": "questions", "flexinference": { "...": "..." } } ``` On the OpenAI shape, `type` uses the stock OpenAI categories plus two of ours. `billing_error` means a managed balance ran out, and `flexinference_error` means an internal or upstream fault. The AWS shape has no `error` wrapper. Its type goes in the `x-amzn-errortype` header. ### The flexinference block Every error carries one `flexinference` object, the same on all eight endpoints. | Field | Meaning | | - | - | | `code` | Our code for this failure, from the tables above. `null` when a provider error passed through. | | `class` | Which of the nine groups above this failure falls in. | | `origin` | `flexinference` when we made the decision. `provider` when the provider did. | | `status` | The status this failure carries. It matches the HTTP status, except on a stream that had already started. | | `provider` | Which provider or route the failure is about, such as `openai` or `bedrock`. `null` when no single route applies. | | `provider_code` | Whatever code the provider sent, when we passed one through. | | `retryable` | `true` when the same request could succeed later. `false` when something has to change first. | | `doc_url` | Deep link to this code's row above. `null` for a provider error. | > [!TIP] > > Branch on `error.flexinference.code` (or `flexinference.code` on the AWS and > System One shapes). It's the same value on all eight endpoints, while the > stock `error.code` exists on the OpenAI shape only. Treat an unknown code as > an ordinary error of its class. ## A stream that fails after it starts A streaming response returns `200` as soon as the first bytes leave. HTTP gives no way to take that back. So a failure after that point reaches you in the body, not in the status. The stream ends with a terminal error event in your endpoint's shape. It carries the same `flexinference` block a refused request has. Its `status` field says what the failure would have returned before the stream started. A streamed generateContent call ends with the Google error body as its last chunk. A `converse-stream` call ends with an event-stream exception frame (what the AWS SDKs raise on). Your SDK raises on that event. None of them hand you the `flexinference` block though, so read the raw event to get the code. The chunks that arrived before the raise are the whole answer. The dashboard logs the request as failed with this code, not as the `200` that went out first. ## Provider errors A provider error keeps its status and message and comes back in your endpoint's shape. Call `/v1/messages` with an OpenAI model and its error comes back Anthropic-shaped. A passed-through provider error carries the block too, with `origin` reading `provider` and their code in `provider_code`. ## Flex outcome headers Successful `200` responses carry these on every endpoint, streaming or not. | Header | Meaning | | - | - | | `x-flexinference-flex-requested` | `true` when you sent a duration `start_within`; `false` on `default`, `priority`, or `auto`. | | `x-flexinference-flex-applied` | `true` only when the flex tier served the response. | | `x-flexinference-flex-reason` | Machine-readable outcome. Values below. | | `x-flexinference-provider-surface` | Which provider wire ran it: `openai.responses`, `openai.chat`, `gemini.interactions`, or `anthropic.messages`. Not always your endpoint (a `/v1/chat/completions` call usually runs on `openai.responses`). | | `x-flexinference-cost` | Provider cost of this serve as a micro-USD integer, the same value as `usage.cost.total_micro_usd`. Non-streaming only, and only when the serve can be priced. A streamed response reports cost on its usage frame instead, with `include_cost: true`. See [cost inside a stream](/billing#cost-inside-a-stream). | `x-flexinference-flex-reason` values: | Reason | Meaning | | - | - | | `not_requested` | You sent `default`, `priority`, or `auto`, so there was no race. | | `flex_committed` | The discounted tier served it. The body shows `service_tier: "flex"`, or `"batch"` on a Claude win. | | `flex_lost_race` | You sent a duration and the discounted tier didn't make it, so standard served at the standard price. | > [!NOTE] > > A duration that can't race at all returns `400` instead: > [`flex_model_not_capable`](#flex_model_not_capable) off the flex list, > [`flex_unsupported_for_anthropic`](#flex_unsupported_for_anthropic) on your > own Anthropic key, > [`flex_anthropic_streaming_unsupported`](#flex_anthropic_streaming_unsupported) > with `stream: true`, and > [`flex_anthropic_deadline_too_short`](#flex_anthropic_deadline_too_short) > under 180 seconds. ## Handling errors in code OpenAI SDKs raise on non-2xx responses and attach the parsed body. ```python Python theme={null} from openai import APIStatusError try: resp = client.responses.create( model="gpt-5.5", input="hi", extra_body={"start_within": "00h-00m-30s"}, ) except APIStatusError as e: code = (e.body or {}).get("error", {}).get("flexinference", {}).get("code") if code == "no_byok_key": print("Add your OpenAI key in the dashboard.") else: raise ``` ```typescript Node theme={null} import OpenAI from "openai"; try { await client.responses.create({ model: "gpt-5.5", input: "hi", start_within: "00h-00m-30s", } as any); } catch (e) { if (e instanceof OpenAI.APIError && e.code === "no_byok_key") { console.log("Add your OpenAI key in the dashboard."); } else { throw e; } } ``` # What is FlexInference Source: https://docs.flexinference.com/index You set a time window, and we find you cheaper inference inside it. FlexInference is a deadline aware LLM router. You set a time window (5 seconds to 10 minutes for most models) and we find you cheaper inference. We can hunt for cheaper inference across a bunch of different providers. This saves about 48 percent for roughly 20 percent more latency. We also work on default and auto requests. We provide BYOK support for free. We also have trace storage, PII masking, and moderation all behind a single parameter. We are currently working on building an A/B testing platform so you can test out different models. We also support cheap inference search for tools like Codex, OpenClaw, Cursor, and more. Our goal is to make working with AI as easy and affordable as possible. ## How does it work? When a provider offers Flex API support we first check if your request can start in that time using Flex. If it can't we cancel the Flex request and escalate up to a default request. This means you don't get charged 1.5x, and always pay either 50% or 100%. We have about a 96 percent hit rate, which is why we can usually save about 48 percent. When providers don't support Flex, they usually support Batch. With batch inference it can take up to 24 hours. However, that's not always the case. We have built a model that forecasts compute usage for all these providers. When you send us a request we check the time window you set, model, time of day, and a few other parameters. If based on those our model says that you could get your request within time then we run your request. If not we send out a default request. If we do send that request and it doesn't fulfill in time then we send out a default request. This offering is only behind Managed Keys. It's because it requires eating the cost of failed attempts about 4 percent of the time. With managed keys though you never pay that yourself, we take the hit for you. This allows managed keys users to get flex race support far more often and no double charges. ## How much do you charge? For "Bring Your Own Key" we are free. We support Gemini and OpenAI model flex race support. We also have default and priority support. Support across Gemini, OpenAI, Anthropic, and Workers AI open source models. For managed keys we charge 10% and offer Anthropic flex race too. We also have a higher hit rate for flex in managed due to cross provider search. We also provide PII masking, moderation, and trace storage through managed keys. When you add cash through Managed Keys, it isn't stored as credits. Instead you can refund all your cash back (except the fee). > [card] [Quickstart](/quickstart) > > One working request, in about a minute. > [card] [Flex Race Routing](/deadline-routing) > > What to set your time limit to, and what happens when it runs out. # Input Prompt Moderation Source: https://docs.flexinference.com/input-prompt-moderation We can check your prompt for harmful content before it reaches the provider. A blocked prompt returns `403 moderation_blocked` and reaches no provider. ```json theme={null} { "moderate": true } ``` Moderation runs on Managed Keys and is off by default. If your request sets `moderate` we follow it. If it doesn't, we follow your organization's default. If neither is set, moderation is off. # MCP Server Source: https://docs.flexinference.com/mcp-server Our MCP server lets coding agents search the docs and read your account. It's a remote HTTP server at: ``` https://mcp.flexinference.com/mcp ``` ## Connecting ```json mcp.json theme={null} { "mcpServers": { "flexinference": { "type": "http", "url": "https://mcp.flexinference.com/mcp" } } } ``` ```bash Claude Code theme={null} claude mcp add --transport http flexinference https://mcp.flexinference.com/mcp ``` The first account call opens a browser for dashboard login and shows the requested scopes, which you can approve or narrow. Docs tools need no login. ## Tools without login * `search_docs` searches the docs and the full error catalog, and returns the best matches with links. * `get_error_reference` looks up what an error code means and how to fix it. Leave `code` out to list every code. * `run_flex_demo` sends one prompt twice on the same model, once through the Flex Race and once as a default request, and returns both answers with the billed comparison. One run per IP address per day. * `compare_usage_export` prices a usage CSV export (OpenAI platform, Anthropic console, or OpenRouter) at each model's measured rate and returns the per-model breakdown. Neither tool stores what you send. ## Tools behind login Each one takes one scope, and each one only reads. * `get_usage_summary` (`usage:read`) reads your usage and savings by model. * `list_api_keys` (`keys:read`) lists your keys by name, last 4, and created date. Never the full key. * `get_byok_status` (`byok:status`) reads which providers have a key on file, as a yes or no. Never the key. * `get_billing_status` (`billing:read`) reads your plan and balance. Never the full card number. No tool here creates or takes a key. Keys live in the [dashboard](https://www.flexinference.com/dashboard). # Models Available Source: https://docs.flexinference.com/models `GET /v1/models` lists the model families we serve for your key. Send a model by its family alias, such as `gpt-5.5` or `gemini-3.5-flash`. A dated snapshot of an alias works too. Any other name returns `400 model_not_carried` before the request reaches your provider. ## Every endpoint reaches every model * `POST /v1/responses` speaks OpenAI Responses. * `POST /v1/chat/completions` speaks OpenAI Chat Completions. * `POST /v1/interactions` speaks Google Interactions. * `POST /v1/messages` speaks Anthropic Messages. * `POST /v1beta/models/{model}:generateContent` speaks Google GenerateContent. * `POST /model/{modelId}/converse` speaks Amazon Bedrock Converse. We translate the shape you send into the shape the provider wants. So you can ask a Claude model in the OpenAI shape, or a GPT model in the Anthropic shape. What comes back is the provider's own body, in the shape of the endpoint you called. ## Decision models `gpt-6-luna`, `microsoft-decision-1`, `clef`, and `clef-flash` answer named questions with probabilities instead of writing text. They run on `POST /v1/decisions` and `POST /v1/systemone`, on your own keys only, and they never race. See [Decision models](/decision-models). The text endpoints above refuse the last three with `400 model_surface_mismatch`, because they write no text. ## Models that run the Flex Race Only OpenAI and Gemini sell a flex tier we race, and only on some models. * OpenAI: `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-5.6`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-5.5`, `gpt-5.5-pro`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.4-pro`, `gpt-5.2`, `gpt-5.1`, `gpt-5`, `gpt-5-mini`, `gpt-5-nano`, `o3`, `o4-mini` * Gemini: `gemini-4-argon`, `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-3.1-pro-preview`, `gemini-3.1-flash-lite`, `gemini-3-flash-preview`, `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite` A duration `start_within` on any other model returns `400 flex_model_not_capable`. Claude is the exception. Anthropic publishes no flex tier, and Claude still races a cheaper tier of its own on managed keys, without streaming, inside a window of three to ten minutes. See [Flex Racing with Claude models](/deadline-routing#flex-racing-with-claude-models). Gemini has no `auto` tier, so send `default` for Gemini's standard tier. ## Asking the API `GET /v1/models` returns the catalog for your key, and `GET /v1/models/{id}` returns one entry. Both are OpenAI-compatible, so the OpenAI SDK reads them with no changes. ```bash theme={null} curl https://api.flexinference.com/v1/models \ -H "Authorization: Bearer $FLEX_API_KEY" ``` Each entry is an OpenAI model object plus a `flexinference` block. `flex_race` says whether a duration runs the race on the model. `tiers` lists the tier names it serves for your key. `providers` lists the routes that run it, starting with its direct route. Every `claude-*` model reads `false` on `flex_race` and can still race, because a Claude race turns on your organization and your request, not on the model. `capabilities` answers the same questions for every route the model runs on, keyed by route name. Each entry covers the content parts it takes and the structured-output forms it accepts. It also says how the route handles a reasoning block. The answers differ by route on the same model. `claude-opus-4-8` takes a JSON schema on `anthropic` and refuses one on `bedrock`. Read `enforced_by` first. `flexinference` means we check the entry before we call the provider, so an `unsupported` is a 400 from us. `provider` means we forward your request and the provider decides. It also decides whether it runs the model. Read those entries as what we pass on, not as a promise. A decision model also carries a `decisions` block: its routes, its question limit, and its decision rate per route. A model with no text route lists empty `providers` and `tiers`. `pricing` lists what each route's provider charges for the model, in dollars per million tokens. `input` and `output` are always there, and `cache_read` and `cache_write` appear where the provider prices caching. `cache_write` is the provider's 5-minute cache write, and `cache_write_1h` is the 1-hour write where the route can bill it, which today is Claude on the `anthropic` route. We bill from the same numbers. A route with no entry has no published rate. ## Open-source models We run open-source families on Cloudflare Workers AI, inside the network at the edge. Their route is `cloudflare`, and they run at the standard tier, so send `default`. They do text, streaming, and function calling. * OpenAI: `gpt-oss-120b`, `gpt-oss-20b` * Meta: `llama-3.3-70b`, `llama-3.1-8b`, `llama-4-scout-17b-16e-instruct`, `llama-3.1-70b-instruct-fp8-fast`, `llama-3.1-8b-instruct-fp8`, `llama-3.2-1b-instruct`, `llama-3.2-3b-instruct`, `llama-3.2-11b-vision-instruct`, `llama-guard-3-8b` * Qwen: `qwen3-30b`, `qwen2.5-coder-32b-instruct`, `qwq-32b` * Mistral: `mistral-small-3.1`, `mistral-7b-instruct-v0.1` * Moonshot AI: `kimi-k2.5`, `kimi-k2.6`, `kimi-k2.7-code` * Z.ai: `glm-4.7-flash`, `glm-5.2` * Google: `gemma-4-26b-a4b-it` * DeepSeek: `deepseek-r1-distill-qwen-32b` * IBM: `granite-4.0-h-micro` * NVIDIA: `nemotron-3-120b-a12b` * AI Singapore: `gemma-sea-lion-v4-27b-it` Three of them read images: `llama-3.2-11b-vision-instruct`, `llama-4-scout-17b-16e-instruct`, and `gemma-4-26b-a4b-it`. Send an image to any other family and the request fails by name rather than dropping it. We also run open-source families on DeepInfra. Their route is `deepinfra`, and like Workers AI they run at the standard tier, so send `default`. You can name an open-source model three ways, so code you already wrote keeps working. Our name, the provider's model name, or the provider's full id all reach the same model: ```json theme={null} { "model": "deepseek-v3" } { "model": "DeepSeek-V3" } { "model": "deepseek-ai/DeepSeek-V3" } ``` Case doesn't matter. We answer with our name, so your logs and your bill show one name per model. Three families run on both. `gemma-4-26b-a4b-it`, `llama-4-scout-17b-16e-instruct`, and `kimi-k2.6` go to Workers AI unless you ask for DeepInfra: ```json theme={null} { "model": "llama-4-scout-17b-16e-instruct", "provider": ["deepinfra", "cloudflare"] } ``` That order tries DeepInfra first and falls back to Workers AI. Ask for `["cloudflare"]` and you get the edge instead. ## What passes through Tool calling, structured outputs, vision, and reasoning pass through to the provider you chose. Use that provider's own fields for them. Don't send `service_tier`. We set the tier from `start_within`, so a request carrying its own returns `400 service_tier_not_allowed`. A native field works only on the provider that owns it. Send `top_k` to a Claude model and it passes through. Send it to a GPT or Gemini model and you get `400 unsupported_parameter`, never a quiet loss. # OpenClaw Source: https://docs.flexinference.com/openclaw Point OpenClaw at FlexInference through its custom provider onboarding or its config file. OpenClaw reaches any OpenAI-compatible endpoint through a custom provider. Onboarding writes the entry for you, and the config file holds it afterwards. OpenClaw has no per-request deadline field of its own, so the deadline goes on an [agent key](/agent-keys). ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure OpenClaw to send its requests to FlexInference through a custom provider. Use the OpenClaw CLI, not hand-edited JSON, so every write is schema-validated. > > You will never see or handle my API key. OpenClaw will read it from the `FLEXINFERENCE_API_KEY` environment variable through a secret reference, and I export that myself. Do not ask me for the key, do not pass it on any command line, and do not read it from my environment. > > Ask whether to use my default OpenClaw profile or a separate one. A separate profile isolates config, state, gateway port, and workspace, and is the safe way to try this. Prefix every command with `--profile flex` if I choose one. > > 1. Confirm which config file is active with `openclaw config file`. > > 2. Tell me to export the key first, and stop until I confirm. Print this line; do not run it and do not ask for the value: > > export FLEXINFERENCE_API_KEY= > > 3. Write the provider entry. It carries no credential. The model row is required, because OpenClaw refuses a third-party provider that declares no `models`; step 5 replaces it with the full catalog: > > openclaw config set models.providers.flexinference --merge --strict-json '{"baseUrl":"https://api.flexinference.com/v1","api":"openai-completions","models":[{"id":"gpt-5.6-sol","name":"GPT-5.6 Sol","compat":{"supportsUsageInStreaming":true}}]}' > > 4. Declare an environment secrets provider, then point the provider's apiKey at it. Both commands pass only the VARIABLE NAME, never the value: > > openclaw config set secrets.providers.default \ > --provider-source env --provider-allowlist FLEXINFERENCE_API_KEY > > openclaw config set models.providers.flexinference.apiKey \ > --ref-provider default --ref-source env --ref-id FLEXINFERENCE_API_KEY > > 5. Fill the model list from the live FlexInference catalog rather than by hand: > > curl -s https://api.flexinference.com/v1/models \ > -H "Authorization: Bearer $FLEXINFERENCE_API_KEY" \ > | jq '{models:{providers:{flexinference:{models: > [.data[] | {id, name: .id, compat: {supportsUsageInStreaming: true}}]}}}}' \ > | openclaw config patch --stdin > > Run every write with `--dry-run` first and show me the diff before applying it. > > 6. Verify with `openclaw models list --provider flexinference`, then run `openclaw security audit`. > > Rules that matter, do not deviate: > - Never pass my key as an argument to an `openclaw` command, and never write it into a config file. `openclaw onboard --custom-api-key` does both, which is why step 4 uses a reference instead. > - Step 5 is the one place the key expands, into curl's `-H` argument, where a same-user process can read it. That is a deliberate trade for a single catalog read. Do not extend it to any other command. > - The provider id must be `flexinference` in every command. If an earlier setup derived `custom-api-flexinference-com` from the host, tell me, and use that id consistently instead of creating a second provider. > - `api` must be `openai-completions`. That is the only adapter FlexInference's Chat Completions surface works with here. > - The base URL must end in `/v1`. > - You MUST list models explicitly. OpenClaw only lets its own built-in provider ids omit `models`, and it will never call `GET /v1/models` for a provider defined in config. Model discovery is a plugin capability and does not apply here. > - Every model row needs `compat: { supportsUsageInStreaming: true }`. OpenClaw makes streaming usage opt-in for third-party endpoints, and without it every streamed turn reports zero tokens and no cost. > - Leave `"mode": "merge"` alone so my existing providers survive. > - Step 4 resolves the reference at write time, so it fails if I have not exported the variable yet. That failure is expected, not a reason to fall back to a literal key. > - FlexInference's catalog publishes no context window or token ceiling, so generated rows carry neither. Do not invent values; leave them out unless I give you numbers. > > Report what you changed and which config file you wrote. > ``` ## Onboard a custom provider 1. Start the guided setup. ```bash theme={null} openclaw onboard ``` 2. Pick the custom provider option when it asks about auth. That is `custom-api-key`. 3. Enter the router as the base URL, including the `/v1` suffix. ```text theme={null} https://api.flexinference.com/v1 ``` 4. Paste your agent key. 5. Leave the compatibility mode on `openai`. That is our Chat Completions surface. 6. Enter a model id we run, such as `gpt-5.6-sol`. The prompt never puts your key on a command line, which is why it's the path shown here. `openclaw onboard --non-interactive` exists too, but its `custom-api-key` auth mode reads the credential from `--custom-api-key`, so the secret ends up in your shell history and in process arguments. Script the setup with [config commands and a secret reference](#keep-the-key-out-of-the-config-file) instead, which is the same result without the exposure. Whichever route you take, set the provider id yourself: ```bash theme={null} openclaw config set models.providers.flexinference --merge --strict-json \ '{"baseUrl":"https://api.flexinference.com/v1","api":"openai-completions","models":[{"id":"gpt-5.6-sol","name":"GPT-5.6 Sol","compat":{"supportsUsageInStreaming":true}}]}' ``` Left to itself, OpenClaw derives the id from the host and ends up with `custom-api-flexinference-com`, and every later command on this page would need that name instead. The write includes a model row because it has to. OpenClaw refuses a third-party provider that declares no `models`, so a `baseUrl`-only write fails schema validation. Replace the whole row in the next section. The compatibility mode maps to `api`. `openai` writes `openai-completions`, which is the one our Chat Completions endpoint works with. The other choices are `openai-responses` and `anthropic`. ## The config file Onboarding writes into `~/.openclaw/openclaw.json` under `models.providers`. Print the path OpenClaw is using with `openclaw config file`. ```json theme={null} { "models": { "mode": "merge", "providers": { "flexinference": { "baseUrl": "https://api.flexinference.com/v1", "api": "openai-completions", "apiKey": { "source": "env", "provider": "default", "id": "FLEXINFERENCE_API_KEY" }, "models": [ { "id": "gpt-5.6-sol", "name": "GPT-5.6 Sol", "contextWindow": 400000, "maxTokens": 128000, "input": ["text", "image"], "compat": { "supportsUsageInStreaming": true } } ] } } } } ``` `"mode": "merge"` keeps your built-in providers and adds this one beside them. `api` must be `openai-completions`. The onboarding `openai` compatibility mode writes exactly that. `apiKey` takes a plain string too, which is what onboarding writes. The reference shown here keeps the secret out of the file. See [keep the key out of the config file](#keep-the-key-out-of-the-config-file). **List your models yourself.** Only OpenClaw's built-in provider ids may leave `models` out. A third-party id must declare both `baseUrl` and `models`, so add a row per model you want in the picker. **Set `compat.supportsUsageInStreaming`.** OpenClaw makes streaming usage opt-in for a third-party endpoint, because some servers refuse it. Without this flag we never get the request for a usage frame, so every streamed turn reports zero tokens and no cost. ## Fill the model list from our catalog OpenClaw won't call `GET /v1/models` for a provider you define in config. Model discovery is a plugin capability, and the bundled plugins that have it are the only ones that use it. A config-defined provider reads its `models` array and nothing else. Generate that array from our catalog instead, and write it in one command. ```bash theme={null} export FLEXINFERENCE_API_KEY= curl -s https://api.flexinference.com/v1/models \ -H "Authorization: Bearer $FLEXINFERENCE_API_KEY" \ | jq '{models:{providers:{flexinference:{models: [.data[] | {id, name: .id, compat: {supportsUsageInStreaming: true}}]}}}}' \ | openclaw config patch --stdin ``` `config patch` merges objects and replaces arrays, so this swaps the model list and leaves `baseUrl` and `apiKey` untouched. Add `--dry-run` to see the write first. Keep only the models that race the cheaper tier by filtering on the catalog's own flag. ```bash theme={null} jq '[.data[] | select(.flexinference.flex_race) | {id, name: .id}]' ``` Our catalog publishes no context window and no token ceiling, so rows made this way have neither. Add `contextWindow` and `maxTokens` yourself where OpenClaw's defaults don't fit the model. Re-run the command whenever our catalog changes. Check the result: ```bash theme={null} openclaw models list --provider flexinference ``` ## Global config and profiles OpenClaw keeps one config per profile, not one per folder. The working directory never changes which file it reads. | Scope | Config path | How to select it | | - | - | - | | Default | `~/.openclaw/openclaw.json` | the default | | Named | `~/.openclaw-/` | `--profile ` | | Dev | `~/.openclaw-dev/` | `--dev` | | Explicit | any path | `OPENCLAW_CONFIG_PATH` | Use a named profile to try FlexInference without touching your usual setup. ```bash theme={null} openclaw --profile flex onboard ``` A profile isolates state as well as config, so its gateway port and workspace are separate too. ## Keep the key out of the config file Onboarding writes the key into `openclaw.json` in plain text. Set `apiKey` to a secret reference instead, and the config stores the variable's name rather than its value. 1. Export the key in the shell you will run these commands from. ```bash theme={null} export FLEXINFERENCE_API_KEY= ``` 2. Declare an environment secrets provider and allow that one variable. ```bash theme={null} openclaw config set secrets.providers.default \ --provider-source env --provider-allowlist FLEXINFERENCE_API_KEY ``` 3. Point the provider's `apiKey` at it. ```bash theme={null} openclaw config set models.providers.flexinference.apiKey \ --ref-provider default --ref-source env --ref-id FLEXINFERENCE_API_KEY ``` The config then holds `{"source": "env", "provider": "default", "id": "FLEXINFERENCE_API_KEY"}` and no secret. The key never reaches a command line either, because step 3 passes only the variable's name. OpenClaw resolves the reference when you run step 3, so export the variable first. A missing or empty variable fails the write with `SecretRefResolutionError` rather than storing something broken. Add `--dry-run` to check without writing. Check what's exposed with the built-in audit. ```bash theme={null} openclaw security audit ``` ## Troubleshooting **The model picker is short, or a model is missing.** A config-defined provider never calls `GET /v1/models`, so it shows only the rows you wrote. Regenerate the list from our catalog. **Turns report zero tokens and no cost.** OpenClaw didn't ask us for streaming usage, so we sent no usage frame. Set `compat.supportsUsageInStreaming` to `true` on each model row. **A model id is refused.** Rows you wrote by hand can drift from what we run, since the `id` goes out exactly as written. Regenerate the list from our catalog rather than editing ids. **Config edits don't take effect.** The gateway holds the old config. Restart it, and confirm you edited the file that `openclaw config file` prints. Anything not specific to OpenClaw is on [agent keys](/agent-keys#troubleshooting). # OpenCode Source: https://docs.flexinference.com/opencode Point OpenCode at FlexInference with config only. OpenCode reads a provider entry out of a JSON file, with no source change and no fork. OpenCode can set `start_within` in config, so an [agent key](/agent-keys) is optional here. The key is still the simpler path, because it changes without a restart. ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure OpenCode to send its requests to FlexInference. This is config only: no source change, no fork, no patch. > > You will never see or handle my API key. The provider entry stores only the `{env:FLEXINFERENCE_API_KEY}` template, and I export the value myself. Do not ask me for the key, and do not read it from my environment. > > Ask me whether this should apply to every project or one project, then write the provider entry to the matching file. Global is `~/.config/opencode/opencode.json`. Per project is `opencode.json` in the project root. Project config wins over global. Create the file if it does not exist, and merge into it rather than overwriting anything already there. > > The entry: > > { > "$schema": "https://opencode.ai/config.json", > "model": "flexinference/gpt-5.6-sol", > "provider": { > "flexinference": { > "name": "FlexInference", > "env": ["FLEXINFERENCE_API_KEY"], > "npm": "@ai-sdk/openai-compatible", > "options": { > "apiKey": "{env:FLEXINFERENCE_API_KEY}", > "baseURL": "https://api.flexinference.com/v1" > }, > "models": { > "gpt-5.6-sol": { > "name": "GPT-5.6 Sol", > "reasoning": true, > "tool_call": true, > "limit": { "context": 400000, "output": 128000 } > } > } > } > } > } > > Then print this line for me to run in the shell I start OpenCode from. Do not run it and do not ask for the value: > > export FLEXINFERENCE_API_KEY= > > Rules that matter, do not deviate: > - Keep `options.apiKey` as the literal `{env:FLEXINFERENCE_API_KEY}` template. Never inline my key. > - The top-level `model` field is what selects the provider. Without it OpenCode stays on its built-in default and never reaches FlexInference. > - `options.baseURL` must end in `/v1`. > - Every key under `models` is a slug sent verbatim on the wire, so it must be one FlexInference serves. `gpt-5.6-sol` is a safe default. > - Do not put `seed`, `stop`, `presence_penalty`, `frequency_penalty`, `logit_bias`, `logprobs`, `top_logprobs`, `prediction`, `audio`, `modalities`, or `web_search_options` in any model's `options`. FlexInference refuses those Chat Completions parameters, and they also conflict with a key that carries a flex duration. > - Do not add `start_within` unless I ask. My agent key already carries the deadline, and a key duration falls back safely on models that cannot race while a config duration errors. > - If I mention working in repositories I do not control, tell me to set `OPENCODE_DISABLE_PROJECT_CONFIG`. A project config wins over the global one and can repoint `baseURL` while still reading my exported key. `OPENCODE_CONFIG` does not prevent that, because project config loads after it. > > Verify the file is valid JSON, then report what you changed and which file you wrote. > ``` ## Configure OpenCode 1. Export the key in the shell that starts OpenCode. ```bash theme={null} export FLEXINFERENCE_API_KEY=flex_live_... ``` 2. Write the provider entry to `opencode.json`. ```json theme={null} { "$schema": "https://opencode.ai/config.json", "model": "flexinference/gpt-5.6-sol", "provider": { "flexinference": { "name": "FlexInference", "env": ["FLEXINFERENCE_API_KEY"], "npm": "@ai-sdk/openai-compatible", "options": { "apiKey": "{env:FLEXINFERENCE_API_KEY}", "baseURL": "https://api.flexinference.com/v1" }, "models": { "gpt-5.6-sol": { "name": "GPT-5.6 Sol", "reasoning": true, "tool_call": true, "limit": { "context": 400000, "output": 128000 } } } } } } ``` 3. Start OpenCode against that file. ```bash theme={null} OPENCODE_CONFIG=/path/to/opencode.json opencode ``` Four fields hold the integration. `npm` picks the OpenAI-compatible package. `options.baseURL` sends requests to the router. `options.apiKey` reads the key from the environment. Each key under `models` is a slug we run. Add a model by adding a key under `models`. Everything else in the entry is display and limits. ## Global or per project Put the provider entry in one of two places, depending on how widely you want it. | Scope | Path | Applies to | | - | - | - | | Global | `~/.config/opencode/opencode.json` | every project on this machine | | Per project | `opencode.json` in the project root | that project only | | One run | any path, via `OPENCODE_CONFIG` | the launch you pass it to | **Project config wins over global.** OpenCode looks for `opencode.json` in the working directory and walks up to the nearest Git directory, so a repo can override your machine-wide provider without touching it. Put the provider entry in the global file and the deadline stays the same everywhere. Put it in a project file and only that repo routes through us. Set `OPENCODE_DISABLE_PROJECT_CONFIG` to stop the upward search. Two more sources exist for bundles and automation. `OPENCODE_CONFIG_DIR` names a directory OpenCode reads config out of, and `OPENCODE_CONFIG_CONTENT` holds the JSON inline. Use `OPENCODE_CONFIG` for a file you opt into per run. ```bash theme={null} OPENCODE_CONFIG=/path/to/opencode.json opencode ``` ## Set the deadline in config instead OpenCode can send `start_within` itself. Both places are plain JSON, and both beat the key. Set it per model. The `options` block goes into the request body for that model. ```json theme={null} "gpt-5.6-sol": { "name": "GPT-5.6 Sol", "options": { "start_within": "00h-00m-30s", "reasoningEffort": "medium" } } ``` Set it per variant instead, to switch without changing model. Pick one with `--variant` on `opencode run`, or cycle them in the TUI with `ctrl+t`. ```json theme={null} "gpt-5.6-sol": { "name": "GPT-5.6 Sol", "variants": { "patient": { "start_within": "00h-05m-00s", "reasoningEffort": "high" }, "now": { "start_within": "priority", "reasoningEffort": "low" } } } ``` A duration here fails on a model that can't race. The same duration on the key falls back instead. That's the reason to prefer the key. ## Troubleshooting **Requests never reach us.** The top-level `model` field is what selects the provider, so defining a provider without naming it there leaves OpenCode on its built-in default. Set `"model": "flexinference/"`. **[`401 invalid_api_key`](/errors#invalid_api_key).** `FLEXINFERENCE_API_KEY` is unset in the shell that started OpenCode. Export it before launching, since `options.apiKey` reads it from the environment. **A config edit changed nothing.** A later config source overrode it. Check the search order above, and prefer `OPENCODE_CONFIG` to opt into one file per run. Anything not specific to OpenCode is on [agent keys](/agent-keys#troubleshooting). [OpenWork](/openwork) and [OpenScience](/openscience) read the same provider entry. # OpenScience Source: https://docs.flexinference.com/openscience Point OpenScience at FlexInference with config only. OpenScience reads a provider entry out of a JSON file. A stock build needs no source change. OpenScience can set `start_within` in config, so an [agent key](/agent-keys) is optional here. The key is still the simpler path, because it changes without a restart. ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure OpenScience to send its requests to FlexInference. This is config only: no source change, no fork, no patch. > > You will never see or handle my API key. The provider entry stores only the `{env:FLEXINFERENCE_API_KEY}` template, and I export the value myself. Do not ask me for the key, and do not read it from my environment. > > 1. Create a directory named `config/` and put `openscience.json` in it with this content: > > { > "$schema": "https://syntheticsciences.ai/config.json", > "model": "flexinference/gpt-5.6-sol", > "provider": { > "flexinference": { > "name": "FlexInference", > "env": ["FLEXINFERENCE_API_KEY"], > "npm": "@ai-sdk/openai-compatible", > "options": { > "apiKey": "{env:FLEXINFERENCE_API_KEY}", > "baseURL": "https://api.flexinference.com/v1" > }, > "models": { > "gpt-5.6-sol": { > "name": "GPT-5.6 Sol", > "reasoning": true, > "tool_call": true > } > } > } > } > } > > 2. Print these lines for me to run. Do not run the export and do not ask for the value: > > export FLEXINFERENCE_API_KEY= > OPENSCIENCE_CONFIG_DIR=./config bun run dev > > 3. Add `config/package.json`, `config/bun.lock`, and `config/node_modules/` to `.gitignore`. OpenScience writes those into any directory it loads config from on first run. > > Rules that matter, do not deviate: > - Use `OPENSCIENCE_CONFIG_DIR`, not `OPENSCIENCE_CONFIG`. The first names a directory and scans it for commands, agents, and plugins. The second names a single file and scans nothing. > - If I ask for a plugin, place the file at `config/plugins/.js` and leave the `plugin` key out of the JSON entirely. > - Tell me that any `.openscience` or `.synsc` directory inside a repository I open is also scanned for plugins, and that those plugins run with my exported key in the environment. Recommend I export the key only in the launch shell. Every entry in that array without a `file://` prefix is treated as an npm package name and handed to `bun add`, which fails and takes plugin startup down. The directory scan is one level deep and loads every `.js` and `.ts` sitting directly in `plugins/`, so keep shared modules outside it. > - Do NOT put `start_within` in any model's `options`. FlexInference injects a key default only when the field is ABSENT, so writing it here permanently overrides my agent key's deadline with whatever you hardcoded. Only add it if I tell you I am not using an agent key. > - Keep `options.apiKey` as the literal `{env:FLEXINFERENCE_API_KEY}` template. Never inline my key. > - The top-level `model` field is what selects the provider. Without it OpenScience stays on its built-in default. > - Every key under `models` is a slug sent verbatim on the wire, so it must be one FlexInference serves. > > Verify the file is valid JSON, then report what you created and the exact command to run. > ``` ## Configure OpenScience 1. Export the key in the shell that starts OpenScience. ```bash theme={null} export FLEXINFERENCE_API_KEY=flex_live_... ``` 2. Write the provider entry to `openscience.json`. ```json theme={null} { "$schema": "https://syntheticsciences.ai/config.json", "model": "flexinference/gpt-5.6-sol", "provider": { "flexinference": { "name": "FlexInference", "env": ["FLEXINFERENCE_API_KEY"], "npm": "@ai-sdk/openai-compatible", "options": { "apiKey": "{env:FLEXINFERENCE_API_KEY}", "baseURL": "https://api.flexinference.com/v1" }, "models": { "gpt-5.6-sol": { "name": "GPT-5.6 Sol", "reasoning": true, "tool_call": true } } } } } ``` 3. Start OpenScience with the config directory set. ```bash theme={null} OPENSCIENCE_CONFIG_DIR=/path/to/config bun run dev ``` Leave `start_within` out of `options` when your key holds the deadline. We only fill a stored default in when the field is absent, so a value here would override the key on every request. Set `"start_within": "default"` on every model instead when you're **not** using an agent key. That's the safe baseline, because a model picked with no session selection then routes standard rather than racing by accident. ## Where the file goes OpenScience merges config from several places, and a later source wins. * The global user config in OpenScience's config directory. * `OPENSCIENCE_CONFIG`, a path to one config file. * `synsc.jsonc`, `synsc.json`, `openscience.jsonc`, and `openscience.json` found walking up to the worktree root, unless `OPENSCIENCE_DISABLE_PROJECT_CONFIG` is set. * `OPENSCIENCE_CONFIG_CONTENT`, holding the JSON inline. * Those same four names inside each `.openscience` or `.synsc` directory on that walk, plus any directory named by `OPENSCIENCE_CONFIG_DIR`. The two path variables aren't interchangeable. `OPENSCIENCE_CONFIG` names one file. `OPENSCIENCE_CONFIG_DIR` names a directory and treats the whole thing as config, scanning it for commands, agents, and plugins. Use the directory form when the bundle holds more than JSON. ## Load a plugin by placing it OpenScience scans each config directory for `{plugin,plugins}/*.{ts,js}` and loads what it finds as a local file. Put the file at `plugins/flex.js` and leave `plugin` out of the JSON. ``` config/ openscience.json plugins/ flex.js ``` Writing the path into `plugin` doesn't work. OpenScience reads every entry there without a `file://` prefix as an npm package name and hands it to `bun add`, so `"./plugins/flex.js"` fails to install and takes plugin startup down with it. The scan is one level deep, and it takes every `.js` and `.ts` sitting in `plugins/` itself. Keep shared modules outside that directory, or OpenScience loads them as plugins too. The first time OpenScience loads config from a directory it writes `package.json`, `bun.lock`, `node_modules/`, and a `.gitignore` covering them into it. Expect those, and keep them out of Git. ## Troubleshooting **A plugin never loaded.** Naming it in `plugin` sends it to `bun add` as a package name, which fails and takes plugin startup down. Put the file at `plugins/flex.js` inside the config directory and leave `plugin` out of the JSON. **A helper module loaded as a plugin.** The scan takes every `.js` and `.ts` sitting in `plugins/` itself. Move shared modules outside that directory. **Requests never reach us.** The top-level `model` field is what selects the provider. Without it OpenScience stays on its built-in default. **[`401 invalid_api_key`](/errors#invalid_api_key).** `FLEXINFERENCE_API_KEY` is unset in the shell that started OpenScience. Export it before launching. **The key's deadline never applies.** A `start_within` in a model's `options` wins over the key, because we only fill a stored default in when the field is absent. Remove it from the entry. Anything not specific to OpenScience is on [agent keys](/agent-keys#troubleshooting), and [OpenCode](/opencode) holds the per-model deadline options, which OpenScience shares. # OpenWork Source: https://docs.flexinference.com/openwork Point OpenWork at FlexInference by importing an OpenCode config bundle. OpenWork drives an OpenCode backend, so the file you write is an OpenCode config file. The backend reads the provider entry out of it. OpenWork gives you nowhere to set `start_within` in its own UI, so the deadline goes on an [agent key](/agent-keys). ## Set this up with an agent Copy the block below into any coding agent. It never asks for your API key: you run the one export line yourself. > [accordion] Copy agent setup prompt > > ```text theme={null} > Configure OpenWork to send its requests to FlexInference. OpenWork drives an OpenCode backend, so the file you write is an OpenCode config file that OpenWork imports into its profile. > > You will never see or handle my API key. The provider entry stores only the `{env:FLEXINFERENCE_API_KEY}` template, and I export the value myself. Do not ask me for the key, and do not read it from my environment. > > 1. Create a directory named `config/` beside my OpenWork checkout and put `opencode.json` in it with this content: > > { > "$schema": "https://opencode.ai/config.json", > "model": "flexinference/gpt-5.6-sol", > "provider": { > "flexinference": { > "name": "FlexInference", > "env": ["FLEXINFERENCE_API_KEY"], > "npm": "@ai-sdk/openai-compatible", > "options": { > "apiKey": "{env:FLEXINFERENCE_API_KEY}", > "baseURL": "https://api.flexinference.com/v1" > }, > "models": { > "gpt-5.6-sol": { > "name": "GPT-5.6 Sol", > "reasoning": true, > "tool_call": true, > "limit": { "context": 400000, "output": 128000 } > } > } > } > } > } > > 2. Find the OpenCode binary OpenWork should drive and note its path. > > 3. Give me the launch command, with the binary path filled in: > > OPENWORK_ELECTRON_USERDATA="$PWD/.openwork-flex-userdata" \ > OPENWORK_DATA_DIR="$PWD/.openwork-flex-data" \ > OPENWORK_DEV_OPENCODE_IMPORT_CONFIG_DIR="$PWD/config" \ > OPENWORK_OPENCODE_BIN= \ > pnpm dev > > 4. Print this line for me to run in that same shell. Do not run it and do not ask for the value: > > export FLEXINFERENCE_API_KEY= > > OpenWork passes its parent environment to the backend, which is how the value reaches the provider entry. > > 5. Add `.openwork-flex-userdata/` and `.openwork-flex-data/` to `.gitignore` if this is a Git repository. > > Rules that matter, do not deviate: > - OpenWork ignores a config file in the working directory. The bundle only reaches the backend through `OPENWORK_DEV_OPENCODE_IMPORT_CONFIG_DIR`. > - The import only runs when `OPENWORK_DEV_MODE=1`, which `pnpm dev` sets. A production launch skips it entirely. > - Reuse the same `OPENWORK_ELECTRON_USERDATA` and `OPENWORK_DATA_DIR` paths on every launch, or you start a fresh profile and lose session history. The copy overwrites on each launch but never deletes. > - Keep `options.apiKey` as the literal `{env:FLEXINFERENCE_API_KEY}` template. Never inline my key. > - The top-level `model` field is what selects the provider. Without it the backend stays on its built-in default. > > Report what you created and give me the exact command to run. > ``` ## Configure OpenWork 1. Put an `opencode.json` in a directory of its own. Use the provider entry from [OpenCode](/opencode#configure-opencode). 2. Export the key in the shell that starts OpenWork. ```bash theme={null} export FLEXINFERENCE_API_KEY=flex_live_... ``` 3. Launch OpenWork with the import path set. ```bash theme={null} OPENWORK_ELECTRON_USERDATA="$PWD/.openwork-flex-userdata" \ OPENWORK_DATA_DIR="$PWD/.openwork-flex-data" \ OPENWORK_DEV_OPENCODE_IMPORT_CONFIG_DIR="$PWD/config" \ OPENWORK_OPENCODE_BIN=/path/to/opencode/binary \ pnpm dev ``` OpenWork keeps the backend on an isolated profile, so it ignores a config file in your working directory. It copies the named directory into the profile on launch, then starts the backend with `OPENCODE_CONFIG_DIR` set to that copy. `pnpm dev` sets `OPENWORK_DEV_MODE=1`, which is what turns the import on. OpenWork passes the parent environment through to the backend, so `FLEXINFERENCE_API_KEY` reaches the provider entry. ## Scope comes from the profile, not the folder OpenWork doesn't read config out of your working directory, so the global and per-project split that [OpenCode](/opencode#global-or-per-project) offers doesn't apply here. Scope comes from the profile you launch against. | Scope | What sets it | Applies to | | - | - | - | | One profile | `OPENWORK_ELECTRON_USERDATA` and `OPENWORK_DATA_DIR` | every session in that profile | | The bundle | `OPENWORK_DEV_OPENCODE_IMPORT_CONFIG_DIR` | whatever the profile imports | Keep one pair of profile paths per configuration you want to switch between. The same bundle imported into two profiles gives you two isolated setups, each with its own session history. Reuse the paths above to keep a profile. Change them to start a fresh one. ## The import copies on every launch and never deletes The copy runs on every launch, and it overwrites. Edit the bundle, restart on the same `OPENWORK_ELECTRON_USERDATA` and `OPENWORK_DATA_DIR` paths, and the backend reads the new file. It never deletes. A file you removed from the bundle stays in the profile copy. Clearing that needs fresh paths for both variables, which starts the profile over and loses its session history. Do that only when a leftover file is in the way. ## Troubleshooting **The import never ran.** `OPENWORK_DEV_MODE=1` is what enables it, and `pnpm dev` sets it. A production launch skips the import. **A config edit changed nothing.** The copy runs per launch but only onto the profile it was given. Restart on the same `OPENWORK_ELECTRON_USERDATA` and `OPENWORK_DATA_DIR` paths. **A file you deleted is still loaded.** The copy overwrites but never deletes. Start a fresh profile with new paths for both variables, accepting the loss of session history. **Requests never reach us.** The top-level `model` field in the bundle is what selects the provider. Without it the backend stays on its built-in default. **[`401 invalid_api_key`](/errors#invalid_api_key).** `FLEXINFERENCE_API_KEY` is unset in the shell that started OpenWork. Export it there, since the backend inherits that shell's environment. Anything not specific to OpenWork is on [agent keys](/agent-keys#troubleshooting), and [OpenCode](/opencode) holds the provider entry. # OpenWorker Source: https://docs.flexinference.com/openworker Point OpenWorker at FlexInference through its OpenAI provider. OpenWorker points its OpenAI provider at any OpenAI-compliant server. Keys sit in the app's local secret store, not in a file. OpenWorker gives you nowhere to set `start_within` per request, so the deadline goes on an [agent key](/agent-keys). > [!NOTE] > > OpenWorker is in open beta, so these fields move. Check them against your > build. The endpoint and key go through the app's UI, not a file, so this page has no agent setup prompt. Only the model line sits in config. ## Configure OpenWorker 1. Open OpenWorker and go to provider settings. Pick the **OpenAI** provider. 2. Paste your agent key into **OpenAI API key**. 3. Set **Custom endpoint (optional)** to the router, including the `/v1` suffix. ```text theme={null} https://api.flexinference.com/v1 ``` 4. Set the default model in `~/.config/coworker/config.toml`. ```toml theme={null} model = "gpt-5.6-sol" ``` A per-workspace file at `/.coworker/config.toml` overrides the global one. Every key in it is optional, and unset keys fall back to built-in defaults. OpenWorker also reads `OPENAI_API_KEY` from the environment. Export your agent key there to keep it out of the secret store. ```bash theme={null} export OPENAI_API_KEY=flex_live_... ``` ## Troubleshooting **OpenWorker didn't detect the provider from the key.** It checks for `sk-` and `AIza` prefixes to guess one, and a `flex_live_` key matches neither. Pick **OpenAI** yourself. **Requests still go to OpenAI.** **Custom endpoint (optional)** is blank, so the provider falls back to `api.openai.com`. Set it to the router URL, including `/v1`. **The model picker and `config.toml` disagree.** A per-workspace `.coworker/config.toml` overrides the global file. Check which one your project directory has. Anything not specific to OpenWorker is on [agent keys](/agent-keys#troubleshooting). # PII Masking Source: https://docs.flexinference.com/pii-masking We can mask personal data out of your prompt before the provider sees it. Each match becomes a stable placeholder such as `[EMAIL_1]`, so the model can still tell people apart. It covers emails, phone numbers, and patterns such as card numbers. ```json theme={null} { "pii_mask": true } ``` Masking runs on Managed Keys. On your own keys we forward your request untouched. If your request sets `pii_mask` we follow it. If it doesn't, we follow your organization's default. If neither is set, masking is off. That means you can send `false` to turn masking off for one request when your organization has it on. If masking is on and it fails, we stop the request rather than send it unmasked. # Pricing Source: https://docs.flexinference.com/pricing Your own provider keys are free. Managed Keys costs the provider's own price plus a 10 percent fee on each top-up. ## Managed Keys We require you to prepay a balance, which is then used to pay off model costs for the provider chosen. Add \$100 and we charge your card \$110, and \$100 becomes spendable. The smallest top-up is \$10. [Billing](/billing) covers the balance, refunds, and running out. Per-model rates are on the [pricing page](https://www.flexinference.com/pricing). # Prompt Caching Source: https://docs.flexinference.com/prompt-handling We cache every Claude request on the direct Anthropic route. A repeated prefix then bills at one tenth of the normal input price. Writing the cache costs 1.25 times the input price, so a prefix you never reuse costs 25 percent more. That's why you can turn caching off. ```json theme={null} { "cache": false } ``` Your own markers always win. If your request has any `cache_control`, we forward it and add nothing of our own. A request too short to cache runs uncached. On Bedrock we only follow your explicit markers, because Bedrock has no automatic caching. OpenAI and Gemini cache repeated prefixes themselves, so there is nothing to set. Each provider runs its own cache, and none of them share. So a [backup route](/backup-providers) starts with an empty cache, and its first request pays the full input price. On Managed Keys we replace `user`, `safety_identifier`, and `prompt_cache_key` with a hash of your organization id before the provider sees them, because the identity on our credential has to come from us. Provider-side cache affinity is per organization there. On your own keys all three pass through unchanged. The response reports `cached_tokens` and `cache_write_tokens` in its usage block. # Quick Start Source: https://docs.flexinference.com/quickstart 1. Go to [https://www.flexinference.com/](https://www.flexinference.com/) 2. [Sign Up](https://www.flexinference.com/signup) 3. You should now be in [https://www.flexinference.com/dashboard](https://www.flexinference.com/dashboard) 4. Either place your own key in place for a provider or switch it to managed [here](https://www.flexinference.com/dashboard/api?tab=providers) 5. Create a FlexInference Normal API key [here](https://www.flexinference.com/dashboard/api?tab=keys) 6. Copy and Paste any of the following ## Flex Race Request (Gemini / GPT) ### TypeScript > [tab] Chat Completions > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.chat.completions.create({ > model: "gpt-5-nano", > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "00h-00m-30s", > } as any); > > console.log(resp.choices[0].message.content); > ``` > [tab] Responses > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.responses.create({ > model: "gpt-5-nano", > input: "Write a haiku about cheap GPUs.", > start_within: "00h-00m-30s", > } as any); > > console.log(resp.output_text); > ``` > [tab] Messages > > ```typescript theme={null} > import Anthropic from "@anthropic-ai/sdk"; > > const client = new Anthropic({ > baseURL: "https://api.flexinference.com", > authToken: "flex_live_...", > }); > > const resp = await client.messages.create({ > model: "gemini-3.5-flash", > max_tokens: 1024, > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "00h-00m-30s", > } as any); > > console.log(resp.content[0].text); > ``` > [tab] generateContent > > ```typescript theme={null} > import { GoogleGenAI } from "@google/genai"; > > const ai = new GoogleGenAI({ > apiKey: "flex_live_...", > httpOptions: { baseUrl: "https://api.flexinference.com" }, > }); > > const resp = await ai.models.generateContent({ > model: "gemini-3.5-flash", > contents: "Write a haiku about cheap GPUs.", > config: { > httpOptions: { headers: { "x-start-within": "00h-00m-30s" } }, > }, > }); > > console.log(resp.text); > ``` ### Python > [tab] Chat Completions > > ```python theme={null} > from openai import OpenAI > from openai.types.chat import ChatCompletion, ChatCompletionMessageParam > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > messages: list[ChatCompletionMessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: ChatCompletion = client.chat.completions.create( > model="gpt-5-nano", > messages=messages, > extra_body={"start_within": "00h-00m-30s"}, > ) > print(resp.choices[0].message.content) > ``` > [tab] Responses > > ```python theme={null} > from openai import OpenAI > from openai.types.responses import Response > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > resp: Response = client.responses.create( > model="gpt-5-nano", > input="Write a haiku about cheap GPUs.", > extra_body={"start_within": "00h-00m-30s"}, > ) > print(resp.output_text) > ``` > [tab] Messages > > ```python theme={null} > import anthropic > from anthropic.types import Message, MessageParam, TextBlock > > client = anthropic.Anthropic( > base_url="https://api.flexinference.com", > auth_token="flex_live_...", > ) > > messages: list[MessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: Message = client.messages.create( > model="gemini-3.5-flash", > max_tokens=1024, > messages=messages, > extra_body={"start_within": "00h-00m-30s"}, > ) > > block = resp.content[0] > if isinstance(block, TextBlock): > print(block.text) > ``` > [tab] generateContent > > ```python theme={null} > from google import genai > from google.genai import types > > client = genai.Client( > api_key="flex_live_...", > http_options=types.HttpOptions(base_url="https://api.flexinference.com"), > ) > > resp: types.GenerateContentResponse = client.models.generate_content( > model="gemini-3.5-flash", > contents="Write a haiku about cheap GPUs.", > config=types.GenerateContentConfig( > http_options=types.HttpOptions(headers={"x-start-within": "00h-00m-30s"}), > ), > ) > print(resp.text) > ``` ## Flex Race Request (Anthropic) These need Managed Keys for Anthropic. On your own Anthropic key they return `400 flex_unsupported_for_anthropic`. ### TypeScript > [tab] Chat Completions > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.chat.completions.create({ > model: "claude-opus-4-8", > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "00h-03m-00s", > } as any); > > console.log(resp.choices[0].message.content); > ``` > [tab] Responses > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.responses.create({ > model: "claude-opus-4-8", > input: "Write a haiku about cheap GPUs.", > start_within: "00h-03m-00s", > } as any); > > console.log(resp.output_text); > ``` > [tab] Messages > > ```typescript theme={null} > import Anthropic from "@anthropic-ai/sdk"; > > const client = new Anthropic({ > baseURL: "https://api.flexinference.com", > authToken: "flex_live_...", > }); > > const resp = await client.messages.create({ > model: "claude-opus-4-8", > max_tokens: 1024, > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "00h-03m-00s", > } as any); > > console.log(resp.content[0].text); > ``` > [tab] generateContent > > ```typescript theme={null} > import { GoogleGenAI } from "@google/genai"; > > const ai = new GoogleGenAI({ > apiKey: "flex_live_...", > httpOptions: { baseUrl: "https://api.flexinference.com" }, > }); > > const resp = await ai.models.generateContent({ > model: "claude-opus-4-8", > contents: "Write a haiku about cheap GPUs.", > config: { > httpOptions: { headers: { "x-start-within": "00h-03m-00s" } }, > }, > }); > > console.log(resp.text); > ``` ### Python > [tab] Chat Completions > > ```python theme={null} > from openai import OpenAI > from openai.types.chat import ChatCompletion, ChatCompletionMessageParam > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > messages: list[ChatCompletionMessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: ChatCompletion = client.chat.completions.create( > model="claude-opus-4-8", > messages=messages, > extra_body={"start_within": "00h-03m-00s"}, > ) > print(resp.choices[0].message.content) > ``` > [tab] Responses > > ```python theme={null} > from openai import OpenAI > from openai.types.responses import Response > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > resp: Response = client.responses.create( > model="claude-opus-4-8", > input="Write a haiku about cheap GPUs.", > extra_body={"start_within": "00h-03m-00s"}, > ) > print(resp.output_text) > ``` > [tab] Messages > > ```python theme={null} > import anthropic > from anthropic.types import Message, MessageParam, TextBlock > > client = anthropic.Anthropic( > base_url="https://api.flexinference.com", > auth_token="flex_live_...", > ) > > messages: list[MessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: Message = client.messages.create( > model="claude-opus-4-8", > max_tokens=1024, > messages=messages, > extra_body={"start_within": "00h-03m-00s"}, > ) > > block = resp.content[0] > if isinstance(block, TextBlock): > print(block.text) > ``` > [tab] generateContent > > ```python theme={null} > from google import genai > from google.genai import types > > client = genai.Client( > api_key="flex_live_...", > http_options=types.HttpOptions(base_url="https://api.flexinference.com"), > ) > > resp: types.GenerateContentResponse = client.models.generate_content( > model="claude-opus-4-8", > contents="Write a haiku about cheap GPUs.", > config=types.GenerateContentConfig( > http_options=types.HttpOptions(headers={"x-start-within": "00h-03m-00s"}), > ), > ) > print(resp.text) > ``` ## Default Request ### TypeScript > [tab] Chat Completions > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.chat.completions.create({ > model: "gpt-5-nano", > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "default", > } as any); > > console.log(resp.choices[0].message.content); > ``` > [tab] Responses > > ```typescript theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://api.flexinference.com/v1", > apiKey: "flex_live_...", > }); > > const resp = await client.responses.create({ > model: "gpt-5-nano", > input: "Write a haiku about cheap GPUs.", > start_within: "default", > } as any); > > console.log(resp.output_text); > ``` > [tab] Messages > > ```typescript theme={null} > import Anthropic from "@anthropic-ai/sdk"; > > const client = new Anthropic({ > baseURL: "https://api.flexinference.com", > authToken: "flex_live_...", > }); > > const resp = await client.messages.create({ > model: "claude-opus-4-8", > max_tokens: 1024, > messages: [{ role: "user", content: "Write a haiku about cheap GPUs." }], > start_within: "default", > } as any); > > console.log(resp.content[0].text); > ``` > [tab] generateContent > > ```typescript theme={null} > import { GoogleGenAI } from "@google/genai"; > > const ai = new GoogleGenAI({ > apiKey: "flex_live_...", > httpOptions: { baseUrl: "https://api.flexinference.com" }, > }); > > const resp = await ai.models.generateContent({ > model: "gemini-3.5-flash", > contents: "Write a haiku about cheap GPUs.", > config: { > httpOptions: { headers: { "x-start-within": "default" } }, > }, > }); > > console.log(resp.text); > ``` ### Python > [tab] Chat Completions > > ```python theme={null} > from openai import OpenAI > from openai.types.chat import ChatCompletion, ChatCompletionMessageParam > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > messages: list[ChatCompletionMessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: ChatCompletion = client.chat.completions.create( > model="gpt-5-nano", > messages=messages, > extra_body={"start_within": "default"}, > ) > print(resp.choices[0].message.content) > ``` > [tab] Responses > > ```python theme={null} > from openai import OpenAI > from openai.types.responses import Response > > client = OpenAI( > base_url="https://api.flexinference.com/v1", > api_key="flex_live_...", > ) > > resp: Response = client.responses.create( > model="gpt-5-nano", > input="Write a haiku about cheap GPUs.", > extra_body={"start_within": "default"}, > ) > print(resp.output_text) > ``` > [tab] Messages > > ```python theme={null} > import anthropic > from anthropic.types import Message, MessageParam, TextBlock > > client = anthropic.Anthropic( > base_url="https://api.flexinference.com", > auth_token="flex_live_...", > ) > > messages: list[MessageParam] = [ > {"role": "user", "content": "Write a haiku about cheap GPUs."} > ] > > resp: Message = client.messages.create( > model="claude-opus-4-8", > max_tokens=1024, > messages=messages, > extra_body={"start_within": "default"}, > ) > > block = resp.content[0] > if isinstance(block, TextBlock): > print(block.text) > ``` > [tab] generateContent > > ```python theme={null} > from google import genai > from google.genai import types > > client = genai.Client( > api_key="flex_live_...", > http_options=types.HttpOptions(base_url="https://api.flexinference.com"), > ) > > resp: types.GenerateContentResponse = client.models.generate_content( > model="gemini-3.5-flash", > contents="Write a haiku about cheap GPUs.", > config=types.GenerateContentConfig( > http_options=types.HttpOptions(headers={"x-start-within": "default"}), > ), > ) > print(resp.text) > ``` # Spending Limits Source: https://docs.flexinference.com/spending-limits We put no money ceiling on your own provider keys. Managed Keys spends a prepaid balance, so it can run out. ## What Managed Keys can run out of * **The balance.** The money you prepaid. At zero you get [`402 insufficient_balance`](/errors#insufficient_balance) until you add funds. * **The daily spending limit.** It counts what you spent today plus what your in-flight requests hold, over a UTC day. Past it you get [`429 spend_velocity_exceeded`](/errors#spend_velocity_exceeded) until the day rolls over. A risk review can pause managed requests on top of those two. That's [`403 account_under_review`](/errors#account_under_review). Your own key routes keep working through all of it. ## Two headers report your spend * `x-flexinference-spend-remaining` says `unlimited` when no money ceiling applies. Otherwise it's a signed micro-USD number. It's the smaller of your balance and what's left of today's limit. * `x-flexinference-spend-as-of` is when we read that number, in epoch milliseconds. A negative number means we're turning away managed requests until you add money. ## The limits endpoint Call `GET /v1/limits` with your key. It lists every ceiling on your organization, spending and [usage](/usage-limits) alike. ```bash theme={null} curl https://api.flexinference.com/v1/limits \ -H "Authorization: Bearer $FLEXINFERENCE_API_KEY" ``` ```json theme={null} { "object": "limits", "as_of": 1769558400123, "own_keys": { "unlimited": true, "flex_race_slots": { "limit": 40, "scope": "organization", "on_exceed": "degrade_to_standard" } }, "managed": { "providers": ["anthropic", "openai"], "serving": "ok", "paused_reason": null, "binding": "daily_spend", "spend_remaining_micro_usd": 41200000, "currency": "USD", "balance": { "remaining_micro_usd": 94880000, "cash_micro_usd": 84880000, "credit_micro_usd": 10000000, "reserved_micro_usd": 120000 }, "daily_spend": { "limit_micro_usd": 250000000, "used_micro_usd": 208800000, "remaining_micro_usd": 41200000, "window": "utc_day", "resets_at": 1769644800 }, "concurrency": { "limit": 10, "scope": "organization", "on_exceed": "refuse" }, "ramp_week": 1, "ramp_defaults": { "concurrency": 10, "daily_spend_micro_usd": 250000000 }, "override_in_force": { "concurrency": false, "daily_spend": false }, "rates": [] }, "abuse_limits": { "counted_per_cloudflare_location": true, "request_body_bytes": 50000000, "rates": [ { "name": "organization_requests", "scope": "organization", "window_seconds": 60, "limit": null, "on_exceed": "refuse" }, { "name": "api_key_requests", "scope": "api_key", "window_seconds": 60, "limit": null, "on_exceed": "refuse" }, { "name": "client_ip_requests", "scope": "client_ip", "window_seconds": 60, "limit": null, "on_exceed": "refuse" }, { "name": "failed_authentications", "scope": "client_ip", "window_seconds": 60, "limit": null, "on_exceed": "refuse" } ] } } ``` Every money field is a micro-USD number, and one USD is a million of them. `as_of` is epoch milliseconds. * `managed` comes back `null` when no provider runs on Managed Keys. * `managed.serving` reads `ok` or `paused`. When paused, `paused_reason` carries the matching error code from [the errors page](/errors). * `managed.binding` names the ceiling closest to stopping you (`balance` or `daily_spend`, with `paused` and `exempt` for the special cases). * `managed.spend_remaining_micro_usd` matches the `x-flexinference-spend-remaining` header. * `managed.balance.remaining_micro_usd` adds cash and credit together. `reserved_micro_usd` is money your in-flight requests hold, and we don't subtract it. * `managed.ramp_week` says which week of the account-age schedule you're in, and `ramp_defaults` is what that week gives you. `override_in_force` means an admin set a number by hand, so the schedule won't move it. * A `limit` of `null` in `abuse_limits.rates` means the number isn't published. Back off for `Retry-After`. When we can't read one of these records, you get [`503 limits_unavailable`](/errors#limits_unavailable). Requests keep working. # Timeouts Source: https://docs.flexinference.com/timeouts `start_within` bounds when your request starts, not how long the response takes. We hold the HTTP response open until a tier commits, so your client has to wait out your window plus the answer. The OpenAI and Anthropic SDKs both allow 10 minutes by default, which matches the longest duration we accept. Raise that setting when a long window and a slow answer could add up past it. ```python Python (openai SDK) theme={null} client = OpenAI( base_url="https://api.flexinference.com/v1", api_key="flex_live_...", timeout=900, # seconds, longer than your start_within plus the answer ) ``` ```typescript Node (openai SDK) theme={null} const client = new OpenAI({ baseURL: "https://api.flexinference.com/v1", apiKey: "flex_live_...", timeout: 900_000, // ms, longer than your start_within plus the answer }); ``` ```python Python (anthropic SDK) theme={null} client = anthropic.Anthropic( base_url="https://api.flexinference.com", auth_token="flex_live_...", timeout=900, # seconds, longer than your start_within plus the answer ) ``` ```typescript Node (anthropic SDK) theme={null} const client = new Anthropic({ baseURL: "https://api.flexinference.com", authToken: "flex_live_...", timeout: 900_000, // ms, longer than your start_within plus the answer }); ``` A client that gives up early returns `499 client_closed_request`. When the provider never starts, we cancel the upstream and return `504 upstream_timeout`. When the provider stops feeding an open stream, we cancel it and end the response with `504 stream_idle_timeout`, and whatever text you received is the whole answer. # Trace Storage Source: https://docs.flexinference.com/trace-storage We can store your prompts and responses, encrypted, so the Logs page in the dashboard can show them. ```json theme={null} { "trace_storage": true } ``` Trace storage runs on Managed Keys. Only your request turns it on. There is no organization default, and without the field we keep billing data and nothing else, the same as on your own keys. A later request without the field stores nothing new. What you stored stays until you delete it on the Logs page. # Upstream Retries Source: https://docs.flexinference.com/upstream-retries Retries cover the case where the provider will not start your request at all. ```json theme={null} { "retry": { "count": 2 } } ``` * `count` is required, from 1 to 5. It is the number of extra attempts after the first one fails. * `backoff` is `exponential` by default, or `linear`. * `jitter` is on by default. It spreads the waits apart, and only ever shortens them. We retry a `429`, a `5xx`, or a connection that never opened, and only before anything commits. We do not retry your own `4xx`, a bad provider key, a timeout, or a request you cancelled, because those fail the same way twice. A retry goes back to whichever tier your request ended on, so a lost race retries the default tier. The race itself never counts against `count`. When the provider sends `Retry-After` we honor it, up to 60 seconds. Your client probably retries too, and the two multiply. A stock OpenAI or Anthropic client retries twice, which is three sends. Each send spends its own budget, so `count: 3` makes each one up to four attempts, and the request can reach twelve. We set `x-flexinference-retries` to the number we ran, so you can turn your client down. An agent key can carry a retry policy the same way it carries a duration. See [setting the duration for Agent Keys](/deadline-routing#setting-the-duration-for-agent-keys). # Usage Limits Source: https://docs.flexinference.com/usage-limits We set no request allowance and no monthly cap. Every limit on this page is a ceiling on how much runs at once. ## On your own keys Only one limit applies. Your organization can run a fixed number of flex races at a time. Past that number we run the request on the standard tier, so you lose the discount, not the answer. ## On Managed Keys * **Concurrency.** Your organization can run a fixed number of managed requests at a time. Past it you get [`429 rate_limit_exceeded`](/errors#rate_limit_exceeded) with a `Retry-After`. * **Shared pools.** Workers AI and Foundry serve everyone from one pool, so each organization gets a per-minute rate there. Past it you get the same `429`. ## On every organization We count requests per minute three ways (per organization, per key, and per IP). A fourth counter tracks failed auth attempts per IP. A body over 50 MB returns [`413 request_too_large`](/errors#request_too_large). Back off for the seconds in `Retry-After`. `GET /v1/limits` reports every ceiling on this page next to the spending ones. See [Spending Limits](/spending-limits#the-limits-endpoint).