OpenCode with a LiteLLM gateway

Route the OpenCode terminal agent through your self-hosted LiteLLM gateway so every coding session uses authenticated keys, tracked spend and the same budgets as the rest of your AI traffic.

On this page

How OpenCode connects to a LiteLLM gateway

A platform team that wants developers to use OpenCode without distributing shared provider keys or losing track of spend points OpenCode at an existing LiteLLM instance and gives each developer a LiteLLM API key. That is the whole connection model: OpenCode sends its model requests to the gateway, the gateway authenticates the key, and the gateway forwards the request to whichever model the key is allowed to use. The configuration itself follows the method in the LiteLLM docs: OpenCode integration, so the work for the team is mostly deciding who gets keys, which models they reach and where the gateway is reachable from developer machines. The gateway's own deployment, database and key model are covered in the LiteLLM pillar, not here.

In practice, centralized authentication means no developer holds a raw provider credential. Provider keys stay in the gateway configuration, and every request is tied to a LiteLLM key that can be revoked, rotated or restricted to specific models without touching the developer's laptop beyond a changed environment variable. Usage tracking means each request is recorded against the key that made it, so spend can be read per person or per team rather than per shared account. Cost controls are the budgets and limits attached to those keys. Confirm with your own configuration which budget and rate limit types your LiteLLM version applies to virtual keys, because enforcement settings differ by release and by how keys are created.

Before rollout, decide three things with the team lead and the security owner: which models OpenCode keys can call, what budget a developer key carries, and where the LiteLLM key is stored on developer machines. Check that the gateway endpoint is reachable from every network where OpenCode runs, and test one key end to end, including a request that should be refused because the model is not on its allow list. A key that fails this test is a configuration finding to fix before wider access, not a reason to add a shared fallback key.

What you need before you configure OpenCode

OpenCode only needs an endpoint and a key, but the gateway behind it has to be ready first. The items below cover the LiteLLM instance, the team and its keys, the network path from developer machines, and the OpenCode build you test against. Work through them in order, since the gateway decisions shape the client configuration.

PostgreSQL behind virtual keys

Virtual keys, per-key budgets and spend tracking all need a PostgreSQL database, so it is a hard prerequisite rather than an option for this setup. Confirm that the database is provisioned, backed up and reachable from every proxy instance before you issue any key to a developer. Without it, the budgets you plan to rely on for OpenCode usage do not exist.

Virtual keys docs

Redis once you scale out

Once more than one proxy instance runs, LiteLLM expects Redis 7.0 or newer for shared rate limits, router state and cache. A single-instance pilot can skip it, but a team rollout that adds replicas without Redis will enforce TPM and RPM limits inconsistently across instances. Confirm the Redis version and its placement before you add a second replica.

Production guide

Release line and support window

Choose the LiteLLM release line you will run and record it in your change log. LiteLLM maintains support for the four most recent stable minor versions for both open source and Enterprise deployments, so an older gateway can fall out of support while OpenCode keeps moving. Check the current release list before you pin the image, and plan upgrades on a regular cadence.

Supported minor versions
4
LiteLLM releases

A team with keys and a model allowlist

Create a dedicated team for developers who will use OpenCode, then issue each person a virtual key scoped to the models that team is approved to call. Restricting keys to specific models keeps a terminal agent from reaching expensive or unapproved routes by accident. Decide who owns the allowlist, who approves changes to it, and how budgets are assigned to the team before anyone installs the client.

Network path from developer machines

OpenCode runs on laptops and workstations, so every developer machine must reach the LiteLLM proxy over a route your security team has approved. Confirm the hostname, TLS termination, and any VPN or IP allowlisting that applies to the proxy. Test the path from a standard developer device, not only from the server subnet, because a working health check does not prove that a laptop on the corporate network can connect.

OpenCode version and configuration keys

Pin the OpenCode release your team tests against and record it alongside the LiteLLM version. The release number and the configuration keys that point OpenCode at a custom provider are not supplied here, so confirm them with the OpenCode project and the LiteLLM tutorial before you write any config file. Retest when either side changes, since a client update can alter how it reads provider settings.

OpenCode tutorial

Configuring OpenCode to use LiteLLM step by step

This sequence takes a team from a running LiteLLM gateway to an OpenCode session whose model calls carry a scoped, budgeted key and appear in the gateway's spend and request logs.

  1. Confirm the gateway is healthy

    Before anything else, the platform team checks that the LiteLLM proxy answers on its health endpoint and that the database and any configured model providers respond. Run the health check from the network segment where developers will connect, not only from the host itself, so that DNS, TLS and firewall rules are tested as well. The step is done when the check returns a healthy status from a developer workstation or a representative runner. If it fails, resolve the gateway issue first, because every later check depends on it.

  2. Create a team and its scoped virtual key

    An administrator creates a team in the LiteLLM admin UI, then issues a virtual key for that team. Set a budget, TPM and RPM limits, and an allowlist of the models this team may call, so that the key cannot reach models the organization has not approved for coding agents. Record the key's identifier and the budget values in your change record. The step is done when the key appears under the team with the limits you set and the model list shows only the approved models. Check the key's exact field names and limit options against the LiteLLM virtual keys documentation before you script this.

  3. Set the base URL and key in OpenCode

    The developer adds the LiteLLM base URL and the virtual key to OpenCode's provider configuration so that OpenCode sends its requests to the gateway instead of directly to a model provider. Confirm the exact configuration keys in LiteLLM's OpenCode integration tutorial, because the names depend on the OpenCode version in use. Keep the key out of project files and commit history, and store it in an environment variable or the user's own secret store. The step is done when OpenCode starts and lists the models the gateway exposes for that key.

  4. Select a model the key can reach

    In OpenCode, the developer chooses one model from the list that the virtual key is permitted to call. Pick a model that is on the allowlist and that the team has agreed to use for this work. If the chosen model is missing from the list or the request is refused, the mismatch is between the key's allowlist and the model's route on the gateway, so fix it in the gateway rather than adding models to the developer's local config. The step is done when the model is selected and the session shows it as the active model.

  5. Run one request through the gateway

    The developer sends a short, non-sensitive prompt in OpenCode, such as asking for a summary of a small test file. Use a test repository or a dummy file rather than production code during this check. The response should arrive normally, and the gateway should record one request against the team's key. The step is done when the response returns without error and the request is visible in the gateway's request logs.

  6. Confirm the request in spend and logs

    The administrator opens the spend view and the request logs in the LiteLLM admin UI and finds the request from the test. Check that the spend is attributed to the correct key and team, that the model name matches the one selected in OpenCode, and that the token counts are recorded. If the request is missing from spend, check that the logs are being written and that spend updates have reached the database, since batched writes can add a short delay at scale. The step is done when the request, its team, its model and its spend are all visible in the gateway's records.

  7. Remove the key from shell history

    If the developer pasted the virtual key into a terminal, a command line, or a script during setup, remove it from shell history and any shared history file, then clear the in-memory variable for that session. Move the key into the approved local secret store or environment file that OpenCode reads. Confirm the history file no longer contains the key by searching it for the key prefix. The step is done when the search returns no matches and OpenCode still starts using the stored key. Rotate the key if it may have been visible to anyone else.

How a coding session reaches a model through the gateway

The session starts on a developer workstation, where OpenCode reads a LiteLLM API key and sends its model requests to the gateway instead of directly to a provider. The LiteLLM proxy checks the virtual key, applies its budget and rate limits, and hands the request to the router, which selects an approved provider or private model. PostgreSQL holds keys and spend records, and Redis joins once more than one proxy instance runs. Check that the trust boundary sits where your network policy expects it.

Request path from OpenCode through the LiteLLM gateway to approved models.

Choosing key scope for individuals and teams

A personal virtual key gives each developer their own credential that LiteLLM ties to one identity. Every request OpenCode sends carries that person's key, so spend, rate limits and model access can be read and enforced per individual. This is the option that gives the cleanest attribution, and it is the one most aligned with a per-person governance model. The cost is administrative: someone must issue, track and retire one key for each developer, and offboarding must include revoking that key.

  • Attribution: Usage in the spend logs maps directly to a named person, which simplifies review and incident questions.
  • Budget granularity: Per-key budgets can be set for each developer, and per-user budgets can apply on top if the key is linked to a user.
  • Rotation effort: Rotation touches many keys, so automate issuance and revocation through your identity or provisioning process where possible.
  • Leak exposure: A leaked key exposes only one person's access and budget, which limits blast radius.
  • Offboarding: Confirm that departing staff lose gateway access on the same day their directory account is disabled.

Before rollout, confirm with your LiteLLM administrator how keys are created and whether per-user identities are linked through SSO or manual provisioning.

Mapping OpenCode settings to LiteLLM identity and spend

This table maps each OpenCode setting to its LiteLLM counterpart, from the key a developer holds to the spend record the gateway writes. Read it as a checklist for deciding where identity, budgets and provider credentials live, and mark each Enterprise-dependent row for confirmation against the edition you plan to run. The main takeaway is that developers should hold only a gateway key, while budgets, model lists and provider secrets stay on the gateway.

OpenCode elementLiteLLM counterpartEdition and what to confirm
API key in OpenCode configurationVirtual key issued by the gateway, scoped to one person or teamOpen source. Confirm the key is read from an environment variable, not written into a shared config file
Individual developerPer-user budget and rate limits on the keyOpen source for per-key and per-user budgets. Confirm your version supports the limits you need
Team or project using OpenCodeTeam-level budget owner with keys assigned to that teamTeam RBAC is listed as Enterprise. Confirm team administration against your edition
Model selected in OpenCodeModels the key is allowed to call, enforced at the gatewayOpen source. Confirm that a request for a model outside the key's list is refused
Request metadata such as user or project tagsFields recorded in spend logs for chargeback and reviewConfirm which metadata fields your version records and how they appear in reports
Provider credentials for hosted modelsStored on the gateway as model configuration, never on developer machinesSecret manager integrations are listed as Enterprise. Confirm the storage option you will use
Sign-in to the gateway admin UISSO for administrators and users of the admin UISSO is free for up to 5 users in v1.76.0 and later, then requires Enterprise. Confirm the count and version

Securing the OpenCode to LiteLLM path

OpenCode runs on developer machines, so the security of this setup depends on where the LiteLLM key lives, how the proxy is exposed, and which controls your edition of LiteLLM actually provides. The cards below cover the parts to decide and verify before rollout.

Key storage on developer machines

Each developer holds a LiteLLM virtual key that OpenCode reads from its configuration or environment. Treat that key as a credential: keep it out of shared repositories, dotfiles synced to cloud storage and project configuration committed to version control. Confirm in OpenCode's current documentation where it reads the key from, and whether a helper or environment variable is the safer option for your fleet. Never place the master key on a laptop.

OpenCode tutorial

Master key in a secret manager

The LiteLLM master key (LITELLM_MASTER_KEY) must start with sk- and should live in a secret manager, not in a container image, a Helm values file or a shell profile. It is the administrative credential that can mint virtual keys, so only the gateway and the small group that administers it should be able to read it. Ask who can read it, how access is logged and how the value is rotated without redeploying every developer.

Production guide

Restrict virtual keys to approved models

A virtual key can be limited to specific models, so an OpenCode key issued for a coding team does not reach every provider behind the gateway. Build the allowed model list from the models your security review approved, and test that a key cannot call a model outside it. Re-check the list whenever a provider or model is added to the gateway configuration.

Virtual keys docs

Rotation and revocation

Plan how a key is replaced when a laptop is lost, when a developer leaves or when a key may have been exposed. Virtual keys can be revoked centrally at the gateway, so the working procedure is to revoke the key, issue a new one and confirm the old key is refused. Agree on the rotation interval and the owner of each team's keys before the first developer is onboarded.

Network exposure of the proxy

Decide whether the gateway is reachable only from corporate networks, VPN or a private endpoint, or from the public internet. Terminate TLS in front of the proxy and restrict inbound paths to the ports and sources you approve. Confirm that developers on remote networks can reach the gateway through your VPN or zero-trust access layer before you rely on it for daily work.

Open source versus Enterprise controls

The open-source proxy provides virtual keys, budgets, rate limits and model restrictions. Audit logs, IP allowlisting, JWT authentication with identity provider tokens and team-level guardrails are described in the Enterprise documentation, so confirm the edition you run before promising them to a security reviewer. Ask LiteLLM to confirm which features your license covers, and test each control in your own environment.

Free SSO limit
5 users
Enterprise docs

Testing that usage is tracked and budgets hold

Before OpenCode's traffic is treated as governed, run a short test plan against the gateway and keep the results. The first test is a budget refusal: create a virtual key with a deliberately small budget, use OpenCode with it until the budget is spent, and confirm that the next request is refused by LiteLLM rather than passed to the provider. Repeat the check with a team-level budget, because the spend that matters to finance often accrues at the team level and a per-key pass does not prove the team cap holds. Use a throwaway model or a low-cost model for this so the test itself does not create meaningful spend.

The second test is model restriction. Create a key limited to one approved model, point OpenCode's configuration at that key, and request a different model from the list OpenCode offers. The request should fail at the gateway. Then check the gateway's own record of the attempt, not only OpenCode's error message. A restriction that only appears in the client configuration is not a control, so confirm the key itself carries the model limit. Also confirm which key OpenCode reads from its environment, since a stale key in a shell profile can make a test appear to pass or fail for the wrong reason.

The third test is attribution. Send a few OpenCode sessions under a known test key and user, then open the spend logs and confirm each request shows the correct key, user and team. Check that the spend figure roughly matches the provider's usage for the same calls, and record any difference, because reconciling gateway spend with provider bills is its own exercise. The fourth test is revocation: revoke the test key and confirm that OpenCode's next request is rejected. Record the time between revocation and the first refused request, and keep the test log with the LiteLLM version you ran, because behavior can change between releases. Load testing and capacity limits belong to the performance work, so keep this plan focused on correctness and evidence.

Why OpenCode requests fail through LiteLLM

This table lists the failures teams most often see when OpenCode sends requests through a LiteLLM gateway, with the likely cause and first fix for each. Work down the rows in order, since authentication and key scope problems are the cheapest to check and often explain the rest. The last row lists what to collect before escalating to your gateway operators or LiteLLM support.

FailureLikely causeFix to try first
Authentication error (401)The key is wrong, expired, deleted, or pasted without the sk- prefix, or OpenCode is reading a stale environment variable.Confirm the key starts with sk-, re-export it in the shell that launches OpenCode, and test the key with a simple curl call to the gateway's models endpoint.
Model not foundThe virtual key is restricted to a model list that does not include the model name OpenCode requests, or the model name does not match a configured route.Compare the model string in the OpenCode config with the models the key can see, then either adjust the key's allowed models or correct the name.
Budget exceededThe key, user or team has reached its spend budget for the period, so the gateway rejects further calls.Check current spend for the key, user and team in the admin UI, then request a temporary budget increase from the gateway owner if the work is approved.
Rate limit hit (429)Agentic sessions send many requests and large prompts, so the key's TPM or RPM limits are exceeded in a short window.Check which limit is hit, reduce concurrent sessions or model calls per developer, and ask the gateway owner to review the limit against observed usage.
Base URL or path mismatchOpenCode points at the wrong base URL, omits the /v1 path, or uses a provider block that does not match the LiteLLM endpoint.Set the base URL to the gateway address exactly as documented in the LiteLLM OpenCode tutorial, and confirm the provider name and model identifiers match the config.
Proxy unreachable from developer networkDNS, TLS trust, VPN or firewall rules block the developer machine from reaching the gateway, or the certificate chain is not trusted.Test connectivity from the developer network with curl, confirm the internal CA is installed on the workstation, and check egress rules with the network team.
Database connection exhaustionThe gateway's PostgreSQL connections are used up under load, so key lookups and spend writes time out and requests fail intermittently.Check connection pool settings and active connections on the database, look for many instances or workers competing for connections, and escalate to the platform team if the pool is saturated.
What to collect before escalatingEscalations stall without the exact request, timing and identity involved.Record the OpenCode version, the model string and provider block (with the key redacted), the HTTP status and error body, the time with time zone, the key alias or user, and the gateway version and logs for that request ID.

Questions buyers ask about OpenCode and LiteLLM

Does OpenCode work with LiteLLM sign-in through SSO?

Single sign-on for the LiteLLM admin UI is a separate feature from API access for a tool like OpenCode. OpenCode connects to LiteLLM with a LiteLLM API key, which is the documented setup, so each developer or team gets a key that is authenticated, tracked and budgeted. SSO for the admin UI is supported with Google, Microsoft Entra ID, Okta and generic OIDC providers. From v1.76.0, SSO is free for up to 5 users, and an Enterprise license is needed beyond that, so check the LiteLLM Enterprise documentation before planning SSO for a larger group. Confirm with your identity team whether per-developer token sign-in into OpenCode itself is needed, because that pattern is not the documented path for this topic.

What does an OpenCode and LiteLLM setup cost, and what recurs?

Costs fall into four groups. Infrastructure is the largest recurring item: a PostgreSQL database for virtual keys and spend, optional Redis once more than one proxy instance runs, and compute for the proxy. LiteLLM's production guide suggests 1 vCPU and 4 GiB memory per worker as a starting point. Model provider usage is billed by each provider and is separate from the gateway. The gateway itself is open source under the MIT license for most of the code, and an Enterprise license is only needed for features such as SCIM, audit logs or team guardrails. Implementation effort is mostly one-time, covering configuration, key design, budgets and rollout, while upgrades and monitoring recur. Ask any quote to separate these lines.

How long does a pilot usually take, and what drives the timeline?

The duration depends on the scope agreed in writing before work starts, so no fixed figure applies here. The main drivers are the number of identity and access decisions, whether the database and Redis are already run by your platform team, how many provider accounts need to be connected, which models developers may use, and how many people sit in the pilot group. Choosing budgets and per-key model restrictions often takes longer than the technical install because policy owners must agree. Ask for a scope document with named milestones and a pilot exit review before any work begins.

What must our team provide for the pilot?

Your team should provide four things. First, identity access: named administrators who can approve how keys and users are created. Second, a PostgreSQL database, since virtual keys and budgets need one, plus Redis 7.0 or newer if more than one proxy instance will run. Third, provider accounts and credentials for each approved model provider, stored in a secret manager rather than in shared files. Fourth, a developer pilot group of a few engineers who will use OpenCode daily and report friction. Also agree which network the proxy will run in and how developers will reach it.

Can our internal platform team set this up without outside help?

Yes, a team with experience running PostgreSQL, container platforms and secrets management can deploy LiteLLM and point OpenCode at it using the documented tutorial. The harder parts are governance decisions: which models are approved, how budgets map to teams, how keys are rotated, what gets logged, and how the gateway is upgraded within a supported release line. Teams without spare capacity often use an implementation partner for the design and rollout, then keep operations in-house. DeployOpen plans, implements, documents and supports self-hosted platforms in your own infrastructure, and the split of work is agreed in writing.

How does OpenCode usage show up in spend and budget reports?

Each request made through a LiteLLM key is attributed to that key, its user or its team, so usage and spend can be read per person or per group. LiteLLM virtual keys support per-key, per-user and per-team budgets, TPM and RPM limits, temporary budget increases and restriction to specific models. Spend reported by the gateway should be compared with provider invoices during the pilot, because provider billing is the final record. Ask the implementer to show how keys map to teams before the pilot starts, so reports are useful from the first week.

What operational risks should we check before rolling OpenCode out widely?

The main risks are a gateway outage stopping all developer work, keys shared across people, budgets set too low or too high, and an unsupported gateway version. Plan for high availability with more than one proxy instance and Redis, rotate keys on a schedule, and keep LITELLM_MASTER_KEY in a secret manager. Keep the gateway on one of the four most recent stable minor versions, which LiteLLM says it supports for open source and Enterprise deployments. Test failover and budget enforcement in the pilot before expanding the group.

How DeployOpen scopes and delivers the OpenCode gateway integration

DeployOpen plans, configures, tests and hands over OpenCode pointed at your existing or new LiteLLM gateway, inside infrastructure you control. Each engagement starts from a written scope that defines which models, keys, teams and logs are covered.

How we scope

  • We confirm which LiteLLM gateway and version OpenCode will call, and who owns it.
  • We list the model routes, virtual key types and team budgets OpenCode users will need.
  • We agree in writing which developer machines, environments and identity methods are in scope.

How we build

  • We set up OpenCode provider configuration that points to the gateway and reads the key from a secret, not a plain file.
  • We restrict each key to approved models and check that budgets and rate limits block overuse.
  • We test requests end to end and confirm that usage appears in gateway spend and request logs.

How we hand over

  • We deliver a configuration guide, a rollout checklist and a short runbook for key rotation and budget changes.
  • We document what each team must confirm in its own environment, including network reachability and versions.
  • We walk your platform and security staff through the setup so they can review it against your controls.

How we support

  • Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer after handover.
  • A retainer can cover re-testing when OpenCode or LiteLLM releases change the configuration you rely on.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.