Skip to main content

Codex

Codex is a coding agent that runs in your terminal and edits code in your repository. Out of the box it sends every request straight to its vendor. Routing it through Spanway means the requests use a virtual key that your admin controls, so the spend counts against your team budget, the company guardrails and logging apply, and the admin can serve Codex with any model the gateway knows, not only the vendor's own. This page sets Codex up by hand in its config.toml. If you have spanwayctl on your machine, coding agent setup can write the same file for you.

A real-world scenario​

A platform team wants developers to use Codex, but every request must be logged and stay inside a monthly budget per developer. The admin creates a key per developer that may call gpt-6.1-sol and claude-sonnet-5-5. Each developer adds a spanway provider to ~/.codex/config.toml that reads the key from the SPANWAY_API_KEY environment variable, so the key never sits in a file that might be shared, and points model_catalog_url at the gateway, so the Codex /model picker shows exactly the two models the key may use. When a developer's budget runs out, Codex stops with the gateway's budget message, and the admin sees every request on the Logs page under the developer's key alias.

Prerequisites​

  • Codex 0.129.0 or newer. Check with codex --version. Older releases let a repository's settings redirect requests that carry your key.
  • Codex 0.156.0 or newer for model_catalog_url, which fills the /model picker from the gateway. On 0.129 to 0.155 the provider works, but the picker shows Codex's own models, so pick a gateway model with -m or model = "...".
  • The gateway's address, for example https://gateway.example.com, reachable from your machine.
  • A virtual key for Codex, made as in the next section.
  • At least one model on the gateway that works through the Responses API, which is the only API Codex speaks. Every chat model behind the gateway qualifies, because the gateway translates Responses requests for providers that do not speak it natively, see Responses API.

Make a key for Codex​

  1. In the Admin UI open Virtual Keys (/ui/api-keys) and click + Create New Key.
  2. Set Key Name to who and which tool, for example jane-codex. Leave Key Type on AI APIs.
  3. In Models, pick the models the developer may choose in Codex, for example gpt-6.1-sol and claude-sonnet-5-5. Codex uses the model you pick for everything in a session, including summarising a long conversation, so there is no separate background model to add.
  4. Open Optional Settings. Set Max Budget (USD), for example 150, and Reset Budget to monthly. Set Requests per minute Limit (RPM), for example 60, so a runaway loop slows down instead of burning the budget. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage.
  5. Click Create Key and copy the key. It is shown once.

The same key from the API, with the master key or a proxy admin's key:

curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "jane-codex", "key_type": "llm_api", "models": ["gpt-6.1-sol", "claude-sonnet-5-5"], "max_budget": 150, "budget_duration": "30d", "rpm_limit": 60}'

Make a key for a tool explains every field.

Steps​

  1. Put the key in your shell profile (~/.zshrc or ~/.bashrc) so every terminal has it, then open a new terminal.

    export SPANWAY_API_KEY="sk-..."
  2. Check the key and see which models it may call. The gateway answers without /v1 too, but Codex needs the /v1 form in the next step.

    curl https://gateway.example.com/v1/models -H "Authorization: Bearer $SPANWAY_API_KEY"
  3. Open ~/.codex/config.toml, or $CODEX_HOME/config.toml if you set CODEX_HOME. Create it if it does not exist. Use this user level file. Codex ignores model_provider and model_providers in a project's own .codex/config.toml, so a provider placed there does nothing.

  4. Add the provider and select it. The settings are explained in the table below.

    model_provider = "spanway"
    model = "gpt-6.1-sol"

    [model_providers.spanway]
    name = "Spanway proxy"
    base_url = "https://gateway.example.com/v1"
    env_key = "SPANWAY_API_KEY"
    env_key_instructions = "Create a key in the Spanway Admin UI under Virtual Keys and export it as SPANWAY_API_KEY."
    wire_api = "responses"
    supports_websockets = false
    requires_openai_auth = false
    model_catalog_url = "https://gateway.example.com/v1/models"
    request_max_retries = 1
  5. If you start Codex with --profile <name>, check that $CODEX_HOME/<name>.config.toml (~/.codex/<name>.config.toml by default) sets no model_provider or model_providers of its own, because the profile's values win over config.toml.

  6. Start Codex in a repository and send a prompt.

    codex
  7. Type /model. The picker lists the models from the gateway's catalog, which are the chat models your key may use.

SettingWhat to putWhy
model_provider"spanway"Selects the provider table below. The ids openai, ollama, lmstudio, amazon-bedrock, amazon-bedrock-runtime and gcp are reserved by Codex, so do not reuse them.
modelA public model name from GET /v1/models, typed exactlyThe model Codex starts on. You can switch later with /model or codex -m <name>.
base_urlhttps://gateway.example.com/v1, with /v1Codex adds /responses to this address. Without /v1 the gateway still answers, but keep /v1 so the address matches the model catalog URL.
env_key"SPANWAY_API_KEY"The name of the environment variable that holds the key. Codex sends its value as Authorization: Bearer <key>. The key never lands in the file, so you can share or commit the file safely and rotate the key without editing it.
env_key_instructionsOne sentenceWhat Codex prints when the variable is missing, so a teammate knows where to get a key.
wire_api"responses"The Responses API is the only protocol Codex speaks.
supports_websocketsfalseCodex can stream over a WebSocket, which the gateway does not offer. false makes Codex use plain HTTP streaming, which the gateway serves.
requires_openai_authfalseTells Codex not to ask for a vendor sign-in for this provider.
model_catalog_urlhttps://gateway.example.com/v1/modelsCodex calls this address with ?client_version=<its version> and the key. When the gateway sees client_version, it answers in Codex's own catalog format instead of the OpenAI list, built from the models the key may use.
request_max_retries1Codex retries failed requests on its own, and the gateway also retries and falls back between deployments. Keeping Codex's retries low stops one failure from turning into many provider calls.

The model catalog​

The catalog is what makes the /model picker show gateway models. A model Codex already knows keeps Codex's own settings for it, such as its reasoning levels. Any other model, for example claude-sonnet-5-5, gets the same general settings Codex uses for a model it does not know. When an admin sets model_info.service_tiers on a deployment, those tiers appear in Codex as slash commands such as /ultrafast, which send service_tier on the request, see service tiers. Only models whose mode is chat or responses are listed, and a model whose every deployment is a wildcard such as openai/* is not listed.

Codex reads the catalog when it starts, so restart Codex after the admin adds or removes a model for your key. A model_catalog_json path in your config takes priority over model_catalog_url and stops the fetch. spanwayctl codex uses that path on purpose, it writes the catalog to ~/.codex/spanway-models.json at every launch.

With spanwayctl instead​

spanwayctl codex runs Codex with the same provider passed as -c overrides on the command line, reads the key from OPENAI_API_KEY, which it sets for that run only, and writes the catalog file described above. spanwayctl configure codex writes the provider into config.toml permanently, with the key in a static Authorization header rather than env_key. Pick one setup per machine. The CLI reference lists their flags.

Expected result​

Codex answers the prompt. Nothing on screen says the gateway is in between, which is the point.

The request appears on the gateway's Logs page (/ui/logs). Open Filters, pick your Key Alias, for example jane-codex, and click Apply Filters. Each Codex turn is one row on the /v1/responses route with the model, tokens and cost. The gateway groups the rows of one Codex session by the session-id header Codex sends, see agent governance.

Codex does not show response headers. To read them, send one request with the same key from a terminal:

curl -i https://gateway.example.com/v1/responses \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "gpt-6.1-sol", "input": "Say hello"}'
HTTP/1.1 200 OK
x-spanway-call-id: 6f1c2a9e-3b7d-4c1e-9a52-8d0f4e7b1c23
x-spanway-model-group: gpt-6.1-sol
x-spanway-routing-reason: strategy=simple-shuffle
x-spanway-attempts: 1
x-spanway-response-cost: 0.00042
x-spanway-key-spend: 12.40
x-spanway-key-max-budget: 150.0

x-spanway-call-id is the id to search for on Logs. x-spanway-model-group and x-spanway-routing-reason say which model group served the call and why, see routing decision headers. x-spanway-key-spend and x-spanway-key-max-budget show how much of the budget is left.

To check the catalog Codex will see, ask for it the way Codex does:

curl "https://gateway.example.com/v1/models?client_version=0.159.3" -H "Authorization: Bearer $SPANWAY_API_KEY"

The answer is {"models": [...]} with one entry per model, each with a slug such as gpt-6.1-sol.

What works through the gateway​

FeatureWorksNotes
StreamingYesOver HTTP server-sent events. Keep supports_websockets = false.
Tool calls (shell, file edits, MCP tools)YesCodex runs its tools on your machine and sends the results back as normal Responses API items. The model behind the name must support tool calling.
ImagesYes, when the model takes imagesCodex attaches screenshots and images you paste. A text-only model behind the name rejects them with a 400 from the provider.
Reasoning effortYesCodex sends reasoning.effort. For a model Codex does not know, the picker shows no reasoning levels.
Prompt cachingProvider dependentCaching happens at the provider. The cached tokens show in the cost on Logs.
Service tiersYes, when the admin sets themSee the model catalog.
Codex specific parametersDropped when unsupportedFor requests whose user agent starts with codex, the gateway turns on drop params by default, so a parameter the provider does not take, such as service_tier on a model without tiers, is removed instead of failing the request. An explicit drop_params in the request or in spanway_settings wins over this default.
WebSocket transportNoThe gateway serves HTTP streaming only.

Errors​

Codex prints the HTTP status and the gateway's message, usually after a few automatic retries. The text in the third column is what the gateway sends, and the client error reference lists the same errors for every tool.

CaseStatusGateway textFix
SPANWAY_API_KEY is not set in the terminal that started CodexnoneNone, Codex stops before sending. It reports the missing variable by name and prints your env_key_instructions.Export the variable and open a new terminal, or start Codex from a terminal that has it.
Wrong or deleted key401Authentication Error, Invalid proxy server token passedCopy the key again from Virtual Keys, or ask the admin whether it was blocked.
Blocked key401Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin.Ask the admin to open the key in Virtual Keys and click Unblock Key.
Expired key401Authentication Error - Expired Key. Key Expiry time <time> and current time <time>Ask the admin for a new key or a later expiry.
The key may not use the model403The requested model '<model>' is not available for this API key, or the model name is invalid.Pick a model from /model, or ask the admin to add the model to the key.
The model name does not exist on the gateway400Invalid model name passed in model=<name>Set model to a name from GET /v1/models, typed exactly, including case.
The budget is spent422Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max>Wait for the reset, or ask the admin to raise Max Budget.
The key's rate limit is reached429Rate limit exceeded for <scope>: <value>. Limit type: <type>.Wait for the reset time in the message, or ask for a higher RPM or TPM limit.
Wrong path, such as /v1/v1/responses404Not FoundSet base_url to https://gateway.example.com/v1 exactly once.
Connection refusednoneNone, the gateway never answered. Codex reports a connection or stream error and retries.Check the address and port, and run curl https://gateway.example.com/health/liveliness.
TLS or certificate errornoneNone, the connection failed before any answer.When the gateway's certificate comes from a company or private authority, point CODEX_CA_CERTIFICATE at its root certificate in PEM form (Codex falls back to SSL_CERT_FILE when that is not set), see connection problems.
The /model picker shows Codex's own models instead of the gateway'snoneNonemodel_catalog_url is missing, model_catalog_json points elsewhere, the catalog fetch failed, or Codex is older than 0.156.0 and ignores model_catalog_url. Run the catalog curl above, check the address matches base_url, and check codex --version.

Troubleshooting​

  1. Find the request on Logs by your key alias and the time. If a row is there, the drawer shows the status, the message, the model group the router picked and the provider's answer.
  2. If there is no row, the request never reached the gateway. Check base_url, the network and TLS with the curl commands on this page.
  3. Run the same request with curl and compare. If curl works and Codex fails, compare the model name and the address in config.toml with the ones in your curl.
  4. See what Codex will load without starting a session. codex debug models prints the model catalog Codex would use, which shows whether the gateway's models arrived.
  5. Turn on Codex's own logs. Codex writes logs under $CODEX_HOME/log (by default ~/.codex/log), and setting log_dir in config.toml also writes a plain text codex-tui.log there. Start Codex with RUST_LOG=debug codex for more detail, then look for the request URL and status.
  6. Read the routing headers from the curl above. x-spanway-attempts higher than 1 means the gateway retried or fell back, and x-spanway-routing-reason says why.

Troubleshooting has the debug switches for the other clients.

Rotate or remove the key​

To rotate, open the key on Virtual Keys, click Regenerate Key and set a Grace Period such as 24h so the old key keeps working while you switch. Put the new key in SPANWAY_API_KEY in your shell profile and open a new terminal. config.toml does not change, because it only names the variable. From the API this is POST /key/{key}/regenerate, which needs an Enterprise license. Without one, create a new key, switch to it and delete the old one.

To stop routing Codex through the gateway, delete model_provider = "spanway" and the [model_providers.spanway] table from config.toml. To cut the key off, use Block Key in the key's actions menu, which can be undone, or delete the key. From the API, POST /key/block with {"key": "sk-..."} blocks it and POST /key/delete with {"keys": ["sk-..."]} deletes it.