Skip to main content

pi

pi is a small coding agent for the terminal, found at https://pi.dev. It keeps the model providers it can use in a file called models.json. Routing pi through Spanway adds one provider, spanway, that serves every model your key may use, so your requests count against your team budget, pass the company guardrails and show up on the gateway's Logs page. pi does not read the usual OPENAI_BASE_URL or ANTHROPIC_BASE_URL variables, so the provider entry in models.json is the only way to point it at the gateway. spanwayctl pi writes that entry for you on every start, or you write it once by hand.

A real-world scenario​

A developer uses pi for quick edits and wants it on the company gateway. They run spanwayctl pi once. It reads the five models their key may use, writes them into ~/.pi/agent/models.json under a spanway provider with each model's real context window, and starts pi on the first of them. The next week the admin adds a new model to the key, and the next spanwayctl pi picks it up without the developer editing anything.

Prerequisites​

  • pi installed on your machine, see https://pi.dev. The gateway image does not contain pi.
  • The gateway's address, for example https://gateway.example.com, reachable from your machine.
  • A virtual key for pi, made as in the next section.
  • For option 1, spanwayctl on the same machine, see the CLI reference. spanwayctl pi is hidden from spanwayctl --help but works like the other agent commands.

Make a key for pi​

  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-pi. Leave Key Type on AI APIs.
  3. In Models, pick the chat models pi should list. spanwayctl pi lists exactly these, and starts pi on the first one the gateway returns.
  4. Open Optional Settings. Set Max Budget (USD), for example 100, with Reset Budget on monthly, and a Requests per minute Limit (RPM) such as 60. 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.
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "jane-pi", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "gpt-6.1-sol"], "max_budget": 100, "budget_duration": "30d", "rpm_limit": 60}'

Make a key for a tool explains every field.

Steps​

Option 1, spanwayctl pi​

  1. Start pi through spanwayctl. Everything after pi is passed on to pi.

    spanwayctl --base-url https://gateway.example.com --api-key sk-... pi
  2. To start on a particular model, pass it after pi. Your own --model comes later on the command line than the one spanwayctl adds, so yours wins.

    spanwayctl --base-url https://gateway.example.com --api-key sk-... pi --model spanway/gpt-6.1-sol

What spanwayctl pi does, in order:

  1. Checks the key with GET /v1/models. --skip-verify skips this check, but the model list below is still read, because pi cannot start without it.
  2. Reads the models your key may use from GET /v1/models, and their context window and output limit from GET /model_group/info. The limits are best effort: a model without them gets pi's own defaults of 128,000 and 16,384 tokens.
  3. Writes the spanway provider into ~/.pi/agent/models.json, or into models.json in the folder named by PI_CODING_AGENT_DIR. It replaces only the spanway entry under providers and keeps the rest of the file, your other providers included. The folder is created when it is missing.
  4. Sets SPANWAY_PROXY_API_KEY to your key for this run. The file only holds the reference $SPANWAY_PROXY_API_KEY, so the key is never written to disk.
  5. Starts pi with --model spanway/<first model>.

Because the spanway entry is rewritten on every start, any change you make to it by hand is lost on the next spanwayctl pi. Put hand-made settings in a provider with another name, as in option 2.

Option 2, a provider you write yourself​

  1. Put the key in your shell profile (~/.zshrc or ~/.bashrc) and open a new terminal.

    export SPANWAY_API_KEY="sk-..."
  2. Open ~/.pi/agent/models.json (create it if needed) and add a provider. The base URL includes /v1, because pi adds /chat/completions. Use a name other than spanway if you also use spanwayctl pi, so your entry is never overwritten.

    {
    "providers": {
    "spanway-manual": {
    "baseUrl": "https://gateway.example.com/v1",
    "api": "openai-completions",
    "compat": { "supportsStore": false, "supportsLongCacheRetention": false },
    "apiKey": "$SPANWAY_API_KEY",
    "models": [
    { "id": "claude-sonnet-5-5", "contextWindow": 1000000, "maxTokens": 128000, "reasoning": true, "input": ["text", "image"] },
    { "id": "gpt-6.1-sol", "contextWindow": 922000, "maxTokens": 128000 }
    ]
    }
    }
    }
  3. Start pi and pick the model with /model, or start on it directly with pi --model spanway-manual/claude-sonnet-5-5. Opening /model reloads the file, so edits take effect without restarting pi.

SettingWhat to putWhy
baseUrlhttps://gateway.example.com/v1, with /v1pi adds /chat/completions.
api"openai-completions"The chat completions format, which every model on the gateway serves.
compat.supportsStorefalseOne gateway address serves models from many vendors, so pi must not assume vendor-only features from the address.
compat.supportsLongCacheRetentionfalseSame reason. Not every model behind the gateway keeps a long prompt cache.
apiKey"$SPANWAY_API_KEY"pi reads the variable at start, so the file holds no secret. It sends the value as Authorization: Bearer <key>.
models[].idThe exact public names from GET /v1/modelsThe name sent to the gateway.
contextWindow, maxTokensFrom GET /model_group/info (max_input_tokens, max_output_tokens)pi uses them to decide when to compact a long session and how long an answer may be.
reasoning, inputtrue and ["text", "image"] when the model has themTurn on reasoning controls and image input in pi. spanwayctl pi does not write these, so its models are text-only and without reasoning controls in pi.

Expected result​

spanwayctl pi prints two lines and starts pi on a gateway model:

spanway: routing pi through proxy at https://gateway.example.com
spanway: synced 2 proxy models into /Users/jane/.pi/agent/models.json

On the gateway's Logs page (/ui/logs), open Filters, pick your Key Alias, for example jane-pi, and click Apply Filters. Each pi call is one row on /v1/chat/completions with the model, tokens and cost.

pi does not show response headers. To read them, send one request with the same key:

curl -i https://gateway.example.com/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Say hello"}]}'

Look at x-spanway-call-id (the id to search for on Logs), x-spanway-model-group and x-spanway-routing-reason (which model group served the call and why, see routing decision headers), and x-spanway-key-spend with x-spanway-key-max-budget for the budget left.

What works through the gateway​

FeatureWorksNotes
StreamingYesOver /v1/chat/completions with server-sent events.
Tool callsYes, when the model supports toolspi's tools run on your machine and travel as normal tool calls.
ImagesOnly with input setAdd "input": ["text", "image"] to the model in a hand-made provider. The synced provider leaves it out.
ReasoningOnly with reasoning setAdd "reasoning": true in a hand-made provider.
Prompt cachingProvider dependentLong cache retention is turned off in the provider on purpose. Cached tokens show in the cost on Logs.
The Responses API and stored responsesNosupportsStore is off and the provider uses chat completions.

Errors​

The first rows are what spanwayctl pi prints before pi starts. The rest are errors the gateway sends while pi runs, which pi shows in the session. The client error reference lists the gateway errors for every tool.

CaseStatusTextFix
pi is not installed where spanwayctl runsnoneCould not find `pi` on your PATH. Install it first: https://pi.devInstall pi on that machine.
The gateway cannot be reached, or TLS failsnoneCould not list models from the proxy: <error>Check --base-url and that the gateway runs. A company root certificate goes in REQUESTS_CA_BUNDLE for spanwayctl, see connection problems.
The key is rejected while listing models401 or 403The proxy returned HTTP <status> for /v1/models; cannot list models.Run spanwayctl login, or pass a valid --api-key.
The key may call no modelsnoneThe proxy returned no models for your key.spanwayctl pi adds that pi would have nothing to run. Ask the admin to add models to the key.
The gateway answered with something that is not a model listnoneUnexpected /v1/models response from the proxy: <error>Check that --base-url is the gateway and not another server.
Your models.json is not valid JSONnoneCould not read <path> as a JSON object: <error>. Fix or move the file, then retry.Fix the file, or move it away and let spanwayctl pi create a new one.
providers in your file is not an objectnone"providers" in <path> is not an object; fix or move the file, then retry.Make providers a JSON object keyed by provider name.
The file or folder cannot be writtennoneCould not write <path>: <error>Check the permissions on ~/.pi/agent, or set PI_CODING_AGENT_DIR to a writable folder.
Wrong or deleted key401Authentication Error, Invalid proxy server token passedWith option 2, check SPANWAY_API_KEY in the terminal that started pi. Running pi directly with a spanway provider written by spanwayctl pi needs SPANWAY_PROXY_API_KEY set.
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.
The key may not use the model403The requested model '<model>' is not available for this API key, or the model name is invalid.Pick another model in /model, or ask the admin to add it to the key.
The model name does not exist on the gateway400Invalid model name passed in model=<name>Make the id in models.json match a name from GET /v1/models exactly.
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 the budget.
The key's rate limit is reached429Rate limit exceeded for <scope>: <value>. Limit type: <type>.Wait, or ask for a higher RPM or TPM limit.
Wrong path, such as a doubled /v1404Not FoundSet baseUrl to https://gateway.example.com/v1 exactly once.

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, pi never reached the gateway. Open ~/.pi/agent/models.json and check baseUrl and that the key variable it names is set in the terminal that started pi.
  3. Run the curl above with the same address, key and model. If curl works and pi fails, compare the model id with the one in your curl.
  4. A short login token from spanwayctl login expires, after 24 hours by default (the gateway's SPANWAY_CLI_JWT_EXPIRATION_HOURS). Pass a virtual key with --api-key for long sessions.
  5. 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.

Rotate or remove the key​

To rotate, open the key on Virtual Keys, click Regenerate Key and set a Grace Period such as 24h. Pass the new key to spanwayctl --api-key, or put it in SPANWAY_API_KEY for a hand-made provider, and open a new terminal. models.json does not change, because it only names the variable. POST /key/{key}/regenerate does the same from the API and needs an Enterprise license. Without one, create a new key, switch to it and delete the old one.

To stop using the gateway, delete the spanway (and any hand-made) provider from models.json. 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.