OpenLegion · Docsllms.txt
Docs pages

Let your users bring their own model key

Your customers can run their workspace's agents on their own Anthropic or OpenAI API key. The agents' replies are then billed to your customer's account with that vendor, and OpenLegion books them at 0 credits. You decide which workspaces may, and nothing changes in the others.

What runs on the key, and what doesn't

  • The agent's own replies run on the key: the model calls of its runs. The agent's tier picks the model's size and the key picks the vendor:

    TierAnthropicOpenAI
    fast, backgroundClaude Haiku 5.5GPT-6 Luna
    reasoningClaude Sonnet 5.5GPT-6.1 Sol
    frontierClaude Opus 5.5GPT-6 Astra

    A pin to an exact model is ignored on a person's key.

  • Memory and background work stay on OpenLegion's models and bill as before: memory upkeep, embeddings, the check of outside content for injected instructions, and voice. A run still needs credits to start, as any run does.

  • There is never a fall back to OpenLegion's models. When the key or the vendor fails during a run, the run stops and says why (below). The calls go straight to the vendor.

A workspace holds one key, Anthropic or OpenAI. Saving the other vendor's key replaces it.

1. Allow it for a workspace

With a key that has workspaces:write:

await ol.workspaces.update(workspaceId, { model_keys_allowed: true });

model_keys_allowed is false until you turn it on. Turning it off keeps a saved key but stops using it: the workspace's agents go back to OpenLegion's models from their next run. A run already going keeps its model.

2. Let your user save their key

With the kit

import { ModelKeysCard } from "@openlegion/platform/react";

export default function ModelSettings() {
  return <ModelKeysCard notAllowed="explain" />;
}

The card shows the key saved as its vendor and last four characters ("OpenAI · ends in x9Qa · checked 13 Nov"). It takes a new key in a password field. The vendor checks the key before it is saved, which takes a few seconds ("Checking…"). Remove asks first.

  • Only an owner or admin may see, save and remove it: the card calls the kit's routes with your key, as the person your resolve() answers, and a key saved here pays for every conversation in the workspace. A member gets 403 insufficient_role, as their session token would, and the card draws nothing for them. allowModelKeys (below) narrows it further; the card draws nothing for a person it turns away either.
  • If the card can't read the key for another reason (the network, your server), it says so with Try again.
  • Where the workspace may not use a key, the card draws nothing. With notAllowed="explain" it says so in one sentence instead, and still lets your user remove a key saved earlier.
  • labels changes every word, including why a key wasn't saved (malformed, invalid, modelMissing, unchecked, tooMany, notAllowed, with {vendor}), and readFailed and retry for a read that failed. formatDate changes how the date is shown.
  • useModelKeys() is the hook behind it, for a card of your own: allowed, key, saving, error, refresh(), save(vendor, key) and remove(vendor). modelKeysReadState(allowed, error) says whether to draw it, with the card's rule.

Who may: allowModelKeys

Give the handler a function of the person resolve() answered. In your route's createNextHandler({ … }) (app/api/openlegion/[...route]/route.ts), next to resolve, this lets only your founding members bring their own key:

resolve: async () => {
  const session = await currentSession();
  return session ? { workspace: await workspaceFor(session.customer), subject: session.user } : null;
},
// Only your founding members may bring their own key.
allowModelKeys: async (who) => isFoundingMember(who.subject),

For anyone it doesn't let in, the model-key routes answer as if they weren't there: the handler's 404, whatever the method. The card then draws nothing. Only true lets a person in. If the function throws, the answer is no, and the error goes to onError. The other kit routes never ask it.

The kit's routes are GET and POST {basePath}/model_keys, and DELETE {basePath}/model_keys/{vendor}. Its own codes are invalid_body (400: the body isn't {vendor, key}) and invalid_vendor (400). The API's reasons for not saving a key pass on with their codes. The kit tries each save once: every try is a check with the vendor, and checks are counted (below).

From your server

Your key needs the vault scope. The key npx openlegion init made has it.

// app/settings/model-key/route.ts: your settings form posts {vendor, key} here.
export async function POST(request: Request): Promise<Response> {
  const session = await currentSession();
  if (!session) return new Response(null, { status: 401 });
  const ws = openlegion().workspace(await workspaceFor(session.customer), { subject: session.user });
  const { vendor, key } = (await request.json()) as { vendor: "anthropic" | "openai"; key: string };
  const saved = await ws.modelKeys.create({ vendor, key }, { maxRetries: 0 });
  // saved.tail is the key's last four characters; the key itself is never answered.
  return Response.json({ vendor: saved.vendor, tail: saved.tail, replaced: saved.replaced });
}
  • ws.modelKeys.list() answers allowed and the key saved (vendor, tail, checked_at, in_use), never the key.
  • ws.modelKeys.delete(vendor) destroys it. The workspace's agents run on OpenLegion's models from their next run.
  • Never log the request body, and never keep the key: OpenLegion keeps it encrypted, and nothing ever answers it again.
  • With a session token (POST /sessions), only an owner or an admin may save or remove a key.

When a key isn't saved

The key's shape is checked first, and then the vendor checks the key with its models list, which spends no tokens. A key that fails either check isn't saved. Testing locally? Every key with the right shape is sent to Anthropic or OpenAI, even in test mode. Only a key refused by its shape never leaves OpenLegion.

  • model_key_malformed (400, param: "key"): it isn't shaped like the vendor's API key. It is under 8 characters, it has a space or a character outside printable ASCII, or it has the other vendor's prefix (sk-ant- is Anthropic's). Nothing was sent to the vendor. The card says "That doesn't look like an OpenAI key. Check you copied all of it."
  • model_key_invalid (400, param: "key"): the vendor refused it. It may have been revoked or deleted.
  • model_key_model_missing (400, param: "key"): the key can't use a model that this workspace's agents run on now. The message names each one. A key restricted to some models, or a project without access to them, gives this.
  • model_key_unchecked (503): the vendor didn't answer. Try again in a minute.
  • model_key_checks_exceeded (429): the workspace checked 10 keys in the last hour, with Retry-After. The limit stops the check being used to test stolen keys.
  • model_keys_not_allowed (409, a refusal): model_keys_allowed is off.

When a run on the key stops

A run that stops on your user's key fails with one of these codes, in GET /runs/{id} and the run.failed event. In the chat, the stream ends with data-refusal: a sentence for your user that names their vendor. The run isn't retried, and tool calls it made before stopping stand.

CodeWhen
model_key_refusedThe vendor refused the key: it was revoked or deleted.
model_key_out_of_quotaYour user's account with the vendor is out of funds.
model_key_rate_limitedThe key is over its rate limit with the vendor, after retries.
model_key_model_unavailableThe key can't use the model this agent's tier needs, for example an agent added on another tier after the key was saved.
model_vendor_unavailableThe vendor didn't answer, or was overloaded.
model_key_missingThe key was removed while the run was going.

Erasure and the audit log

  • Erasing one of your users (DELETE /subjects/{subject}) deletes the key they saved, so the workspace stops running on their account. A key your server saved without a subject stays.
  • Every check, save, refusal and removal is in the workspace's audit log (model_key.checked, model_key.saved, model_key.refused, model_key.removed), with the vendor and the last four characters, never the key. Turning model_keys_allowed on or off is there too.