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,
spanwayctlon the same machine, see the CLI reference.spanwayctl piis hidden fromspanwayctl --helpbut works like the other agent commands.
Make a key for pi
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Set Key Name to who and which tool, for example
jane-pi. Leave Key Type on AI APIs. - In Models, pick the chat models pi should list.
spanwayctl pilists exactly these, and starts pi on the first one the gateway returns. - Open Optional Settings. Set Max Budget (USD), for example
100, with Reset Budget on monthly, and a Requests per minute Limit (RPM) such as60. 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. - 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
-
Start pi through
spanwayctl. Everything afterpiis passed on to pi.spanwayctl --base-url https://gateway.example.com --api-key sk-... pi -
To start on a particular model, pass it after
pi. Your own--modelcomes later on the command line than the onespanwayctladds, 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:
- Checks the key with
GET /v1/models.--skip-verifyskips this check, but the model list below is still read, because pi cannot start without it. - Reads the models your key may use from
GET /v1/models, and their context window and output limit fromGET /model_group/info. The limits are best effort: a model without them gets pi's own defaults of 128,000 and 16,384 tokens. - Writes the
spanwayprovider into~/.pi/agent/models.json, or intomodels.jsonin the folder named byPI_CODING_AGENT_DIR. It replaces only thespanwayentry underprovidersand keeps the rest of the file, your other providers included. The folder is created when it is missing. - Sets
SPANWAY_PROXY_API_KEYto your key for this run. The file only holds the reference$SPANWAY_PROXY_API_KEY, so the key is never written to disk. - 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
-
Put the key in your shell profile (
~/.zshrcor~/.bashrc) and open a new terminal.export SPANWAY_API_KEY="sk-..." -
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 thanspanwayif you also usespanwayctl 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 }]}}} -
Start pi and pick the model with
/model, or start on it directly withpi --model spanway-manual/claude-sonnet-5-5. Opening/modelreloads the file, so edits take effect without restarting pi.
| Setting | What to put | Why |
|---|---|---|
baseUrl | https://gateway.example.com/v1, with /v1 | pi adds /chat/completions. |
api | "openai-completions" | The chat completions format, which every model on the gateway serves. |
compat.supportsStore | false | One gateway address serves models from many vendors, so pi must not assume vendor-only features from the address. |
compat.supportsLongCacheRetention | false | Same 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[].id | The exact public names from GET /v1/models | The name sent to the gateway. |
contextWindow, maxTokens | From 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, input | true and ["text", "image"] when the model has them | Turn 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
| Feature | Works | Notes |
|---|---|---|
| Streaming | Yes | Over /v1/chat/completions with server-sent events. |
| Tool calls | Yes, when the model supports tools | pi's tools run on your machine and travel as normal tool calls. |
| Images | Only with input set | Add "input": ["text", "image"] to the model in a hand-made provider. The synced provider leaves it out. |
| Reasoning | Only with reasoning set | Add "reasoning": true in a hand-made provider. |
| Prompt caching | Provider dependent | Long cache retention is turned off in the provider on purpose. Cached tokens show in the cost on Logs. |
| The Responses API and stored responses | No | supportsStore 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.
| Case | Status | Text | Fix |
|---|---|---|---|
pi is not installed where spanwayctl runs | none | Could not find `pi` on your PATH. Install it first: https://pi.dev | Install pi on that machine. |
| The gateway cannot be reached, or TLS fails | none | Could 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 models | 401 or 403 | The proxy returned HTTP <status> for /v1/models; cannot list models. | Run spanwayctl login, or pass a valid --api-key. |
| The key may call no models | none | The 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 list | none | Unexpected /v1/models response from the proxy: <error> | Check that --base-url is the gateway and not another server. |
Your models.json is not valid JSON | none | Could 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 object | none | "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 written | none | Could not write <path>: <error> | Check the permissions on ~/.pi/agent, or set PI_CODING_AGENT_DIR to a writable folder. |
| Wrong or deleted key | 401 | Authentication Error, Invalid proxy server token passed | With 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 key | 401 | Authentication 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 model | 403 | The 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 gateway | 400 | Invalid model name passed in model=<name> | Make the id in models.json match a name from GET /v1/models exactly. |
| The budget is spent | 422 | Budget 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 reached | 429 | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Wait, or ask for a higher RPM or TPM limit. |
Wrong path, such as a doubled /v1 | 404 | Not Found | Set baseUrl to https://gateway.example.com/v1 exactly once. |
Troubleshooting
- 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.
- If there is no row, pi never reached the gateway. Open
~/.pi/agent/models.jsonand checkbaseUrland that the key variable it names is set in the terminal that started pi. - Run the curl above with the same address, key and model. If curl works and pi fails, compare the model
idwith the one in your curl. - A short login token from
spanwayctl loginexpires, after 24 hours by default (the gateway'sSPANWAY_CLI_JWT_EXPIRATION_HOURS). Pass a virtual key with--api-keyfor long sessions. - Read the routing headers from the curl above.
x-spanway-attemptshigher than1means the gateway retried or fell back, andx-spanway-routing-reasonsays 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.
Related
- CLI reference for every
spanwayctlagent command. - Connect any client for the base URL rules shared by every tool.
- Client error reference for every gateway error with its cause.
- Make a key for a tool for the admin side.
- Codex, OpenCode and other CLI agents for the other terminal agents.