APIRelay docs

APIRelay guide

APIRelay turns the subscriptions you already pay for (ChatGPT, GitHub Copilot) into one OpenAI-style API with keys, limits and per-app reports. Anything that can talk to OpenAI can talk to it. You change two settings: the base URL and the key.

Quick start

  1. Connect an account. In the dashboard, choose Sign in with ChatGPT. You get a one-time code and type it on OpenAI's own page. Your password never passes through APIRelay.
  2. Check the order. Under Routing, the first account in the chain answers first. Add a second ChatGPT account below it and it takes over when the first runs out.
  3. Make a key. Under API keys, create one per app. It starts with sk-relay- and is shown once.
  4. Send a request.
curl https://apirelay.anri.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-relay-..." \
  -H "Content-Type: application/json" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "Say hi"}]}'

auto means "whatever my chain says". You can also ask for a model by id; GET /v1/models lists every model your accounts offer.

Using it in other apps

Look for a setting called base URL, API base, endpoint or "OpenAI-compatible provider". Give it:

Base URLhttps://apirelay.anri.ai/v1
API keyan APIRelay key, sk-relay-...
Modelauto, or any id from /v1/models

Python

from openai import OpenAI

client = OpenAI(base_url="https://apirelay.anri.ai/v1", api_key="sk-relay-...")
stream = client.chat.completions.create(
    model="auto",
    messages=[{"role": "user", "content": "Three facts about telephone exchanges"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

Node

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://apirelay.anri.ai/v1", apiKey: process.env.RELAY_KEY });
const r = await client.chat.completions.create({
  model: "auto",
  messages: [{ role: "user", content: "Name a switchboard part" }],
});
console.log(r.choices[0].message.content);

Environment variables

Many tools read the standard variables, so this is often all it takes:

export OPENAI_BASE_URL=https://apirelay.anri.ai/v1
export OPENAI_API_KEY=sk-relay-...

Apps like Open WebUI, LibreChat, n8n, Continue, Obsidian plugins and LangChain all have an "OpenAI-compatible" or "custom base URL" option. Some older tools want the URL without /v1; if you get 404s, try it both ways.

Telling apps apart

Every request is filed under an app name so the usage page can split it. APIRelay takes the first one it finds:

  1. The URL path. Use https://apirelay.anri.ai/a/notes/v1 as the base URL. Best for apps where you can only change the URL and the key.
  2. A header: X-Relay-App: notes.
  3. The body: "relay": {"app": "notes"} or "metadata": {"app": "notes"}. These fields are removed before the request goes upstream.
  4. The key's default app, set when you create the key.
  5. Otherwise default.

A key with an app name is locked to that app. If a request names any other app, by URL path, header or body, it is refused with 403 app_not_allowed, on every endpoint. The answer does not say which app the key belongs to; you see the refusal, with both names, in your request log. Case, spaces, dashes and underscores don't count, so a key for Invoice Bot works at /a/invoice-bot/v1. A key with no app name may be used by any app.

The simplest setup is one key per app with the app name on the key. For your own software, the header also lets you name the end user: X-Relay-User: user-42 (or the standard OpenAI user field). Usage then splits by end user too.

client = OpenAI(
    base_url="https://apirelay.anri.ai/v1",
    api_key="sk-relay-...",
    default_headers={"X-Relay-App": "support-bot"},
)

Claude Code and Anthropic clients

APIRelay also speaks Anthropic's Messages format at POST /v1/messages, so Claude Code, the Anthropic SDKs and tools built on them can use your subscriptions too. The answer comes from whatever your chain picks; the relay translates both ways, streaming included.

  1. Add an alias under Routing: claude-* to auto (or to a model id). Claude clients ask for names like claude-sonnet-4-5, and the alias sends them into your chain. Without it they get model_not_found.
  2. Point the client at the relay. Use the site root, without /v1, because Anthropic clients add /v1/messages themselves.
export ANTHROPIC_BASE_URL=https://apirelay.anri.ai/a/claude-code
export ANTHROPIC_AUTH_TOKEN=sk-relay-...
claude
import anthropic

client = anthropic.Anthropic(base_url="https://apirelay.anri.ai", api_key="sk-relay-...")
msg = client.messages.create(model="claude-sonnet-4-5", max_tokens=1024,
                             messages=[{"role": "user", "content": "Hello"}])
print(msg.content[0].text)

Keys work in either header, x-api-key or Authorization: Bearer. Supported: system prompts, text, images, PDF documents, tools with tool_use and tool_result, tool_choice, streaming with the usual event sequence, stop_sequences, and extended thinking (mapped to a reasoning effort). POST /v1/messages/count_tokens returns an estimate of about four characters a token. Anthropic's server tools (web search, code execution), prompt-caching markers and the Batches API are not relayed; server tools are dropped from the request and cache_control is ignored.

Errors come back in Anthropic's shape ({"type": "error", "error": {"type": "rate_limit_error", ...}}) so the SDKs raise their usual exceptions.

Models and fallback

The chain on the Routing page is an ordered list of account and model pairs. For each request, APIRelay builds a list of candidates and tries them in order until one starts answering:

  • model: "auto" goes down the chain from the top.
  • A specific model goes first to every connected account that has it (chain order), then down the rest of the chain. Turn off "fall back to other models" on a key if an app must only ever get the model it asked for.
  • Embeddings only go to accounts that list that embeddings model.

An account is skipped, and the next one tried, when it:

runs out of creditChatGPT usage limit, 402, insufficient_quota. Rested until the time the provider gives for the reset (an hour when it gives none).
gets throttled429. Rested for the provider's retry-after, at most 15 minutes.
signs outThe saved sign-in stops working. Marked "sign in again" in the dashboard until you reconnect.
errors5xx or a network failure. Rested for 20 seconds or so.
crosses its hold-back lineChatGPT only: you can tell the relay to stop at, say, 80% of the 5-hour or weekly window and leave the rest for yourself.
is busyAlready running its limit of parallel requests (3 by default).
can't fit the promptThe model's context window (from the price list below) is smaller than the prompt. Checked before sending, from a rough estimate; after a real "context too long" answer, other steps with the same model are skipped too.
refuses on content policyProviders draw the line in different places, so the next step gets a go. Turn this off under Routing to get the refusal back as it is.

Quick retry. A 5xx, a network failure, or a throttle with a retry-after of two seconds or less gets one more try on the same account before the relay moves on. Most blips clear that fast, and it saves a switch to a different model.

Priority or balanced. By default the chain is strict priority: the top step takes everything until it runs out. Switch Routing to balanced and neighbouring steps that serve the same model are sorted by load on each request (the fuller ChatGPT usage window and requests in flight), with ties taking turns. Two identical plans then wear down evenly instead of one after the other. Steps with different models keep their order.

Fallback only happens before the first token is sent. Once an answer is streaming, it's committed to that account. A request that the upstream rejects as invalid (a bad tool schema, say) comes straight back to you with the upstream's message and is not retried elsewhere.

Model aliases

An alias is a model name your apps can ask for that the relay turns into another one, set under Routing. Point fast at gpt-6-luna today and at something else next month without touching any app. Plain aliases show up in GET /v1/models.

  • End a name with * to catch a family: claude-* or gpt-4*. Exact names beat * names, and the longest * match wins.
  • The target can be auto (your whole chain) or a model id. Aliases don't chain: the target is used as it is.
  • A key's model allow-list accepts either the name the app sent or the alias target.
  • The response carries x-relay-alias, and the request log shows both names.

Key limits and API value

Each key can carry any of: requests per minute, requests per day, tokens per day, tokens per month, a daily and a monthly dollar budget, an allow-list of models, and an expiry date. Days and months run on UTC. Usage is counted when a request finishes, so a burst of long requests can go a little past a cap.

API value is what the same tokens would have cost on the paid API: input, cached input and output tokens priced from LiteLLM's public price list (MIT licensed). Nothing is charged; it shows what your subscriptions are worth to you, per app, key and model, and a dollar budget is an easy way to cap an app without thinking in tokens. Models missing from the list count as $0. The list ships with the relay and refreshes itself weekly.

A key over its limit gets a 429 in OpenAI's format, with code set to rate_limit_exceeded, key_daily_requests, key_daily_tokens, key_monthly_tokens, key_daily_budget or key_monthly_budget. Per-minute limits also send retry-after and x-ratelimit-remaining-requests.

What's supported

POST /v1/chat/completionsStreaming and non-streaming, stream_options.include_usage, tools and tool calls (including parallel), tool_choice, images in user messages, response_format with JSON mode or JSON schema, reasoning_effort.
POST /v1/responsesStreaming and non-streaming. Stateless: send the full input each time; previous_response_id is refused.
POST /v1/embeddingsCopilot and OpenAI-compatible accounts only.
POST /v1/images/generations
POST /v1/images/edits
The OpenAI Images API. On ChatGPT accounts the picture is made by ChatGPT's own image tool (gpt-image-2), which uses the account's Codex usage window. prompt, n (1-4), size, quality, background, output_format, output_compression. Edits take one or more images and an optional mask, as a multipart upload (what the SDKs send) or JSON images: [{"image_url": "data:..."}]. Answers are always b64_json. A picture takes 20-60 seconds. OpenAI-compatible accounts get the request forwarded; Copilot has no image route.
POST /v1/messagesAnthropic's Messages format, see Claude Code and Anthropic clients. Plus POST /v1/messages/count_tokens.
GET /v1/modelsEvery model your accounts offer, your plain aliases, plus auto.

ChatGPT accounts ignore sampling settings. The subscription backend takes no temperature, top_p, max_tokens, stop or seed. They're accepted and dropped so clients that always send them keep working. Copilot and OpenAI-compatible accounts pass them through.

Not available: n greater than 1 on chat, audio in or out, hosted image URLs, the Files, Batch, Assistants and fine-tuning APIs, and legacy /v1/completions.

Reasoning. Turn on "stream reasoning summaries" in Settings and ChatGPT's reasoning summary arrives as reasoning_content in each delta, which several chat front-ends display as thinking.

Response headers

x-request-idThe id shown in the request log.
x-relay-providerchatgpt, copilot or compat.
x-relay-accountName of the account that answered (URL-encoded).
x-relay-modelThe model that answered. With auto or a fallback it can differ from what you asked for.
x-relay-fallbacksHow many accounts failed first. A quick retry on the same account doesn't count.
x-relay-aliasThe alias that matched the requested model, when one did (URL-encoded).
x-relay-appThe app name the request was filed under.

Errors

Every error has OpenAI's shape, so SDKs raise their usual exceptions:

{"error": {"message": "Every connected account is out of credit...", "type": "insufficient_quota", "param": null, "code": "insufficient_quota"}}
400 context_length_exceededNo model in reach has a context window big enough for the prompt.
400 content_policy_violationRefused on content policy, by every route tried (or by the first, if policy fallback is off).
401 invalid_api_keyUnknown, revoked or expired key.
403 app_not_allowedThe key is locked to another app than the one this request names.
403 model_not_allowedThe key's model allow-list doesn't include that model.
404 model_not_foundNo connected account serves that model.
429 insufficient_quotaEvery account is out of credit. retry-after says when the first one frees up.
429 rate_limit_exceededKey per-minute limit, or every account is cooling down.
429 key_daily_tokens, key_daily_budget and friendsThe key hit one of its caps.
502 upstream_errorEvery account failed for other reasons. The message carries the last one.
503 no_accounts / empty_chainNothing connected, or the chain has no steps.

If an answer breaks after streaming started, the stream ends with a data: {"error": ...} line before [DONE].

Accounts and your data

ChatGPT signs in with the same device-code flow the Codex CLI uses, and works with Plus, Pro, Business and Enterprise plans. The dashboard shows how much of the 5-hour and weekly windows are used, straight from the numbers ChatGPT returns. Check now and the background check (about every 30 minutes for an idle account) read them live, so usage outside the relay, such as Codex or the ChatGPT apps, counts too. GitHub Copilot uses GitHub's device flow and needs an active Copilot plan. OpenAI-compatible takes any https base URL and API key, handy as the last step once the subscriptions run dry.

Sign-ins and keys are encrypted at rest, tied to your account, and only ever sent to the provider they came from. The request log keeps counts and routing; message text is only stored if you turn on previews in Settings, and logs are deleted after the retention you choose.

Full request capture. For debugging, Settings has a capture window (up to 31 days, for example "the next 24 hours"). Every request inside it keeps its full JSON, exactly as the app sent it and the full answer it got back, with streamed answers put back together. Open the request in the log to read, copy or download it. Images, files and embedding vectors are not stored and very long text is cut. Captures are deleted after their own keep time (1 to 90 days), and you can delete them all at once.

About the terms. A subscription is sold for use in the vendor's own apps. Relaying it to other software can go against those terms and can get an account limited. Keep APIRelay to your own apps and your own use.

Management API for agents

A coding agent that builds you a new app can set up APIRelay for it without your dashboard login. Create a management token under API keys, Agent access. It starts with rmt_, and you choose what it may do. Management tokens and API keys never stand in for each other: a management token can't call models, and an API key can't manage anything.

keys:readList the keys it may manage, with usage today and this month.
keys:writeCreate, change, rotate and revoke those keys.
usage:readUsage per app and per key: totals, by model, by day, recent errors.
models:readModels, aliases, account health (no sign-in details), and integration settings.

By default a token only sees and changes the keys it created. You can also cap the monthly budget of every key it creates. Each change it makes is listed under Agent access, and revoking the token can revoke its keys too.

curl -X POST https://apirelay.anri.ai/manage/v1/keys \
  -H "Authorization: Bearer rmt_..." -H "Content-Type: application/json" \
  -d '{"app": "invoice-bot", "monthly_usd": 20}'

The answer holds the new key (shown once) and an integration block with everything the app needs: the per-app base URL (/a/invoice-bot/v1, so its usage reports separately), the LAN URL for apps on the same network, env vars (APIRELAY_BASE_URL, APIRELAY_API_KEY, APIRELAY_MODEL), the models, and Node, Python, fetch and curl snippets.

GET /manage/v1/whoamiThe token's name, permissions and limits, and the base URLs.
GET /manage/v1/modelsModels the account serves, plus the state of each connected account.
GET /manage/v1/keysKeys, with ?app= and ?include_revoked=1. GET /keys/{id} for one.
POST /manage/v1/keysCreate a key for an app. Body: app (required), optional name, rpm, daily_requests, daily_tokens, monthly_tokens, daily_usd, monthly_usd, allowed_models, allow_fallback, expires_at.
PATCH /manage/v1/keys/{id}Change a key's limits.
POST /manage/v1/keys/{id}/rotateNew key with the same settings. The old one is revoked unless {"revoke_old": false}.
DELETE /manage/v1/keys/{id}Revoke a key.
GET /manage/v1/usage?app=, ?key=, ?days= (1 to 90).
GET /manage/v1/integration?app=The integration block without creating a key.

Errors use the same shape as the rest of the API. 401 invalid_token means the token is unknown, revoked or expired. 403 missing_scope means it lacks the permission. A token can make 120 requests a minute and create 30 keys an hour.

Agent skill. The APIRelay repo ships a ready skill (skill/apirelay): a SKILL.md with the full "add APIRelay to a new app" workflow, and a zero-dependency CLI. The CLI writes a new key straight into the app's env file, so the key never shows up in the agent's chat, and it verifies the setup with a real request.