← Back to home

Documentation

Five-minute quick start

Pick your OS and the tool you use, then follow the steps. Each step says which file, what to paste and how to tell it worked; no account needed to read it.

Last updated
2026-11-25

Follow along: pick your OS and your tool

Every step below is copy and paste — follow in order, about five minutes.

Your computer runs
The tool you want to use

Anthropic's command-line coding assistant. No Claude account needed — once configured it runs on your quota here, with Prism picking the model.

  1. Step 1: Before you start: get a key

    Sign in to the console, pick a plan, then click New on the Keys page. The key is shown only once — copy it right away and paste it into the box above. Then open PowerShell: press the Windows key, type PowerShell, press Enter. Paste every command below into that window (right-click pastes) and press Enter.

  2. Step 2: Install Claude Code

    Already installed? Skip this. Otherwise copy the line below, paste it and press Enter, then wait for it to finish.

    PowerShell
    irm https://claude.ai/install.ps1 | iex

    Success looks like:Type claude --version and press Enter; you see a version number. If it says the command isn't found, close the window and open a new one — newly installed programs only show up in new windows.

  3. Step 3: Write the config

    Copy the whole block (the Copy button, top right), paste it and press Enter. It writes %USERPROFILE%\.claude\settings.json; if that file already exists, the old one is backed up first with a .bak suffix. auto hands model choice to Prism, by task difficulty. The last line turns off a few Claude Code experiments that other vendors' models reject with a 400.

    PowerShell

    This block contains a key placeholder. Paste your key at the top of the page before copying, or replace the placeholder yourself afterwards.

    New-Item -ItemType Directory -Force "$HOME\.claude" | Out-Null
    if (Test-Path "$HOME\.claude\settings.json") { Copy-Item "$HOME\.claude\settings.json" "$HOME\.claude\settings.json.bak" -Force }
    [IO.File]::WriteAllText("$HOME\.claude\settings.json", @'
    {
      "env": {
        "ANTHROPIC_BASE_URL": "https://agiplan.dev",
        "ANTHROPIC_AUTH_TOKEN": "ap_live_replace_with_your_key",
        "ANTHROPIC_MODEL": "auto",
        "ANTHROPIC_DEFAULT_OPUS_MODEL": "auto",
        "ANTHROPIC_DEFAULT_SONNET_MODEL": "auto",
        "ANTHROPIC_DEFAULT_HAIKU_MODEL": "auto",
        "CLAUDE_CODE_SUBAGENT_MODEL": "auto",
        "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1"
      }
    }
    '@)
    Rather not use a command? Create the file by hand

    Run the first block; it opens %USERPROFILE%\.claude\settings.json in Notepad (click Yes when it asks to create the file). Paste the second block into Notepad and save with Ctrl + S. Don't use Save As — Notepad will quietly add .txt.

    PowerShell
    New-Item -ItemType Directory -Force "$HOME\.claude" | Out-Null
    notepad "$HOME\.claude\settings.json"
    %USERPROFILE%\.claude\settings.json

    This block contains a key placeholder. Paste your key at the top of the page before copying, or replace the placeholder yourself afterwards.

    {
      "env": {
        "ANTHROPIC_BASE_URL": "https://agiplan.dev",
        "ANTHROPIC_AUTH_TOKEN": "ap_live_replace_with_your_key",
        "ANTHROPIC_MODEL": "auto",
        "ANTHROPIC_DEFAULT_OPUS_MODEL": "auto",
        "ANTHROPIC_DEFAULT_SONNET_MODEL": "auto",
        "ANTHROPIC_DEFAULT_HAIKU_MODEL": "auto",
        "CLAUDE_CODE_SUBAGENT_MODEL": "auto",
        "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1"
      }
    }
  4. Step 4: Start it and say something

    Go to your project folder first (e.g. cd path/to/project), then type claude and press Enter. The first time it asks whether you trust the folder — say yes. Then say anything.

    PowerShell
    claude
    Getting an error? First check the key and the network

    Paste this line and press Enter. A list of models with "id" fields means the key and network are fine and the tool's config is off — go back and paste the previous step again. 401 means the key is wrong or deleted; nothing at all or a connection error means a network problem.

    PowerShell

    This block contains a key placeholder. Paste your key at the top of the page before copying, or replace the placeholder yourself afterwards.

    curl.exe -s https://agiplan.dev/v1/models -H "Authorization: Bearer ap_live_replace_with_your_key"

    Success looks like:It answers normally. Type /status and the Anthropic base URL line shows our address — so it's running on us, not on an official account.

If it doesn't work

  • Asked to choose a sign-in method on launch? Run claude update first — older versions ignore the config file and stop at the first-run welcome screen. If it still happens after updating, the config file isn't where it should be; rerun the whole Write the config block.
  • 401: the key is mistyped or you deleted it in the console. Paste the key into the box above again and rerun the whole Write the config block.
  • 404: you edited the address by hand and it now ends in /v1. Claude Code's address has no /v1.
  • Using the Claude Code extension in VS Code? The extension doesn't take its sign-in from this file. Add claudeCode.environmentVariables to your VS Code settings (JSON) with the ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN entries from the config above.
  • **Set ANTHROPIC_* variables in .bashrc / .zshrc or system environment variables before?** Remove them so they don't fight with this file.
  • Don't name the model xxx[1m] to unlock a 1M context. Contexts beyond 400K are far more likely to be throttled or cut off, and cost much more; letting it auto-compact around 200K is steadier for long tasks.

Followed every step and it still fails? Open a ticket under Support in the console with your OS, your tool and the exact error text (never the key). A person answers.

Writing your own code: two things

The guide above is for ready-made tools. For your own code or an official SDK you need exactly two things, the endpoint and the key; write the rest the way your SDK expects.

Your program / toolany configurable SDK① base URL② API keyagiplan.devauth, metering & routingModelspinned or Prism-routed
Change two things: point the base URL at us and swap in your key. Nothing else in your program changes.
# OpenAI-style SDKs take this (with /v1)
https://agiplan.dev/v1

# Anthropic-style SDKs take this (no /v1 — the SDK appends it)
https://agiplan.dev

Check both with one curl first. A list of models means it works; 401 means the key is wrong; a connection error means the address is mistyped.

curl -s https://agiplan.dev/v1/models -H "Authorization: Bearer ap_live_your_key"

Optional /setup env script. When writing your own code, https://agiplan.dev/setup writes the endpoint and key to ~/.config/agiplan/env (mode 600) and exports OPENAI_BASE_URL / OPENAI_API_KEY (open the URL in a browser to inspect the plain-text script). Standalone tools such as Claude Code, Codex and OpenCode don't read that file — follow the setup guide above instead.

Authentication

Every /v1/* endpoint takes a bearer token; /v1/messages also accepts the x-api-key header the Anthropic SDK sends, but every other endpoint accepts only Authorization: Bearer. Keys are created in the console and the plaintext is shown exactly once — we store only a SHA-256 hash, so a key can't be recovered, only rotated.

Authorization: Bearer ap_live_xxxxxxxxxxxx

Keys can be scoped, bound to a custom model, IP-restricted and given an expiry. When rotating, the old key can keep a grace period rather than being cut off instantly.

Each key also has a routing preference (chosen at creation, changeable any time): Auto (default, balances per request type), Speed (fastest first token, unit price may be slightly higher), Cost (cheaper routes for the same model first, occasionally a longer wait — when a model is served by several routes, CU is billed at the rate of the route that actually served you), or Cache (keep one route per conversation, and when a model is served by several routes prefer the one whose cache hits have held up best recently, to reduce cache rewrites). The preference only affects how routes are chosen; failover and circuit breaking behave the same.

Signing in to the console is separate from calling the API: the API only takes keys, while the console uses an emailed code. You can also sign in with a code texted to a mainland China phone number, or with your GitHub account (the same field on the sign-in page takes an email or a phone number). Accounts created with only a phone number can add an email later under Account & security, which is also where GitHub is connected and disconnected. On the same page you can add a passkey (fingerprint, face or phone unlock), after which tapping the field on the sign-in page is enough. Code sign-in always keeps working; adding or removing a passkey asks you to confirm it's you first, and every change sends you a notification email.

Which protocols

The same base URL serves compatible endpoints for three mainstream protocols. Which one you use depends on your SDK — you don't have to tell us.

/v1/chat/completionsOpenAI style/v1/messagesAnthropic style/v1/responsesOpenAI ResponsesOne gatewayone key, one quotaSame models
Three doors into the same room: whichever dialect your SDK speaks, behind it is one key, one quota and one set of models.
EndpointProtocolNotes
/v1/chat/completionsOpenAI-stylestream, tools, response_format
/v1/messagesAnthropic-stylestream, tools, system
/v1/responsesOpenAI Responsesstream, tools, reasoning; Codex's custom_tool_call / compaction / encrypted reasoning pass through untouched; previous_response_id avoids resending context. Naming Claude in Codex runs Claude: apply_patch and namespace tools are converted automatically; OpenAI-hosted tools such as web search aren't available on Claude. Only when the history holds items Claude can't take (compaction compacted history, web_search_call search results, local_shell_call) does it switch to an equally capable GPT model, and x-agiplan-model-actual plus the call record say which item triggered it
/v1/modelsAnyReturns the names you can put in model right now: auto, auto-max, auto-fast, auto-cn, every model you can call by name, and the image, video and audio models. Your own custom models are not listed; see “Custom models” in the console (/app/prism). Its sidebar entry appears once you turn on advanced mode on the Account page
/v1/quotaAnyRead the three windows without making a call, plus your usable boost-pack balance (boost; see Advanced); needs usage:read
/v1/images/{generations,edits}OpenAI-styleGenerate / edit images, billed per image; see Advanced
/v1/videosAsync jobsSubmit a video job, poll, fetch the clip; billed per second; see Advanced
/v1/assetsAGI Plan extensionAsset library: upload reference images and audio once, reuse them; see Advanced
/v1/ticketsAGI Plan extensionSupport tickets: open, reply, read replies and images with your key; same tickets as Support in the console; see Advanced
/v1/media/{id}AGI Plan extensionLinks to generated results; no key needed, kept 7 days; see Advanced

Any tool that lets you change its endpoint works directly, with no plugin and no code changes. Differences between the request formats are handled inside the gateway, so use whichever protocol you already know.

/v1/responses is the only stateful one: on every call (with or without previous_response_id), that turn's input and output are stored on our side for at most 5 hours so your next turn can continue with previous_response_id; a scheduled job deletes them when they expire. If you don't want this storage, use /v1/chat/completions or /v1/messages instead. The privacy policy states the same.

A few endpoints are deliberately not in the table: /v1/device/code, /v1/device/token and /v1/keys/current are the CLI's transport (used by agiplan login and agiplan use), not something you call directly. /v1/traces/{id} is covered under tracing below.

Image input currently supports inline data: URLs (base64) only — remote http(s) image links are not yet supported. A remote link is currently replaced with a text placeholder. When that happens the response carries x-agiplan-dropped-params: content[].image_url, so you won't assume the model saw the image. Audio and file parts behave the same way — currently dropped, and listed in the same header.

For the fine print (request and response headers, strict output caps, capability flags, the full image and video APIs, exact billing) see Advanced usage & API reference.

Name a model, or hand it to Prism

One model field, several ways to use it: a model's ID pins that model (failing over across its own routes, never switching models); a capability tier name routes and fails over across equivalent models in that tier; auto or your custom model name hands routing to Prism. auto starts on a fast, low-cost tier (plain questions go to fast; agent sessions with tools or refactor / design / debug prompts start in balanced) and steps up one tier when the same turn is resent unchanged, cut off mid-stream, or hits three consecutive tool-error turns (up to frontier, held for that session), billed at 0.8× CU. auto-max scores difficulty on every turn and rounds up near boundaries for maximum single-turn quality (and may use Claude); auto-fast optimises speed first, then cost among tiers at or above the required quality floor, billed at the chosen tier; auto-cn restricts auto exclusively to models from Chinese vendors, returning 503 no_eligible_supply rather than switching to non-Chinese models if none are available.

"model": "glm-5.3"         // model ID: pinned (fails over among its own routes), Prism stays out
"model": "domestic"        // tier name: routed among that tier's equivalent models, with failover
"model": "auto"            // handed to Prism: starts low, moves up for hard tasks
"model": "auto-max"        // quality first: per-turn difficulty scoring, rounds up
"model": "auto-fast"       // speed first, then cost (never below auto's tier)
"model": "auto-cn"         // like auto, but only models from Chinese vendors
"model": "my-coding-model" // your own custom model
modelrequest field"glm-5.3"pinned to this one; Prism stays out"auto"Prism starts low and moves up as needed"my-coding-model"your console custom model, routed by its rules
One field, three meanings. When in doubt, send auto.

glm-5.3 above is only an example: the real model names you can use are whatever GET /v1/models returns (the console's “Models & pricing” shows the same list). The tier names are frontier, balanced, domestic and fast. Names like frontier-a or domestic-a seen in older docs are aliases for a tier — they behave exactly like the tier name, do not pin a single model, and are not listed by /v1/models.

To override the difficulty judgement on a single request, add a header: X-AGIPlan-Difficulty: 0.9. Tier coefficients are listed at /models.

Streaming

All three protocols stream SSE in their own native format, behaving exactly as you'd expect. The one thing to know: billing settles when the stream ends.

Request sentquota held firstFirst tokenthen chunk by chunkStream endsnormal, aborted or failedSettlereal usage, excess backwaiting for first tokengenerating
Timeline of one streaming call. The hold happens first, settlement last; an interrupted stream settles the same way.

On arrival we reserve quota: the input side from the tokens already countable in the request, the output side from the max_tokens you declared, capped at 16k. A normal finish, a client abort and a model-service error all run the same teardown, reconciling against actual usage and returning the difference, so disconnecting midway never bills you the worst case. Output beyond the reservation is billed as used, so a window can go slightly over its limit: all in-flight requests together can exceed the 5-hour window by at most 10%. To guarantee that, when max_tokens is above 16k the cap sent to the model may be lowered. Once over, the window shows 0 remaining and new requests wait for the reset. When a window is nearly used up and what is left cannot cover 16k of output, the request still goes through as long as it covers the input plus 4k of output: output is reserved from what remains and the cap sent to the model is lowered to match. Only below that do you get a 429. The last request of a 5-hour window (rolling out): the input side is reserved as if nothing hits the cache, so with a long context and only a few percent of the window left, even the input may not fit. In that case, if the request fits under a cache-hit estimate, and your weekly and monthly quota can cover the worst case, it still goes through: the reservation takes everything left in the 5-hour window and settlement bills actual usage. If the cache misses, that one request can push the 5-hour window over its limit by at most 25% (separate from the 10% above); the excess still counts toward your week and month. At most one such request per window, personal subscriptions only. When the reservation does not fit and the request is routed to a booster pack or your balance (pay-as-you-go) instead, settlement checks once more: if the actual usage fits in all three windows, it is billed to plan quota, with nothing taken from your balance or booster pack (the usage row shows plan quota). If it does not fit, the whole request stays where it was; it is never split.

Reading the quota response

Every response from the three text-protocol endpoints carries the remaining percentage and reset time for all three windows (image and video endpoints don't; see Advanced). Absolute usage is in the console usage detail and the monthly statement. On rate limiting you get a 429 that says which window is full and when it recovers — the 429 carries the same three headers. An invalid key (401) carries none of them, because the account can't be identified at that point.

5-hour window68% leftstarts at first call after a break → resets 5 hours laterThis week34% leftMonday 00:00 (Asia/Shanghai) → end of SundayBilling month81% leftone month from your subscription date, not the calendar monthWhichever window fills first returns 429; headers name the window and its reset time.
Three windows count at once; every call lands in all three. The 5-hour window is the confusing one: it is not a fixed slot. It starts at your first call after a break and resets 5 hours later, so after a 5-hour pause it is always full. The Max plan has no 5-hour window; only the week and billing month apply.
X-AGIPlan-Quota-Session: remaining=68%; resets=2026-08-15T09:00:00.000Z
X-AGIPlan-Quota-Week:    remaining=34%; resets=2026-08-18T00:00:00.000Z
X-AGIPlan-Quota-Month:   remaining=81%; resets=2026-09-05T00:00:00.000Z
Retry-After: 1740        // seconds, only on 429: time to the window reset, or 2 when concurrency is full

The size of the three windows follows your plan. You change plans in the console's Plans panel, with two choices of timing for an upgrade: now, where the difference for the remaining days is charged and the new quota applies immediately (for subscriptions started from 18:00 on 2026-10-20 Beijing time, and for existing ones from their first billing period starting after then, this period's weekly and monthly quota is prorated by the time left: the old quota plus the difference times the remaining share, with the full amount from the next period); or from next period, where this period's quota and price stay as they are, nothing is charged or refunded, and the subscription renews as the plan you picked at its price on that day, with the new quota starting then. Downgrades are from next period only: you keep your current plan for this period and nothing is refunded. A subscription set not to renew can still be upgraded and still ends on its original date. A trial, gifted or redeemed subscription can be switched to a paid one from the panel (“Subscribe now”): it starts immediately at full price and renews monthly, and the rest of the complimentary period ends. The billing page shows which plan renews next and how much it will charge.

Making your quota last

How much quota the same work uses depends mainly on two things: which model (per-call CU can differ several times even within one tier; the models page lists every model's rates) and which route (one model can be served by several routes, billed at the route that served the call). Where your quota goes, at the top of the console usage page, shows each model's share for the selected range and its average CU per call; click a row to see only that model.

  • Same model: set the key's routing preference to “Cost”. Cheaper routes for the same model are preferred, occasionally with a longer wait. Change it per key on the Keys page and switch back any time. It only affects route choice; circuit breaking and failover are unchanged.
  • Another tier: change the model in your requests to a model from a cheaper tier. The usage page and the console overview estimate, from your actual tokens at current tier prices, how much further your quota would go. You make this change yourself; the gateway does not replace a model you named.

A 429 for exhausted quota may also carry one suggestion based on your last 7 days (ratios only), and so may the weekly / monthly quota notice emails. Estimates re-price past tokens at current prices; scheduling still switches routes when one is busy or down, so real savings are usually lower.

Errors and retries

Got an error401key problem: change the key, do not retry429quota / concurrency full: wait Retry-After or lower tier400bad request: fix it first; retrying as-is won't help503tier failover exhausted: switch tier or retry later
Use the status code to decide whether to retry, then the code in the table below to decide what to do.
StatusError codeMeaningWhat to do
401invalid_api_keyKey invalid or revokedUse a different key; do not retry
404model_not_foundImages endpoint: no such image modelSee the entries with kind image in /v1/models
410model_retiredThe model you named has been retired. The message gives the retirement date and suggested replacementsRetrying will not help. Change model to the replacement in the message (for example auto-fast); retired models are also listed at the bottom of Models & prices in the console
503size_unavailableImages endpoint: no route supports that size right nowTry another size or retry later. Failed calls are not billed
400quality_unavailableImages endpoint: none of this model's routes for that size accept the quality you sentRetrying will not change the result. Use one of the values listed in the error, or auto
400wrong_endpointmodel on a chat endpoint (/v1/chat/completions, /v1/messages, /v1/responses) names an image or video modelRetrying will not help. Call POST /v1/images/generations for image models and POST /v1/videos for video models, with the same model. Anything in GET /v1/models whose kind is not text does not go through the chat endpoints
404unknown_modelmodel is not a real model name, a tier name, or one of your custom modelsCheck GET /v1/models, or create a custom model in the console first (Custom models)
404session_expired/v1/responses: the session behind previous_response_id is past its 5-hour retentionDrop previous_response_id and resend the full context
404session_not_found/v1/responses: no such previous_response_id, or it isn't yoursCheck the id came from a response on the same account
404trace_expired/v1/traces/{id}: the trace is past its 30-day retentionThe trace has been deleted and can't be fetched
404trace_not_found/v1/traces/{id}: no such trace, or it isn't yours (a key without the usage:read scope gets 403 insufficient_scope first and never reaches this)Check the trace id and the key
401key_rotation_requiredKey is older than the org's rotation policyRotate a new one in the console
403phone_requiredThe account must verify a mainland China phone number before it can call the API again (the email we sent explains why). Model calls, /v1/models and /v1/keys/current return this code; other endpoints return 401 as for an invalid key. The ticket endpoints keep workingRetrying or switching keys won't help. Bind a mainland China number under Account & security in the console. In most cases access returns as soon as it's verified; the email says if a ticket is also needed
400capability_unavailableNo connected model supports a capability the request declares (vision, tools…). If the named model lacks it but another model has it, the gateway switches to that model and says so in the headers and usage log instead of failingRetrying will not help. Drop the requirement, or wait for a model that supports it to be connected
400context_too_smallThe model you named by its raw ID has a smaller context window than this request's min_context_kRetrying will not change the result. Shorten the context, or pick a model with a larger window — /models lists the window for every model
400upstream_rejected_requestThe model service rejected the request itself; message says which kind: a named parameter, content stopped by a safety policy, thinking content in the conversation history that failed verification, or no reason given. For the last two the gateway first retries on the same line with the thinking content removed from the history (what was removed is listed in x-agiplan-dropped-params, e.g. messages.thinking), then temporarily tries up to 2 other lines, and returns this error only if all of them refuse. When a line does not accept system-role messages in the middle of a conversation, the gateway merges them into the adjacent user message and resends (x-agiplan-dropped-params shows messages.system_role) instead of failing. The same code is used when the input exceeds the context window of every available line (when one line cannot fit it, the gateway first moves to a line that can)Resending as-is gives the same answer; the request is not billed. Follow message: change the named parameter or the content; when no reason is given it usually comes from this conversation's history — start a new session or compact the context and retry, or connect through the OpenAI-compatible format; shorten the context if it is too long. message ends with this request's trace id — send it to us if you believe the request is valid
400upstream_rejectedImages / video: the model service rejected this generation (prompt or reference assets not allowed, or size / parameters not accepted)Another route gives the same answer. Change the prompt or size and retry; failed calls are not billed
400request_exceeds_mix_capWorst-case estimate exceeds the max_cu_per_request set in your custom modelThis is your own cap. Lower max_tokens, shorten the context, or raise the value
403insufficient_scopeKey lacks the required scopeUse a key that has it
403plan_excludes_modelYour custom plan doesn't include this model or groupUse a model in your plan, or contact us to change it
400strict_max_tokens_unavailableYou sent X-AGIPlan-Strict-Max-Tokens, and every route that could serve the request does not guarantee max_tokensRetrying will not change the result. Drop the header (output beyond the cap is billed at actual usage), or use auto / another tier
403no_subscriptionNo active subscription, and pay-as-you-go is off (or the balance is empty). If a subscription ended within the last 30 days, the message says when and links to the plan pickerSubscribe in the console, or enable pay-as-you-go and top up
429quota_exceededA window's quota is exhausted; or the original model didn't answer and the backup model that could take over costs more than your remaining quota allows (we won't push you past the window; failed attempts aren't billed. If you hold a boost pack, the request is drawn from it; if the key has pay-as-you-go top-up on and your balance covers it, the request is charged to your balance. In both cases you won't see this error). The same code — not upstream_rejected_request — is returned when the preferred line was not tried because its estimate exceeded your remaining quota and the backup line that did fit could not take the request: what stopped it is quota, not the request's contentWait per Retry-After, or move to a cheaper capability tier. If you hold a quota reset for that window, the error says so; use it from the console overview to restore the quota at once
429concurrency_exceededIn-flight requests hit your plan's ceilingWait for an in-flight request to finish before sending another. Upgrading resolves this; topping up does not, since it is not a quota problem
429upstream_busyEvery model service that can take this request is full right now (rate-limited or at its concurrency limit); the gateway already waited a moment for a free slotRetry after Retry-After (the shortest wait the model services gave, or 10 seconds). Not your quota or concurrency; failed attempts are not billed
429rate_limitedToo many requests from the same source: CLI device-code requests and signing of result links are cappedWait for Retry-After and try again. Normal use never hits this; looping scripts do
451region_not_availableNo model in that tier is offered in your regionRetrying will not change the result. Pick another tier, or see the region column at /models. If you picked the wrong region, change it under Account & security; it takes effect immediately (switching to mainland China requires verifying a mainland phone number first)
503no_supply_configuredNo model service is currently available for that capability tierRetrying will not change the result. Pick another tier, or use auto — /models shows how many lines each tier has right now
503policy_unavailableThe custom model configuration is currently invalid, usually because a pinned model was retiredThe error message names the target pool and model. Under Custom models in the console, point it to another model or tier and save
503model_unavailableThe model you named by its raw ID has no working route right nowThe gateway will not substitute another model. If the message says it is recovering automatically, retry later; if it says the model is suspended, retrying will not help: pick another model (GET /v1/models only lists models that have a working route). Either way you can use a capability tier name (e.g. domestic) so the gateway can switch between equivalent models
503all_upstreams_failedEvery model in the tier was tried and none workedThe body carries the full record of attempts. Failed attempts are not billed
mid-streamupstream_interruptedThe model service dropped after output had started. The status is already 200, so this arrives as an error event inside the stream, with no normal end marker after itOutput already sent is billed by actual tokens; a stream that drops before producing anything is not billed. Switching models mid-answer would make it inconsistent, so the gateway does not switch models here; on models flagged as resumable it first tries to continue from where the answer stopped (rolling out; see Billing, precisely in the advanced guide), and if that works you never see this error. If you do, resend the request
mid-stream (Responses)invalid_prompt/v1/responses only: after output had started, the model service rejected the request itself (parameters, content, or encrypted items in the history it cannot decrypt). This is OpenAI's code; Codex recognises it and does not blindly retryResending as-is gives the same result; output already sent is billed. Check the request; in Codex, /new starts a fresh session
mid-stream (Responses)context_length_exceeded/v1/responses only: after output had started, the model service said the input exceeds its context windowShorten the context or let the client compact it (Codex suggests starting a new session)

Long waits on a stream start with comment lines. Failover or a long prompt can delay the first event; if nothing has arrived after 20 seconds, the gateway sends 200 with the streaming headers, then a keepalive every 15 seconds so idle timeouts in clients or proxies do not cut the connection: on Chat and Messages an SSE comment : keepalive (ignored by clients per the SSE spec); on Responses a response.in_progress event (sequence numbers advance as usual — clients such as Codex only count events as activity; it is also sent whenever an open stream has had no new event for 15 seconds). If such a request then fails, the error comes as an in-stream error event (codes as in the table above), and the response headers carry no quota or trace headers — the trace id is in a : trace tr_… comment line.

You don't need to retry 5xx yourself. Failover already ran inside the gateway — a 503 means every model in the tier was tried.

Fallback order when plan quota runs out: once a plan window hits zero, calls draw from any usable boost pack first; once boost packs are used up, with pay-as-you-go on the request draws from your balance instead of being refused. If neither can cover the call, the gateway returns 429 and states which limit blocked it (not enabled, monthly ceiling reached, or insufficient balance).

Branch on code, not on message. code is the stable contract and changes are announced; message is a sentence for a human and its wording will change. message is currently Chinese only; code and the HTTP status are unaffected.

Trace IDs

Successful responses carry a trace ID and the model that actually ran. If failover happened, that's marked too. Refused responses carry no trace ID, because the call never became a usage record. On a 503 the chain is in the response body as attempts; send that along when you report the problem.

X-AGIPlan-Trace: tr_01J8FQ3M7X
X-AGIPlan-Model-Actual: deepseek-v4-pro
X-AGIPlan-Failover: true
X-AGIPlan-Tracein every response headerGET /v1/traces/{id}with your own keyFull timelineJSON, retained 30 days
Reporting a problem takes one thing: the trace ID. You can also use it yourself to see which route the call took.

Fetch the full trace with your own key: GET /v1/traces/{id}, structured JSON, retained 30 days. Include the trace ID when reporting a problem.

Docs for AI agents

When an agent such as Claude Code or Codex does the integration for you, hand it any of these. It gets Markdown without navigation or scripts, with the same numbers as the web page:

URLWhat you get
https://agiplan.dev/llms.txtSite index: base URL, the three protocols, a Markdown link for every public page
https://agiplan.dev/llms-full.txtEvery public page as one Markdown file
Any public page + .mde.g. /en/docs.md, /en/pricing.md, /en/models.md; home is /en.md
Header Accept: text/markdownThe page URL itself returns Markdown

Command line (planned)

The agiplan CLI is not publicly released yet (not yet published to npm or as a standalone binary). Below is a preview of the planned subcommands; for current setup, use the guide or environment variables above.

CommandWhat it doesStatus
agiplan logindevice-code auth: confirm in the browser, deliver a new key to the terminalPlanned
agiplan statusshow remaining share, active plan and reset time for all three windowsPlanned
agiplan modelslist available models and capability tiersPlanned
agiplan use <name>bind a custom model to the current key; --none unbindsPlanned
agiplan envprint evaluable environment variablesPlanned
agiplan uninstallremove the local config file written by setup (--yes required)Planned

For security reasons, self-rotation (keys rotate) is not provided in the CLI. If a leaked key could mint its own replacement, an attacker could rotate first and survive revocation of the old key. Key rotation always requires browser session confirmation in the console.

Per-project .agiplan files store only the profile name, never plaintext keys, and are safe to commit to Git.

Migrating from another service

If you already use an official SDK or another aggregator, only two things change: the endpoint and the key. Where model names differ, a custom model name gives you a mapping layer and your application code stays untouched.

Two behaviours differ from the official API. First, if you omit max_tokens we set a cap for you and send it to the model (treated as a declared 64000: the cap that the quota reservation allows, then narrowed to fit the chosen line's context window; if the line rejects it we lower it once and resend), so a very long answer can still stop at that cap with finish_reason: "length"; when we do, the x-agiplan-max-tokens-default response header carries the value actually sent to the model. Second, when max_tokens is above 16k, or when the window is nearly used up, the cap sent to the model may be lowered, to bound how far a single request can go over quota (see the Streaming section above). When that happens, the trace records the value before and after.

GLM models include reasoning tokens inside max_tokens. A tiny budget can leave visible output empty with finish_reason: "length" (still billed on actual tokens). auto avoids GLM when thinking wasn't requested and the budget is below 1024; when specifying a GLM model directly, set max_tokens to at least 1024, or pass thinking: { "type": "enabled", "budget_tokens": 2048 }.

One more thing that affects your bill: when a request needs a capability the tier you picked cannot provide, we lift it to a tier that can — and bill the tier it landed on. The common case is images: your custom model selects the fast tier, no model there has vision, so the call lands on the domestic flagship tier and is billed at that tier's higher coefficients. We only ever lift, never drop, so a downgrade never happens silently. Every text-endpoint response carries x-agiplan-billed-group naming the tier actually billed, matching what appears in your usage detail. To avoid being lifted, don't send that custom model content its tier can't handle, or pick a tier that supports it.

  • Create a custom model named after the model name you use today, routing to the matching capability tier.
  • Change the base URL and key, then run your tests.
  • Check the coefficients at /models and reconcile your first day against the usage detail in the console.

JMRAI legacy balance migration

Legacy JMRAI (jmrai.net) users can migrate their balance: sign in at jmrai.net to get your migration link, then open that link (or visit /migrate) to confirm. Amounts are fixed by the frozen snapshot taken when the legacy service stopped; one legacy account binds to exactly one AGI Plan account, permanently.

The migrated amount lands as bonus balance: valid for 90 days from credit, usable for pay-as-you-go (not for buying or renewing plans), non-refundable, non-withdrawable and not invoiceable. After any paid purchase you also get a 5% bonus on your legacy top-ups (migrated amount included), credited automatically after a 7-day confirmation window with the same 90-day validity.

  • Migration entry: jmrai.net (legacy password or WeChat verification code).
  • The migration window closes automatically on 2027-10-12; unclaimed balances are forfeited after that.
  • For amount or eligibility disputes, open a support ticket with your legacy order records.

If something is missing or unclear, email support@agiplan.dev or open a ticket in the console.