页面简介
Use one OpenAI-compatible API for Claude, GPT and Gemini: change the base URL in your SDK, read usage on streamed responses, and handle every error code.
正文摘录
On this pageIf you call more than one model provider, you already pay a tax for it: a different SDK per vendor, a different auth header, a different error format, and a separate bill at the end of the month. An OpenAI-compatible API removes most of that. You keep the client you already have, point it at one base URL with one key, and choose the model with the model field. This guide goes from a new account to a working request, then covers what comes up once real traffic starts: streaming with real token counts, the Anthropic-native option for Claude tools, and the error codes worth handling explicitly. What "OpenAI-compatible" means An OpenAI-compatible API mirrors the OpenAI wire protocol. On APIKO that means: PartWhat stays the same as OpenAIBase URLhttps://api.apiko.app/v1 instead of https://api.openai.com/v1EndpointsPOST /v1/chat/completions, GET /v1/modelsAuthAuthorization: Bearer <key>Request bodymodel, messages, stream, stream_options, max_tokens, …Response bodychoices[0].message, usage.prompt_tokens, usage.completion_tokensErrors{"error": {"message", "type", "code"}} with standard HTTP status codes Because the shape is the same, anything that already speaks OpenAI works without new call logic: the official openai SDKs, LangChain (see the LangChain guide), LlamaIndex, a bare fetch or requests call, and agent tools that ask for a base URL and key. What changes is the set of models behind the endpoint. On APIKO that list includes Claude, GPT, Gemini, DeepSeek, GLM, Grok and Kimi models, all on the same key and the same balance. One distinction is worth keeping straight. api.apiko.app is the gateway: it serves /v1 and is what your code talks to. apiko.app is the console where you create keys, check usage and top up. The console does not proxy /v1 traffic, so never point an SDK at it. Step 1: Create an API key Sign up, open API Keys in the console (/dashboard/apikeys) and create a key. The full sk-… value is shown once, so copy it into an environment variable straight away: export APIKO_API_KEY="sk-..." Each key can carry its own spending limit. When a key has spent that amount, its requests fail instead of drawing more from your balance, which makes separate keys for staging, production and individual services a cheap safety net. If you sign in with Google using a Gmail address, $0.20 is added to your balance automatically, no card needed, once per person. It works with every model, including image and video. Step 2: Change the base URL in your existing code The official OpenAI SDKs for Python and Node.js both read two environment variables. If your code creates the client without arguments, this is the whole migration: export OPENAI_BASE_URL="https://api.apiko.app/v1" export OPENAI_API_KEY="$APIKO_API_KEY" If your code passes the values explicitly, change baseURL in JavaScript or base_url in Python. Nothing else in the client changes. Python: Copyimport os from openai import OpenAI client = OpenAI( base_url="https://api.apiko.app/v1", api_key=os.environ["APIKO_API_KEY"], ) res = client.chat.completions.create( model="gpt-6.1-sol", messages=[{"role": "user", "content": "Hello"}], ) print(res.choices[0].message.content) Node.js: Copyimport OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.apiko.app/v1", apiKey: process.env.APIKO_API_KEY, }); const res = await client.chat.completions.create({ model: "gpt-6.1-sol", messages: [{ role: "user", content: "Hello" }], }); console.log(res.choices[0].message.content); Building messages, reading choices[0].message.content, your retries and timeouts all stay exactly as they were. That is the point of an OpenAI-compatible API: the integration work you did once covers every model you add later. Step 3: Call Claude, GPT or Gemini with the same request Here is the same call over curl: Copycurl https://api.apiko.app/v1/chat/completions \ -H "Authorization: Bearer $APIKO_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-6.1-sol", "messages": [{"role": "user", "content": "Hello"}] }' To switch models, change only the model string: claude-sonnet-5-5 for Claude, gemini-3.8-flash for Gemini, deepseek-v4-pro for DeepSeek. Do not type ids from memory or from another provider's docs. Ask the gateway which ids your key can call: curl https://api.apiko.app/v1/models \ -H "Authorization: Bearer $APIKO_API_KEY" You can also browse the model catalog, where each model page shows its supported parameters and current price. Image models such as Nano Banana use /v1/images/generations with the same key; to choose between Google's two tiers, see Nano Banana 2.1 vs Nano Banana Pro. A note on Gemini: Google runs its own OpenAI-compatible endpoint for Gemini models, so you may have seen "OpenAI-compatible API Gemini" in other guides. Through APIKO you don't need a separate Google key or base URL. Gemini models sit behind the same https://api.apiko.app/v1 as everything else. Streaming, and how to get real token usage Set "stream": true and the response arrives as server-sent events: one data: line per chunk, ending with data: [DONE]. That part is standard and rarely causes trouble. The part people miss is usage. A plain streamed response carries no usage field at all. If your logging, budgeting or per-customer billing depends on token counts, they will simply be missing on the streaming path. Add stream_options to the request: Copycurl -N https://api.apiko.app/v1/chat/completions \ -H "Authorization: Bearer $APIKO_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-6.1-sol", "messages": [{"role": "user", "content": "Hello"}], "stream": true, "stream_options": {"include_usage": true} }' With include_usage set, the last chunk carries a usage object with the real prompt and completion token counts for that request. These are the same numbers APIKO bills against, so parse that chunk rather than estimating with a local tokenizer. In Python: Copystream = client.chat.completions.create( model="gpt-6.1-sol", messages=[{"role": "user", "content": "Hello"}], stream=True, stream_options={"include_usage": True}, ) for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") if chunk.usage: # usage appears when stream_options.include_usage is enabled print(chunk.usage) Streaming is also the safer choice for long outputs. A non-streaming request with no response after 100 seconds gets a 524 from the edge proxy, but the request keeps running and is billed. A streamed response starts sending right away and avoids that. The Anthropic-native option for Claude If your code or tool already speaks Anthropic's format, you don't have to translate it. The same key works on POST /v1/messages, authenticated with x-api-key plus anthropic-version: 2023-06-01 (or Authorization: Bearer): Copycurl https://api.apiko.app/v1/messages \ -H "x-api-key: $APIKO_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-sonnet-5-5", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}] }' Anthropic's SDKs append /v1/messages themselves, so give them https://api.apiko.app as the base URL, not the /v1 URL used for OpenAI clients. Claude-specific fields such as thinking and output_config.effort go in the body as they would with Anthropic; the Claude API reference lists how each one is handled. Claude Code uses the same endpoint. Set these before starting it: export ANTHROPIC_BASE_URL="https://api.apiko.app" export ANTHROPIC_AUTH_TOKEN="$APIKO_API_KEY" export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-4-5" export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-5-5" export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-5-5" The integration guides cover Claude Code, Cursor, Cline and other tools step by step. If you stay on the OpenAI-compatible endpoint, you can still call Claude: use the Claude model id and set thinking depth with reasoning_effort. For Claude on Chat Completions the accepted values are none, minimal, low, medium, high, xhigh and max; anything else returns 400. Error codes worth handling explicitly Errors use the OpenAI body shape, so existing error handling mostly works. These are the cases to handle on purpose: Statuserror.code / typeCauseWhat to do400variesInvalid parameter or valueFix the request; do not retry401Missing, mistyped or deleted keyCheck the Authorization: Bearer header and that the key still exists in API Keys; do not retry403insufficient_user_quotaBalance is used upTop up in Billing; do not retry until you have429rate_limit_errorOver 500 requests per minute for the accountBack off with jitter; a 429 is not billed404model_not_foundModel id is wrong or the model was retiredCheck the id with GET /v1/models; retrying will not help503 / 5xxUpstream failure after the gateway's own retriesRetry with backoff; a failed request is refunded A few details from the API reference that save debugging time: The rate limit is 500 requests per minute per account, counted across all keys and models. Bursts of up to 500 are accepted, then capacity refills at about 8 requests per second. There is no Retry-After header, so start backoff at about one second. On /v1/messages, the model-not-found case shows as error.type not_found_error instead of an error.code. Most error messages end with a request id. Keep it: Task Logs lists requests by id, and support needs it when you chat with us. If you call the API with a bare HTTP library, send a normal User-Agent. Some library defaults, such as Python's built-in urllib, are rejected at the edge with error code: 1010 before they reach the gateway. The official SDKs set one for you. How billing works per request Every call follows the same three steps, streaming or not. A pre-hold is taken from your balance when the request starts, based on an estimate. When the response completes, it settles to the real usage the provider reports. If the call fails, the pre-hold is refunded automatically. Retries across channe