Blog · · 11 min read
BYOK for AI agents: accept customer-owned LLM keys without silent fallback or broken tool calls

An enterprise buyer asks whether your product's agent can run on their own OpenAI, Anthropic, Azure, or Bedrock account. Saying yes is easy. Shipping BYOK for AI agents is harder, because an agent stresses a customer route far more than a chat reply does. The key passes a test, then the second tool turn fails on the customer's endpoint. A gateway quietly retries a dead key on your credentials, so the tenant's prompts run under your provider agreement and the outage shows up as your bill. A rotated key breaks a run halfway through a write. This guide gives you a contract for customer-owned model credentials: prove the route before you enable agent features, make fallback a tenant decision, and record which credential served every call.
Direct answer: a customer-route contract
Treat each customer key, model, and endpoint as a route that has to earn agent features, then apply seven rules:
- Store a versioned credential record per tenant, with provider, endpoint, wire model, API surface, and a key version.
- Probe the exact route with a streamed tool call and the follow-up tool-result turn before any agent feature uses it.
- Enable features per route, so plain chat can run on a route that is not yet safe for tool-using workflows.
- Write the fallback policy into the tenant contract (
never,same-account-only, orplatform-allowed) and configure your gateway to match. - Bind each run to a credential version and recheck it before every model call.
- Log credential provenance on every model call: source, key version, route, and whether fallback happened.
- Attribute failures: errors from the customer's account go to the tenant admin and stay out of your product SLO.
Why BYOK breaks agent features that worked on your own keys
On platform keys you choose the model, API surface, quota, and fallback. With BYOK the customer owns some of those, and common tooling defaults assume they do not.
A key test checks authentication, not the agent loop. Vercel AI Gateway's Test Key button runs a small query on a cheap, fast model from the provider to confirm the credentials work (Vercel AI Gateway: Bring Your Own Key). GitHub sets a higher bar for its own agent: Copilot CLI's docs tell you to choose a model and endpoint that support tool calling and streaming (GitHub Docs: Adding LLM models to Copilot CLI).
Customer routes fail on protocol details your keys never hit. Three 2026 reports against VS Code's BYOK support show the pattern. First, a GPT-5.5 deployment behind an enterprise proxy rejected reasoning effort combined with function tools on Chat Completions and asked for the Responses API, which the customer's proxy did not expose (microsoft/vscode#318969). Second, Gemini 3.x through an OpenAI-compatible endpoint answered the first tool call and then rejected the next turn because the thought signature was not echoed back (microsoft/vscode#318970). Google's thinking guide says clients that manage their own history must resend thought blocks exactly as received, because the signatures inside them carry reasoning continuity (Google Gemini API: Thinking). Third, a local model stayed unavailable for agent mode until the user declared toolCalling: true (microsoft/vscode#319917). These are author reports from one client, but each maps to a check you can run first. Ofox's setup guide notes that a plain-text ping only checks authentication and text generation, and that a capability flag is not a protocol adapter (Ofox: GitHub Copilot BYOK setup).
Gateway defaults move traffic back to your account. Vercel AI Gateway retries a failed BYOK query with its system credentials and bills that usage to your credits; BYOK spend is metered separately and does not count toward budgets (Vercel). OpenRouter falls back to its shared endpoints when all BYOK keys hit a rate limit or failure, and excludes BYOK spend from guardrail and workspace budgets unless you enable include_byok_in_budgets (OpenRouter: BYOK). OrcaRouter re-serves a failed BYOK request on platform capacity at full price and tags it byok_fallback, and its docs warn that an unnoticed dead key shows up as a higher bill rather than as errors (OrcaRouter: Bring Your Own Key). With shared key fallback on, Ramp's Router retries on its own shared key after 401, 403, 429, 5xx, network, and timeout failures (Ramp Router).
The quota belongs to the customer. Tian Pan points out that a customer's per-key quota is shared with whatever else they run on that key, so your feature competes with their batch jobs, and your support team has to tell "we are limiting" apart from "your provider is limiting your key" (Tian Pan: Bring-Your-Own-Key for AI Features).
Decide what a customer route must prove
A key test proves authentication, not agent readiness, so probe the tenant's exact model, endpoint, and API surface with a streamed tool call and the follow-up tool-result turn before enabling agent features. This recommended probe set runs on the tenant's real route, and each failure disables only the features that depend on that capability.
| Capability | Probe on the customer route | If it fails |
|---|---|---|
| Authentication | Minimal request with the stored key | Block the route and notify the tenant admin |
| Streaming | Streamed text response that reaches a terminal event | Disable streaming chat; allow non-streamed answers |
| Tool call | Streamed response that emits a call to a dummy read-only tool | Disable every tool-using agent feature |
| Tool-result turn | Send the tool result back and require a valid next turn | Disable multi-step agents even if single calls work |
| Reasoning state | Repeat the tool-result turn with reasoning enabled, resending provider reasoning items unchanged | Run without reasoning or keep agents off this route |
| Structured output | Request a small JSON Schema response and validate it | Disable features that write structured fields |
| Context size | Send your largest tool catalog plus a realistic history | Lower the history budget or disable large-catalog agents |
The tool-result turn is easy to skip, yet the Gemini report above failed only after the first tool call worked. Keep the probe side-effect-free: the dummy tool reads a constant and writes no usage rows.
Implement BYOK for AI agents step by step
1. Store a versioned credential record
Keep the secret in a secrets system and keep only metadata in your application database. Yotta Labs recommends binding every credential to a tenant, retrieving it only after the request proves tenant ownership, and storing a reference rather than the raw secret in queued jobs (Yotta Labs: Bring-Your-Own-Key Access for AI Providers).
CustomerModelRoute {
tenant_id
route_id
provider # openai | anthropic | azure | bedrock | vertex | openai_compatible
base_url # validated: https, no embedded credentials, no private IPs
api_surface # chat_completions | responses | messages | generate_content
wire_model # deployment or model name sent to the provider
capability_model # well-known model used to look up limits and features
secret_ref # pointer into the secrets store, never the key
key_version # increments on every rotation
fallback_policy # never | same_account_only | platform_allowed
probe_result # per-capability pass/fail with timestamp
enabled_features[] # derived from probe_result
status # active | disabled | revoked
}
Copilot CLI separates the model name sent to the provider from the model used to look up capabilities and token limits (GitHub Docs). Keep both fields, because an Azure deployment name tells you nothing about what the model behind it supports.
A custom base_url is also an egress destination your servers will call with tenant data. OrcaRouter checks it at save time and again on every connection and redirect, refusing hostnames that resolve to private or reserved addresses, and it requires the key to be re-entered when the address changes (OrcaRouter). Apply the same rules before you store a customer endpoint.
2. Probe the exact route before enabling agent features
Run the probe set when the tenant saves the route, rotates the key, changes model or endpoint, and when you upgrade your agent runtime. Store results per capability and record the API surface tested, because a pass on chat_completions says nothing about responses.
3. Gate features per route, not per tenant
Derive enabled_features from the probe. A route that streams chat but fails the tool-result turn can still serve grounded answers while action-taking agents stay off. Show the admin which probe failed, so the fix (expose /responses, use the provider's native endpoint, pick another model) is theirs to make.
4. Make fallback a tenant contract
Several gateways retry a failed customer key on platform credentials by default and leave BYOK spend outside budgets, so make fallback an explicit tenant contract and log which credential served every model call. Ask the buyer during onboarding, write the answer into fallback_policy, and map it to the gateway's controls:
| Tenant policy | Meaning | Gateway setting to look for |
|---|---|---|
never | Fail with a typed error when the customer key cannot serve | OpenRouter is_byok_only; OrcaRouter Always use this key; Ramp shared key fallback off |
same_account_only | Try other keys the tenant owns, never platform credentials | Multiple tenant keys with platform fallback disabled |
platform_allowed | Platform credentials may serve, billed and disclosed as such | Gateway default, plus alerts on every fallback |
OrcaRouter's pinned mode returns byok:key_unavailable and skips model fallbacks too, because each is another route to platform capacity (OrcaRouter). Apply the same rule in your runtime so model failover cannot reach platform credentials for a never tenant. Check data policies too. Vercel skips BYOK keys by default when zero data retention is enforced unless a key is marked ZDR-compliant (Vercel), and OpenRouter applies your data policies to BYOK endpoints (OpenRouter), so a retention-sensitive tenant can be served by a path they never approved.
If gateway budgets cap your agent loops, turn on BYOK inclusion or enforce your own per-tenant step and token limits, since the gateway may not count customer-key spend.
5. Bind runs to a credential version
Bind each agent run to the credential version it started with and recheck it before every model call, so a rotated or revoked key stops the run at a step boundary instead of failing mid-tool or silently switching accounts. No gateway ships this as a feature, so treat it as a design recommendation drawn from documented behavior. Yotta Labs advises re-checking that a credential is still active when a background job executes and defining what in-flight work does on revocation (Yotta Labs). Ramp allows key fallback on a streaming request only before billable output starts (Ramp Router), so switch credentials only at a step boundary.
on run_start(run, tenant):
route = routes.active(tenant)
run.binding = { route_id: route.route_id, key_version: route.key_version }
before each model_call(run):
route = routes.get(run.binding.route_id)
if route.status != "active" or route.key_version != run.binding.key_version:
run.pause(reason = "credential_changed") # between steps, never mid-tool
notify_admin(run.tenant, route)
return
if not route.enabled_features.contains(run.feature):
run.fail(reason = "route_not_qualified")
Resume after rotation only when the new version passes the probe, and record any rebinding on the run so the audit trail shows which key served which steps. Keep reasoning items with the run too: Google's guide requires resending thought blocks unchanged in stateless mode (Google Gemini API: Thinking), so a run moved to another provider mid-way loses that state. Restart it from a clean step instead.
6. Record provenance on every model call
Ramp's logs record credential_source as byok or shared and a key_fallback_used flag (Ramp Router). Copy that idea into your own trace, whatever gateway you use:
model_call_event {
run_id, step_id, tenant_id
route_id, key_version
credential_source # customer | platform
fallback_used # true | false
provider, api_surface, wire_model
input_tokens, output_tokens
error_class # none | customer_auth | customer_quota | provider_outage | platform
}
Finance can then bill the right party, compliance can see which agreement covered each call, and support can explain a spike on the customer's provider dashboard. Tian Pan describes that spike as the question nobody can answer once token accounting leaves your system (Tian Pan).
Handle failures and attribute them correctly
| Signal from the customer route | Likely owner | What the agent and product do |
|---|---|---|
| 401 or 403 | Customer key or account permissions | Pause runs, mark the route unhealthy, notify the tenant admin |
| 429 or quota exhausted | Customer quota, shared with their other workloads | Back off within the run budget, then return a typed "provider limit" message |
| 400 on tool or reasoning parameters | Route lacks a capability | Disable the affected feature and rerun the probe |
| 5xx or timeout | Provider outage | Retry within budget; fall back only if the policy allows |
| Your gateway or runtime error | You | Count against your SLO and page your team |
OrcaRouter auto-disables a key on 401 or 403 and never on 429 or 5xx (OrcaRouter), which is a useful default split. Whatever split you pick, show the tenant a message they can act on, such as "your provider key was rejected", and keep customer-caused errors out of your error budget.
Verify the solution
Turn the contract into tests that run against a fake provider and a staging tenant:
- Capability gate: a route whose fake provider answers text but rejects the tool-result turn never gets tool-using features enabled.
- Reasoning replay: a route that requires reasoning items rejects a turn with stripped items, and your runtime passes the probe only when it resends them unchanged.
- Fallback pin: with
fallback_policy = never, a forced 401 produces a typed error and zero platform-credential calls, including through model failover. - Provenance: every model call in a run carries
credential_source,key_version, andfallback_used, and the counts reconcile with the gateway's own logs. - Rotation and revocation: rotating or revoking the key while runs wait between steps pauses them before the next model call; no step runs on an unbound version.
- Attribution: a forced customer 429 is shown to the tenant admin and does not burn your SLO.
- Endpoint safety: a
base_urlthat resolves to a private address is rejected at save time and at connection time.
Common mistakes
- Shipping a key field and calling it BYOK. The osFoundry migration guide describes a routing layer that prefers the customer's key and falls back to the platform key (osFoundry: BYOK LLM Architecture patterns). That suits tenants who chose it, as long as the choice is written into their policy.
- Probing once. Routes change when customers rotate keys, move deployments, or adopt new models. Re-probe on every change and after your own runtime upgrades.
What to do next
Pick one enterprise tenant that has asked for BYOK for AI agents and write down their route: provider, endpoint, API surface, model, and fallback policy. Run the seven probes from the table against that route in staging, enable only the features that pass, and add the provenance fields to your model-call trace before the first production run.