OneKey API
An OpenAI-compatible API for AI models. The base path of every endpoint is /v1.
Quick start
OpenAI SDK compatible. In existing code just point base_url and the key at us — everything else works as is. The full docs live on this single page below.
Need code? Three steps:
- Take your key
The key is taken from the dashboard: the Keys section — it starts with sk-. No key yet? Click «Create key» there.
- Install the OpenAI library
pip install openai for Python, npm install openai for Node.js.
- Paste your key — done
Copy the example below and replace sk-ВАШ-КЛЮЧ with your key from step 1. Leave the URL as is.
# Python
from openai import OpenAI
client = OpenAI(
api_key="sk-ВАШ-КЛЮЧ", # ← сюда вставь свой ключ
base_url="https://api.onekey.gg/v1",
)
resp = client.chat.completions.create(
model="gpt-5.6-sol",
messages=[{"role": "user", "content": "Привет!"}],
)
print(resp.choices[0].message.content)That is it. The code is the same as for OpenAI — only the key and URL (base_url) differ. Streaming, tools, vision, and image generation are documented in the sections below.
Authentication
Every API request requires authentication with a Bearer token in the Authorization header.
HTTP header
Authorization: Bearer sk-ВАШ-КЛЮЧImportant: never keep API keys in client-side code or public repositories. Use environment variables.
OpenAI compatibility
OneKey implements the OpenAI Chat Completions API — most OpenAI code and tools work unchanged. What is supported:
| Capability | Status |
|---|---|
| Streaming (SSE) | Yes, for text models |
| Functions / tool calling | Per model — see catalog |
| Images as input (vision) | Per model — see catalog |
| reasoning_effort / reasoning_content | Per model and endpoint |
| temperature · top_p · max_tokens · stop | Per model; unsupported fields may be rejected |
| OpenAI SDK (Python / Node / Go / …) | Yes |
| Anthropic SDK (/v1/messages) | Yes, Claude only |
| Context cache | Automatic when the provider returns cache usage |
| response_format / json_mode | Per model; expect 400 responses |
| Image generation | gpt-image-2 · /v1/images/generations |
| Embeddings · seed · logprobs · n>1 | Not declared compatible |
Do not expect unknown parameters to be silently ignored: upstream providers may return 400. Send only the fields supported by the chosen model and endpoint.
SDKs and languages
Any OpenAI-compatible SDK works — set base_url to https://api.onekey.gg/v1. No SDK? It is plain HTTP. Examples:
Go
// Go — github.com/openai/openai-go
client := openai.NewClient(
option.WithAPIKey("sk-ВАШ-КЛЮЧ"),
option.WithBaseURL("https://api.onekey.gg/v1"),
)
resp, _ := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
Model: "gpt-5.6-sol",
Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("Hello!")},
})
fmt.Println(resp.Choices[0].Message.Content)PHP
<?php // PHP (curl)
$ch = curl_init("https://api.onekey.gg/v1/chat/completions");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer sk-ВАШ-КЛЮЧ", "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode([
"model" => "gpt-5.6-sol",
"messages" => [["role" => "user", "content" => "Hello!"]],
]),
]);
echo curl_exec($ch);OpenAPI and Postman
The service does not publish a spec file or a ready-made Postman collection yet — every endpoint and parameter is documented on this page.
The documentation works manually: the endpoint descriptions suit building requests in Postman/Insomnia and generating clients after the sections below.
Chat Completions
A single endpoint for all chat models. Switch providers by changing the model parameter.
Request
curl https://api.onekey.gg/v1/chat/completions \
-H "Authorization: Bearer sk-ВАШ-КЛЮЧ" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.5",
"messages": [
{"role": "user", "content": "Hello!"}
],
"temperature": 0.7
}'Parameter
| Parameter | Type | Description |
|---|---|---|
model | string | Model id from the live catalog — the Models section |
messages | array | Array of messages with role and content |
temperature | float | Creativity from 0 to 2 (default 1) |
max_tokens | integer | Maximum number of tokens |
stream | boolean | Stream the response |
Streaming (SSE)
Add stream: true — text models return Server-Sent Events, with Chat Completions tokens arriving in choices[0].delta.content. The Responses API event format is different and is described in its section. Image generation returns plain JSON.
Python (openai SDK)
# Python (openai SDK)
stream = client.chat.completions.create(
model="gpt-5.6-sol",
messages=[{"role": "user", "content": "Tell me a short story"}],
stream=True,
stream_options={"include_usage": True}, # usage in the final chunk
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)cURL
curl https://api.onekey.gg/v1/chat/completions -H "Authorization: Bearer sk-ВАШ-КЛЮЧ" -H "Content-Type: application/json" -d '{"model":"gpt-5.6-sol","messages":[{"role":"user","content":"Hi"}],"stream":true}'Responses API
POST /v1/responses is available to every GPT model whose live catalog entry lists this endpoint. With stream: true it returns SSE; without stream it returns plain JSON. For Claude, use Chat Completions or Messages.
Request
curl https://api.onekey.gg/v1/responses \
-H "Authorization: Bearer sk-ВАШ-КЛЮЧ" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.6-sol",
"input": "Привет!",
"max_output_tokens": 256,
"stream": true
}'POST /v1/responses/compact is GPT/Codex-only and compacts long histories. Call it before reaching the catalog context_window. Do not send provider-specific reasoning/item IDs persisted from another account.
For Codex CLI, use the context settings from the Guides: 353K for GPT-5.6 and auto-compact before that threshold.
Messages API (Anthropic)
The /v1/messages endpoint is the native Anthropic Messages format for Claude models (opus / sonnet / haiku). Compatible with the Anthropic SDK and Claude clients such as SillyTavern. Claude also works via the standard /v1/chat/completions.
Request
curl https://api.onekey.gg/v1/messages \
-H "Authorization: Bearer sk-ВАШ-КЛЮЧ" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4-8",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Привет!"}
]
}'For Python use the anthropic SDK with base_url="https://api.onekey.gg" and the same key.
Functions (function calling)
Pass tools[] and the model returns tool_calls with arguments. You run the function and send the result back as a role:"tool" message. Works for both GPT and Claude — the basis of agents (Cline, Roo, bots).
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "Weather in Paris?"}]
resp = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
call = resp.choices[0].message.tool_calls[0] # name + arguments (JSON)
# run your function, then send the result back:
messages.append(resp.choices[0].message)
messages.append({"role": "tool", "tool_call_id": call.id, "content": "sunny, 22C"})
final = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
print(final.choices[0].message.content)Images as input (Vision)
Put an array of text and image_url blocks into content. A public URL or data:base64 is accepted. Multimodal models support it (gpt-5.x, claude-opus/sonnet).
resp = client.chat.completions.create(
model="gpt-5.6-sol",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "https://example.com/cat.jpg"}},
# or base64: {"url": "data:image/png;base64,iVBORw0K..."}
],
}],
)
print(resp.choices[0].message.content)Image generation
Use POST /v1/images/generations with the gpt-image-2 model. The response carries base64 in data[0].b64_json; save it as PNG or serve it via data:image/png;base64,...
Request
curl https://api.onekey.gg/v1/images/generations \
-H "Authorization: Bearer sk-ВАШ-КЛЮЧ" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A precise isometric diagram of a lunar research station"
}'Response
{
"created": 1784480400,
"data": [{ "b64_json": "iVBORw0KGgoAAA..." }]
}It is a separate endpoint: image_url in Vision passes a picture as model input, while /images/generations creates a new picture.
Reasoning
For GPT models steer the depth with reasoning_effort. Supported values depend on the model; the safe set is low · medium · high, and use minimal/xhigh only when the model’s client lists them. reasoning_content and reasoning_tokens are not returned by every provider in every endpoint.
resp = client.chat.completions.create(
model="gpt-5.6-sol",
messages=[{"role": "user", "content": "A train goes 60km in 1.5h then 90km in 2h. Average speed?"}],
reasoning_effort="high",
)
msg = resp.choices[0].message
print(msg.reasoning_content) # the model's step-by-step reasoning
print(msg.content) # the final answer
print(resp.usage.completion_tokens_details.reasoning_tokens)In Chat Completions, reasoning may arrive as choices[0].delta.reasoning_content separately from delta.content. If the field is absent, use the final content; missing reasoning_content is not an error.
Context caching
OneKey passes a stable prefix to the provider and accounts for cache usage when upstream returns it. A cache hit is not guaranteed: it depends on the model, the chosen account/provider, the size, and an exact match of the request head.
"usage": {
"prompt_tokens": 12000,
"prompt_tokens_details": { "cached_tokens": 11500 },
"completion_tokens": 200
}To hit the cache more often: keep system and early history unchanged, preserve the order of tools and their JSON Schema, and append new user input at the end. Always check the real cached_tokens in usage.
Models
The live model catalog with prices lives on the Models page and in GET /v1/models; a disabled or removed model disappears from it automatically.
curl https://api.onekey.gg/v1/models -H "Authorization: Bearer sk-ВАШ-КЛЮЧ"Balance and usage
Check spend, limits, and the key expiry programmatically — GET /api/quota with the same Bearer key:
curl https://api.onekey.gg/api/quota -H "Authorization: Bearer sk-ВАШ-КЛЮЧ"{
"cost": 1.2345, // USD spent on this key
"tokens_used": 482113,
"daily_tokens_used": 5120,
"remaining_tokens": 24994880,
"rpm": 60, "rph": 600, // paid-tier limits for this key
"expires_at": "2026-07-01T00:00:00Z"
}cost is the API key’s cumulative USD spend. rpm/rph describe the key and do not represent the USD wallet balance; see Billing for the current balance. Free and paid rate limits use independent buckets.
Error codes
| Code | HTTP | Description |
|---|---|---|
invalid_api_key | 401 | The key is missing, disabled, or invalid. |
model_not_found | 404 | The model is not in the live catalog or is temporarily disabled. |
invalid_request_error | 400 | Fix the request body; do not retry it unchanged. |
context_length_exceeded | 400 | Compact the history below the selected model’s context_window. |
rate_limit_exceeded | 429 | Wait for Retry-After and retry with backoff. |
concurrent_stream_limit | 429 | Finish one of the parallel streams; the balance is not the issue. |
key_spend_limit_reached | 429 | Raise the API key spend limit in the dashboard. |
insufficient_balance | 429 | Top up the USD balance. |
content_policy_violation | 403 | Do not repeat the same content; on a false positive pass the support request id. |
upstream_stream_incomplete | 502 | If no useful deltas arrived yet — one safe retry; otherwise continue from a new request. |
Errors and retries
Recommendations for a robust integration:
| HTTP | What to do |
|---|---|
429 | Read error.code first. Retry with backoff only on rate_limit_exceeded/concurrent_stream_limit; balance and spend limits need user action. |
5xx | Before the first useful content/tool delta, make 1–2 retries with jitter. After useful streaming starts, do not retry automatically: a tool action may be duplicated. |
400 | Bad request — fix the body, do not retry as-is. |
401 | Invalid or inactive key. |
Sixty seconds is not enough for long reasoning/agent requests. Split the connect timeout from the overall read timeout:
client = OpenAI(
api_key="sk-ВАШ-КЛЮЧ",
base_url="https://api.onekey.gg/v1",
max_retries=2,
timeout=300,
)Keep the request id from headers/errors: support needs it to locate the request. client_cancelled means the client or its proxy closed the connection, not necessarily the model.
Rate limits
Billing is pay-per-use: requests are charged against your prepaid USD balance at each model’s per-token price. There are no subscription tiers — you pay only for what you actually use.
Rate limits are enforced per account and shared by all of its API keys. The selected tier’s current limit and remaining allowance are returned in the response headers:
X-RateLimit-Limit-Requests: 60
X-RateLimit-Remaining-Requests: 59Two independent limits apply: free requests do not consume the paid-model limit, and paid requests do not consume the free-tier limit:
| Group | Models | RPM | RPH |
|---|---|---|---|
| All paid models | All models except the free tier | 60 | 600 |
| Free tier | gpt-5.4-mini | 15 | 150 |
RPM = requests per minute, RPH = requests per hour. Existing custom paid-tier limits remain unchanged. Exceeding either returns HTTP 429 (rate_limit_exceeded). Need different limits? Email [email protected].
Up to 20 streams can run in parallel on one API key. Exceeding it returns 429 concurrent_stream_limit and does not mean the balance is exhausted.