OpenCode has two documented ways to describe a custom provider, and most guides show only one of them. On 28 November 2026 the current opencode.ai docs use a providers block with package and settings, while the previous docs, which many tutorials copied, use provider with npm and options. This post gives you both, field by field, filled in for One AI API Key, plus a three-line curl test that proves your key works before you touch a config file, and a troubleshooting table that maps each error text to the one check that isolates it. Everything about OpenCode below comes from its own documentation pages and JSON schema, read that day.
What does OpenCode need from a custom provider?
Three things: an endpoint, a credential and a list of model ids. That is all a custom provider is. OpenCode’s catalog (it takes its provider and model list from models.dev) covers the big names. For anything else, the providers page says to add a provider “when its API is not already in the catalog”, and its own example is an OpenAI-compatible endpoint with a name, a key source, a runtime package, a base URL and a first model.
For this gateway the three values are fixed:
| What OpenCode asks for | Value for One AI API Key | Where it comes from |
|---|---|---|
Endpoint (baseURL) |
https://api.oneaiapikey.com/v1 |
The quickstart and authentication docs |
| Credential | A key starting with sk-, created under Keys in the console |
Your account |
| Model ids | Exact ids from GET /v1/models, for example z-ai-glm-5.3:free |
The models page and the free model list |
The runtime package is the part that confuses people, so it is worth one paragraph. OpenCode builds on the AI SDK, and the AI SDK’s OpenAI-compatible provider takes a baseURL, an apiKey that is sent as a Bearer header, optional extra headers, and an includeUsage switch for streaming. Any service that speaks the Chat Completions format can sit behind it. Ours does: the chat completions reference documents the request and the streaming page documents stream_options with include_usage. Our coding agent key guide shows the same idea for Cline, Cursor, Codex CLI and Aider.
How do you test the key before touching OpenCode?
Run two curl calls. When a setup fails, the first question is always “is it the key or the config?”, and curl answers it in ten seconds without any OpenCode in the loop. Every later step in this post assumes these two calls pass.
export ONEAIAPIKEY_API_KEY="paste-your-key-here"
BASE="https://api.oneaiapikey.com/v1"
# 1. Does the key work at all? Prints only the HTTP status, never the key.
curl -s -o /dev/null -w "models: %{http_code}\n" "$BASE/models" \
-H "Authorization: Bearer $ONEAIAPIKEY_API_KEY"
# 2. Does the exact model id answer? Small max_tokens keeps it cheap.
curl -s -w "\nchat: %{http_code}\n" "$BASE/chat/completions" \
-H "Authorization: Bearer $ONEAIAPIKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "z-ai-glm-5.3:free", "max_tokens": 20, "messages": [{"role": "user", "content": "Reply with the word ready."}]}'Read the output like this. models: 200 means the key is valid and the base URL is right. chat: 200 with a short reply means the exact model id works and your account may call it. Anything else tells you which layer to fix, and the error reference lists every status the gateway returns. On Windows PowerShell the first call looks like this (use curl.exe, because plain curl is an alias for another command there):
$env:ONEAIAPIKEY_API_KEY = "paste-your-key-here"
curl.exe -s -o NUL -w "models: %{http_code}`n" https://api.oneaiapikey.com/v1/models -H "Authorization: Bearer $env:ONEAIAPIKEY_API_KEY"We also ran the failure case against the live host on 28 November 2026, without a key, so you can recognise it. A call to /v1/models with no key returns HTTP 401 and this body:
{"error":{"code":"","message":"Invalid API key. Create or copy one under Keys in the console (oneaiapikey.com/console/keys) and send it as Authorization: Bearer YOUR_KEY. (request id: ...)","type":"api_error"}}That is the standard meaning of 401 Unauthorized on MDN: the request lacks valid credentials. If you see this text from inside OpenCode later, the key never reached us in the form we expect, and the problem is in how OpenCode read your config, not in your account. We use the same “test outside the tool first” habit in the free gateway test protocol, which runs eight checks (identity, token counts, latency, errors, streaming, tools, billing and support) and links the real-model verification guide.
If you do not have a key yet, sign in with Google and create one under Keys. There is no card field. The key works for the free ids at once.
Which OpenCode do you have, V1 or V2?
This is the question the older tutorials skip, and it changes the file you write. OpenCode’s documentation is now split into a current version and a previous one. The previous page carries a banner saying “You’re viewing a previous version of the docs”, with a link to the latest. The current docs include a Migrate from V1 page that states two facts you can rely on: “The V1 config format remains supported”, and conversion is optional.
So you have a choice, not a forced upgrade. The table below lists the fields you will meet in a custom provider block, taken from the migration page, the two provider pages and the JSON schema.
| Meaning | V1 form (previous docs) | V2 native form (current docs) |
|---|---|---|
| Top-level map | provider |
providers |
| Runtime package | npm: "@ai-sdk/openai-compatible" |
package: "@opencode/ai/providers/openai-compatible" |
| Endpoint | options.baseURL |
settings.baseURL |
| Key from environment | options.apiKey: "{env:NAME}" |
env: ["NAME"] or settings.apiKey: "{env:NAME}" |
| Extra request headers | options.headers |
headers |
| Model’s real id sent upstream | id |
modelID |
| Token limits | limit: { context, output } (both required) |
limit: { context, input, output } (all optional) |
Two details in that table matter more than they look. First, the V1 schema marks both context and output as required inside a model’s limit object, so a limit with only context fails validation in V1 but is fine in V2. Second, the schema for a provider block in both versions has additionalProperties: false, meaning an unknown key is an error, not a warning. The migration page says the same thing in prose: OpenCode recognises mixed V1 and V2 fields in a few places, but it does “not recursively infer formats inside individual agents, providers, commands, or models”, so each provider entry has to be entirely one format. A V2 package key sitting next to a V1 options block is an easy way to end up with a provider that never appears.
When the migration page converts a V1 provider, it writes the package as aisdk:@ai-sdk/openai-compatible, while the V2 custom-provider example on the providers page uses the native @opencode/ai/providers/openai-compatible. Both strings appear in OpenCode’s own pages, so we use the native one in the V2 file below and the AI SDK one in the V1 file.
Which config should you write?
I installed OpenCode recently
opencode --version if you are unsure what you have; the docs list it as the first thing to include in a bug report.I already have an opencode.json that works
I copied a tutorial and nothing shows up
provider, npm and options it is V1; if it says providers, package and settings it is V2. A block that has some of each is the likely culprit. The troubleshooting table further down starts with this check.I run OpenCode in CI or scripts
/connect. The CLI docs describe opencode run for scripts and CI. Create a separate key with a spend limit for the job, as the one key per project guide explains.How do you add the provider in the V1 format?
Use this file if your OpenCode is older, or if you keep a working V1 config. The V1 custom-provider recipe has two parts: save a credential with /connect, then describe the provider in opencode.json. We use an environment variable for the key, which skips the first part.
Create or edit ~/.config/opencode/opencode.json for every project, or opencode.json in a project root for one. The docs name both locations.
{
"$schema": "https://opencode.ai/config.json",
"model": "oneaiapikey/z-ai-glm-5.3:free",
"provider": {
"oneaiapikey": {
"npm": "@ai-sdk/openai-compatible",
"name": "One AI API Key",
"options": {
"baseURL": "https://api.oneaiapikey.com/v1",
"apiKey": "{env:ONEAIAPIKEY_API_KEY}"
},
"models": {
"z-ai-glm-5.3:free": {
"name": "GLM 5.3 (free lane)",
"limit": { "context": 262144, "output": 16384 }
}
}
}
}
}How the pieces fit, each point checked against the V1 providers page:
- The key under
provideris the provider id. It becomes the prefix of every model reference, which is why the top-levelmodelreadsoneaiapikey/z-ai-glm-5.3:free. npm: "@ai-sdk/openai-compatible"is the package for any API that serves/v1/chat/completions. If a model used/v1/responsesinstead, the docs say to use@ai-sdk/openai. Our chat completions endpoint is the right match for the first package.options.baseURLincludes/v1. OpenCode appends the endpoint path itself.options.apiKeytakes the{env:NAME}substitution that the config page describes, and if the variable is unset it is replaced with an empty string. That detail explains a lot of 401 errors: an unset variable does not crash OpenCode, it sends an empty key.- Each key under
modelsis a model id from our list, andnameis only the label in the picker. limittells OpenCode how much context you have left. The docs say standard providers pull these numbers from models.dev, and a custom provider does not, so you supply them. The context value is the 262,144 tokens our model page lists for this id. Theoutputvalue of 16,384 is our own modest choice, because V1 requires the field; raise it if you want longer single replies.
If you prefer to save the key instead of reading it from the environment, the V1 recipe is: run /connect, scroll to Other, enter a unique provider id (use oneaiapikey so it matches the config), and paste the sk- key. The docs add that the id you enter must match the id in your config, and they put the credential in ~/.local/share/opencode/auth.json. Then drop the apiKey line from the block.
How do you add the provider in the V2 format?
Use this file for a fresh install that follows the current docs. The shape is different but the same three values go in.
{
"$schema": "https://opencode.ai/config.json",
"model": "oneaiapikey/z-ai-glm-5.3:free",
"providers": {
"oneaiapikey": {
"name": "One AI API Key",
"env": ["ONEAIAPIKEY_API_KEY"],
"package": "@opencode/ai/providers/openai-compatible",
"settings": {
"baseURL": "https://api.oneaiapikey.com/v1"
},
"models": {
"z-ai-glm-5.3:free": {
"name": "GLM 5.3 (free lane)",
"limit": { "context": 262144, "output": 16384 }
}
}
}
}
}What changed, according to the current providers page:
providersis keyed by provider id, and models are referenced asoneaiapikey/z-ai-glm-5.3:free, the same as before.envis an ordered list of environment variable names “that can provide the credential”. Our one variable isONEAIAPIKEY_API_KEY. The docs’ own gateway example uses exactly this pattern for an OpenAI-compatible gateway with its own model inventory: anenvlist, the compatible package, asettings.baseURLand amodelsmap.- Model keys can contain more characters than the provider id can. The model reference rules on the models page say the provider part ends at the first
/and cannot contain/or#, while the model part may contain extra/characters but not#. A colon, as in:free, is fine. limitfields are all optional. For a model outside the catalog, the models page says OpenCode assumes JSON tool support, text and image input, a 200,000-token context and a 32,000-token output, and calls these “fallback assumptions, not detected capabilities”. Setting the real context avoids a wrong guess, so we set it.- If the model does not support tools or images, the page says to set accurate
capabilities. A coding agent without working tool calls is not useful, which is why the smoke test further down uses a task that needs one.
The V2 docs also describe a trap that the older guides never had. Credentials from an environment variable must be set “on the server process that runs model requests”. OpenCode V2 uses a shared background server, so a variable you export in a new terminal tab may not be visible to a server that started earlier. The provider accounts page documents two fixes: start a private server with the variable in front (opencode --standalone), or put the variable in the service’s managed environment with opencode service set env, which stops the running service so the next command starts it with the new value. If the curl test passes but OpenCode still reports a missing key, restart the service with opencode service restart after setting the variable, and check opencode auth list, which the docs say shows environment connections as type environment.
Optional: two documented features combine into a useful trick. V2 accepts string-valued headers on a provider, and the gateway reads an X-Fallback-Models header with up to three comma-separated ids, tried in order when the provider fails before answering (see the headers reference). Together:
"oneaiapikey": {
"name": "One AI API Key",
"env": ["ONEAIAPIKEY_API_KEY"],
"package": "@opencode/ai/providers/openai-compatible",
"settings": { "baseURL": "https://api.oneaiapikey.com/v1" },
"headers": {
"X-Fallback-Models": "z-ai-glm-5.3-flash:free, deepseek-deepseek-v4.1-flash:free"
},
"models": { "z-ai-glm-5.3:free": { "name": "GLM 5.3 (free lane)" } }
}In the V1 format the same header goes under options.headers. Our uptime and fallbacks guide explains the retry rules, and the DeepSeek outage guide applies them to a real incident. Remember that a header sent on every request applies to every request, including the ones where you want the exact model you named.
Where should the key live?
In an environment variable, loaded by your shell profile or a secrets tool, and nowhere inside the repository. That is the rule of the twelve-factor app: credentials are config, and config belongs in the environment, not in code. OpenCode helps here because both config formats can read the variable by name, so the committed file holds only the name.
A short ranking of where a key can sit, from safest to riskiest for a coding agent:
- An environment variable read by name (
{env:NAME}in V1,envlist in V2). The file holds no secret. - A saved credential from
/connect. It lives outside your project, inauth.json(V1) or the server database (V2), so it never lands in git by accident. The V2 docs say not to edit the database by hand. - A file reference. The config page also documents
{file:path}substitution, with a path relative to the config or starting with~/. It keeps the key out of the config, but the secret file needs its own care. - The key typed into the config itself. It works. It is also how keys end up in public repositories, and it is the first thing a leak scan finds.
Agents raise the stakes because they read and write files, run shell commands and can echo environment content into a prompt if you let them. Give OpenCode its own key, not the one your production app uses, and set a spend limit on it in the console. The post on keys per project with spend limits shows how, and the key leak checklist tells you what to do in the first hour if one escapes anyway. For the hands-on view of what a coding agent should be allowed to spend, see the guide to runaway agent token bills and the cost control docs.
Where a request travels
How far does a free allowance go with an agent?
Not as far as it does in chat. A chat message is one request. A coding agent runs a loop: it asks the model, runs a tool, sends the result back and asks again, as the loop in our tool calling docs shows. Each round trip is a separate request, and each one resends the growing conversation. So the request cap and the token cap bite at different points, and for an agent the request cap comes first.
The free lane gives each account 100 requests and 3,000,000 tokens a day across all 48 :free ids, refilling at 00:00 UTC (05:30 IST). Enter your own numbers below. Both inputs are assumptions you supply, not measurements, so replace the defaults with counts from your console usage log after a real session.
How many agent tasks fit in one free day?
- Tokens per task
- 108,000
- Tasks allowed by the 100-request cap
- 8
- Tasks allowed by the 3,000,000-token cap
- 27
- Tasks you can finish today
- 8
- Which cap stops you first
- The request cap
Free lane limits imported from the site config: 100 requests and 3,000,000 tokens a day per account, shared by every free id. Past the cap the gateway answers 429 with code daily_limit_free.
With the defaults, the arithmetic is: 12 requests times 9,000 tokens is 108,000 tokens a task. The token cap allows floor(3,000,000 / 108,000) = 27 tasks, and the request cap allows floor(100 / 12) = 8. You finish 8 tasks, and the request cap is what stops you. The chart shows how fast that falls as tasks get longer.
Tasks per free day, limited by the request cap alone
- 5 requests per task20
- 10 requests per task10
- 20 requests per task5
- 40 requests per task2
- 100 requests per task1
Two habits stretch the allowance. Keep prompts short and tell the agent to work in small steps, since every step is billed for the whole history again. And set a cheap model for side jobs: OpenCode’s V2 docs describe a title agent that takes its own model selection, so a tiny model can handle titles while the main model does the work. The post on cutting LLM API costs covers ten more tactics, and the 429 guide separates the three causes of a 429 so you do not mistake the daily cap for a provider outage. Paid use has no request cap here, only your balance and the limit you set per key; credit is added by email today, as the pricing page explains.
How do you check that OpenCode can actually use it?
Run one short prompt, then one task that needs a tool. A provider can pass a plain chat test and still fail as an agent, because agents depend on tool calls and streaming.
Step one is a one-shot prompt. The CLI docs describe opencode run as the way to submit a prompt without opening the interactive interface, built for scripts and CI.
opencode run "Reply with the single word: ready"If a reply comes back, the provider, key and base URL are right. Open /models in the interactive UI and confirm the provider name appears with your model. Step two is a real tool call: ask the agent to read a small file in the project and summarise it. A model that cannot call tools will answer from guesswork or ignore the file, and that is a model problem, not a config problem. Our models page and each model’s own page list what we know; for the free ids the catalog does not list a tools flag, so this test is the evidence. Try another :free id if one fails, since all 48 share the same allowance.
Then look at the console usage log. Each request should show up with its model and token counts. That is also the cleanest way to count requests per task for the calculator above. Because OpenCode may send small housekeeping requests besides your own steps, trust the log, not your memory of how many times the agent paused.
What do the errors mean?
Work from the outside in. The diagram shows the order we use; each rung isolates one layer, so a failure points at one fix instead of five guesses.
Isolate the failing layer
The table maps each symptom to its most likely cause and the check that proves it. The gateway texts are the ones in our error reference; the OpenCode texts are from its providers page and troubleshooting guide.
| Symptom | Likely cause | Check |
|---|---|---|
| 401 “Invalid API key…” | Key missing, mistyped or disabled; {env:NAME} was unset and became an empty string |
Run the curl test with the same variable. Then opencode auth list |
| 404 “Unknown endpoint. The API lives under /v1” | baseURL has no /v1 |
Set it to https://api.oneaiapikey.com/v1 exactly |
| 404 “Invalid URL (POST /v1/chat/completions/extra)” | Path added after /v1 |
Remove everything after /v1 from baseURL |
Provider missing from /models |
JSON syntax error, id mismatch with /connect, or V1 and V2 fields mixed in one block |
Validate the file against $schema; check every key in the block belongs to one format |
| “Model unavailable: provider/model” (V2) | Model key absent or disabled; alias confusion | Check the models map key, not modelID |
| “No model is available for session” (V2) | No enabled model is selectable yet | Finish provider setup, then pick a model in /models |
503 model_not_found, “No available channel” |
Model id typo, or not enabled for your account | GET /v1/models and copy the id exactly |
429 daily_limit_free |
The shared free allowance is used up | Wait for 00:00 UTC, or use a funded balance |
402 paid_needs_deposit |
A paid model on a $0 balance | Pick a :free id, or email to add credit |
403 insufficient_user_quota |
Balance, plan allowance or the key’s spend limit is used up | Check Billing and the key’s limit in the console |
| Request fails after a long wait | OpenCode’s own timeout | V2: raise settings.headerTimeout or settings.chunkTimeout |
On the timeout row: the V2 docs say HTTP requests wait up to five minutes for response headers and up to fifteen minutes between streamed chunks, and that a request exceeding either limit fails with a transport error after OpenCode retries a timed-out request up to three times. Both limits can be changed in milliseconds, per provider. Our error docs cover when the gateway itself times out. Slow replies on busy free routes are normal; the status page shows what we measure.
For 429s specifically, remember what the daily cap counts. It is one counter across every free id and across chat and API together. Chatting in the browser chat in the morning spends the same 100 requests an agent uses in the afternoon. The headers reference lists the response headers that tell you what is left.
Why would you use this gateway with OpenCode at all?
We publish this post, so weigh the reasons accordingly. OpenCode already works well without us: its catalog covers many providers, it documents an optional paid subscription called OpenCode Go for coding models its own team tests, and for OpenRouter it ships a native provider, so an OpenRouter user needs no custom block. If you want zero configuration and one vendor, those are better starts. Our OpenRouter alternatives post and the migration guide cover that comparison honestly, and the LLM gateway versus direct API post lays out when a direct provider is the better answer.
A custom provider block makes sense when one of these is true for you:
- You want a free route that needs no card. Google sign-in, a key, and 48 free ids on a shared allowance of 100 requests and 3,000,000 tokens a day. The free tier comparison sets that against the published limits of other providers.
- You want one key and one balance for several model families, with the model switched by editing one line. The unified API trade-offs post names what you give up for that: an extra network hop and a wider blast radius if the key leaks.
- You want published prices and a public record. Rates are on /pricing and /models; measured availability is on /status; what we monitor and cannot see is on /transparency; and /rankings shows real usage by model.
- You want to switch back easily. The provider block is 15 lines. Deleting it returns you to whatever OpenCode used before. The vendor lock-in exit plan turns that into a drill.
Do not take our word for any of it. Run the two curl checks, use the verification guide to confirm the model you named is the one answering, and read the post on cheap reseller risks and the free key scam patterns before you hand any gateway your key. The same caution applies to installers: our setup here is a config edit and an environment variable, with no script to run, a point the relay malware checks explain in detail.
On data: a coding agent sends file contents to the model, so what the provider does with them matters more here than in chat. On our side, prompts and answers are not stored by default; we keep usage records (model, token counts, charge). We do not train on your data, and the company that runs the model receives the request. The privacy guide and the data processing questions give the full list of what to ask any gateway. Acceptable use applies to every request, and the policy is short.
Before you call it done
0 of 9 done
Not started
Begin with the two curl checks. Every other step depends on them.
What if it still does not work?
Go back to the diagram and stop at the first rung that fails. These are the five causes we would rule out, in this order:
- The provider block mixes field names from the two formats.
baseURLis missing/v1, or has a path after it.- The environment variable is set in a shell that is not the one the OpenCode server runs in (V2), or is unset (both).
- The model id in
modelshas a typo, so the picker shows nothing or the gateway answers 503. - The daily free allowance is spent, and the 429 looks like a config failure.
If curl passes both checks and a clean config still fails, read the log the OpenCode troubleshooting page points to (~/.local/share/opencode/log/opencode.log, with role=server lines for provider activity), and strip keys and prompts before sharing any of it. Then write to support@oneaiapikey.com with the request id from the error body; the id is in every error the gateway returns, as in the 401 sample above. The quickstart and the tool guide for OpenCode are the maintained reference for this setup, and the config generator can write a provider block for several agents from a model id and a key name. If you are choosing among providers rather than wiring one, the provider checklist and the OpenAI-compatible provider test matrix tell you what to compare, and the gateway primer explains why one key can reach many models at all. Anyone coming from the OpenAI API can use the two-line switch guide for the same idea outside OpenCode, and our review states what the service does and does not do.
Get a key and run the two curl checks
$10 sign-up credit, 48 free models sharing 100 requests and 3,000,000 tokens a day, no card.
Frequently asked questions
Does OpenCode support a custom OpenAI-compatible provider?
package set to @opencode/ai/providers/openai-compatible and the endpoint under settings.baseURL. The previous docs (V1) use npm: "@ai-sdk/openai-compatible" with options.baseURL. The migration guide says the V1 format stays supported, so either file works. The side-by-side table above lists every field that changed.Which base URL do I put in OpenCode for this gateway?
https://api.oneaiapikey.com/v1, with /v1 and nothing after it. OpenCode adds the endpoint path itself. If you leave /v1 out, the gateway answers 404 with the message "Unknown endpoint. The API lives under /v1", which we confirmed against the live host on 28 November 2026. The chat completions reference shows the full request shape.Can I use the free models in OpenCode?
:free share 100 requests and 3,000,000 tokens a day per account, and they work at a $0 balance. A coding agent sends one request per step, so the request cap binds long before the token cap; the calculator above shows where. The free tier comparison puts that cap next to other providers.Where does OpenCode store the key I give it?
/connect saves credentials in ~/.local/share/opencode/auth.json. The V2 docs say saved keys live in the server's SQLite database, and that V2 imports the old auth.json on migration. An environment variable stays in your shell and is never saved by OpenCode. Whichever you pick, keep the key out of any file you commit, as the key leak guide explains.Why does my provider not show up in /models?
/connect (V1), or a provider block that mixes V1 and V2 field names. OpenCode's own schema rejects unknown keys inside a provider block, and the migration guide says to keep each provider entry entirely in one format. The troubleshooting table in this post has the checks in order.Does the Anthropic-compatible package work against this gateway?
anthropic-compatible package, and our gateway has an Anthropic-format endpoint documented on the Messages API page. This post covers only the OpenAI-format route, which the OpenCode docs describe in full for custom providers.