Документация API

Каждый маршрут API объяснён по-человечески: что делает, когда нужен и как вызвать. Если вы просто хотите работать в Cursor или VS Code — вся эта страница вам не нужна, хватит Every API endpoint is explained in plain words: what it does, when you need it and how to call it. If you just want to work in Cursor or VS Code, you don't need this page at all — the инструкции подключенияconnection guide: два поля — и работает. is enough: two fields — and it works.

1. С чего начать

Для работы нужны ровно три значения: You need exactly three values: адрес APIthe API address (Base URL), ваш ключyour key и and имя моделиthe model name. Ключ и адрес вы получаете при покупке — вставляете их в свою программу, и она начинает разговаривать с любой из актуальным моделям: GPT, Claude, Grok, DeepSeek, Qwen и другими.. You get the key and the address when you buy — paste them into your app and it can talk to any of the the current models: GPT, Claude, Grok, DeepSeek, Qwen and more.

Base URL

Популярные программы подключаются готовыми конфигами на странице Popular apps connect with ready-made configs on the «Подключение»Connect: Cursor, VS Code (Cline), Claude Code, Codex, ZCode, Python, JavaScript. Там выбрана ваша система (Windows/macOS/Linux) и команды собираются под ваш ключ. page: Cursor, VS Code (Cline), Claude Code, Codex, ZCode, Python, JavaScript. Your operating system (Windows/macOS/Linux) is already selected there, and the commands are assembled for your key.

Проверить, что ключ живой, можно за 5 секунд без единой команды — вставьте его на странице You can check that a key is live in 5 seconds without a single command — paste it on the «Баланс и логи»Balance & logs. page.

2. Что такое маршрут (endpoint)

МаршрутAn endpoint — это адрес, по которому программа отправляет запрос. У API их несколько, у каждого своя работа: один принимает чат, другой генерирует картинки, третий показывает баланс. Это как отделы в банке: «переводы», «вклады», «выписки» — обращаетесь в нужный, получаете нужное. is the address a program sends its request to. The API has several of them, each with its own job: one takes chat, another generates images, a third shows the balance. It is like departments in a bank: “transfers”, “deposits”, “statements” — go to the right one and get what you need.

Маршрут дописывается к Base URL. Например, чат живёт на The endpoint is appended to the Base URL. For example, chat lives at /v1/chat/completions, значит полный адрес такой:, so the full address is:

/chat/completions

Слово «endpoint» (эндпоинт), «маршрут» и «путь» — одно и то же. В документациях чаще пишут endpoint.

3. Ключ и адрес: как представиться серверу

Каждый запрос сопровождается заголовком Every request carries the header Authorization: Bearer sk-… — это ваш пропуск. Без него сервер отвечает — your pass. Without it the server replies 401 Unauthorized и ничего не считает. Некоторые библиотеки вместо Bearer шлют заголовок and processes nothing. Some libraries send an X-API-Key — принимается и так. header instead of Bearer — that is accepted too.

curl /chat/completions \
  -H "Authorization: Bearer sk-ВАШ_КЛЮЧsk-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-5.6-terra",
       "messages":[{"role":"user","content":"Привет!Hello!"}]}'

Ответ — JSON. Внутри The response is JSON. Inside choices[0].message.content — текст ответа модели, а в is the model's reply text, and usage — сколько токенов ушло на вход и выход. shows how many tokens the input and output took.

Ключ — как пароль от кошелька: все списания идут по нему. Не публикуйте его в открытых репозиториях и не пересылайте никому. Продавцу ваш ключ повторно не нужен никогда.

4. Чат: POST /chat/completions — главный маршрут

Через него идёт 95% трафика. Вы отправляете массив сообщений (у каждого — роль: 95% of traffic goes through it. You send an array of messages (each one has a role: system задаёт поведение, sets the behaviour, user — это вы, is you, assistant — прошлые ответы модели), и модель отвечает текстом. Формат полностью совместим с OpenAI SDK: openai-библиотеки Python и JavaScript, Cursor, Cline, Continue — всё работает через смену двух полей (Base URL и ключ). is the model's past replies) and the model answers with text. The format is fully compatible with the OpenAI SDK: the Python and JavaScript openai libraries, Cursor, Cline, Continue — everything works by changing two fields (Base URL and key).

  • model — имя модели, точно как в — the model name, exactly as in таблице моделейthe model table: gpt-5.6-terra, claude-sonnet-5, grok-4.6
  • messages — история переписки целиком; модель не помнит прошлые запросы, поэтому контекст вы передаёте сами; — the entire conversation history; the model does not remember past requests, so you pass the context yourself;
  • streamtrue включает «печатающий» ответ (см. раздел 5); turns on the “typing” response (see section 5);
  • temperature — от 0 до 2: выше = креативнее и менее предсказуемо; — from 0 to 2: higher = more creative and less predictable;
  • max_tokens — лимит длины ответа (у каждой модели свой максимум, он в таблице моделей). — the reply length limit (each model has its own maximum, listed in the model table).

Поддерживаются и картинки на входе (vision) у моделей с бейджем «Vision»: в Input images (vision) are supported for models with a “Vision” badge: content передаётся массив с carries an array with {"type":"image_url","image_url":{"url":"data:image/…"}}. Бейджи Vision / Reasoning / Tools у моделей означают: понимает картинки, «думает перед ответом», умеет вызывать инструменты.. The Vision / Reasoning / Tools badges on models mean: understands images, “thinks before answering”, can call tools.

5. Стриминг: «печатающий» ответ

Добавьте в запрос Add "stream": true — и ответ придёт не одним куском, а серией событий to the request — and the reply arrives not as one chunk but as a series of data: {…} по мере генерации. Именно так работают «живые» ответы в чатах: текст появляется слово за словом, не дожидаясь конца. events while the text is being generated. That is exactly how “live” replies work in chats: the text appears word by word, without waiting for the end.

curl /chat/completions \
  -H "Authorization: Bearer sk-ВАШ_КЛЮЧsk-YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet-5","stream":true,
       "messages":[{"role":"user","content":"Расскажи анекдотTell me a joke"}]}'

Наш сервер не буферизирует стриминг: первый кусок приходит с той же задержкой, что и у модели. Поток завершается событием Our server does not buffer the stream: the first chunk arrives with the same latency as from the model itself. The stream ends with a data: [DONE]. event.

6. POST /responses и WebSocket

Новый формат OpenAI (Responses API). Суть та же — отправили запрос, получили ответ, — но удобнее для агентов: встроенные вызовы инструментов, состояние диалога на сервере, события вместо простого текста. The new OpenAI format (Responses API). The idea is the same — send a request, get a reply — but it is more convenient for agents: built-in tool calls, conversation state kept on the server, events instead of plain text. Codex CLI работает именно через этот маршрутCodex CLI works through this exact endpoint, включая постоянное WebSocket-соединение: агент держит канал открытым и обменивается событиями в обе стороны без новых HTTP-запросов., including a persistent WebSocket connection: the agent keeps the channel open and exchanges events in both directions without new HTTP requests.

Выбирать между «chat» и «responses» вручную не нужно — программа сама использует то, что ей нужно. Оба маршрута проксируются одинаково прозрачно, WebSocket-апгрейды работают.

7. POST /messages — формат Anthropic

Тот же чат, но в структуре Claude: другой формат сообщений и заголовков. Нужен программам, которые «из коробки» говорят по-антроповски — прежде всего Claude Code и часть терминальных агентов. Запрос считает токены по тем же правилам, ответ приходит в The same chat, but in Claude's structure: a different format of messages and headers. It is needed by programs that speak Anthropic out of the box — first of all Claude Code and some terminal agents. The request counts tokens by the same rules, and the reply arrives in content[0].text.

Рядом есть Next to it is POST /messages/count_tokens: отправляете туда сообщение — получаете количество токенов : send a message there and you get the token count безwithout вызова модели и без списания. Удобно, чтобы заранее прикинуть цену длинного промпта. calling the model and without any charge. Handy for estimating the price of a long prompt in advance.

8. Картинки, аудио, видео

  • POST /images/generations — картинка по текстовому описанию; — an image from a text description;
  • POST /images/edits — правка готовой картинки по инструкции; — editing an existing image by instruction;
  • POST /audio/transcriptions — расшифровка аудио в текст; файл отправляется multipart-запросом (не JSON); — audio-to-text transcription; the file is sent as a multipart request (not JSON);
  • POST /audio/speech — озвучка текста; список доступных голосов: — text-to-speech; the list of available voices: GET /audio/voices;
  • POST /videos/generations — заказ видео; готовность проверяется через — ordering a video; readiness is checked via GET /videos/{id};
  • POST /enhance — улучшение промпта/текста вспомогательной моделью. — prompt/text improvement with a helper model.

У этих маршрутов свои коэффициенты списания — они выше текстовых моделей, потому и генерация «дорогая» по токенам. Остаток баланса всегда виден на These endpoints have their own spending multipliers — higher than text models, which is why generation is “expensive” in tokens. The remaining balance is always visible on the чекереchecker.

9. Баланс и логи

  • GET /balance — остаток токенов на ключе. Ответ: — the token balance left on the key. Response: {"object":"balance","token_balance":123456};
  • GET /keys/logs — до 30 последних списаний этого ключа: дата, модель, вход/выход, кэш, сколько списано, статус; — up to 30 latest charges of this key: date, model, input/output, cache, amount charged, status;
  • WS /usage/ws — живой поток расхода в реальном времени (для дашбордов). — a live real-time usage stream (for dashboards).

Всё то же самое — без команд: страница All of the same things — without commands: the «Баланс и логи»Balance & logs и вкладка «Дашборд» в page and the “Dashboard” tab in the кабинетеaccount (там график за сутки и неделю + выгрузка CSV). (with a 24-hour and 7-day graph + CSV export).

10. GET /models — список моделей

Возвращает все доступные модели с полями: Returns all available models with the fields: id (имя для запроса), (the name to use in requests), display_name, multiplier (коэффициент списания), (the spending multiplier), context_window (сколько «памяти» в токенах), (how much “memory” in tokens), max_output_tokens (лимит ответа) и флаги (the reply limit) and the flags supports_vision / reasoning / tools.

На сайте этот список превращён в On the site this list becomes a таблицу моделейmodel table с фильтрами по производителям, описанием каждой модели (кнопка «i») и сортировкой по мощности — искать глазами JSON не придётся. with filters by vendor, a description of every model (the “i” button) and sorting by power — no need to eyeball the JSON.

11. Как считаются токены

ТокенA token — единица обработки: примерно одно короткое слово (в русском языке — часто 2–4 символа). За каждый запрос списывается: is a unit of processing: roughly one short word (often 2–4 characters). Each request is charged as:

(входные токены + выходные токены) × коэффициент модели(input tokens + output tokens) × model multiplier

Коэффициент — множитель «ценности» модели: запрос к флагману с ×2,5 стоит в два с половиной раза дороже токенов, чем к эконом-модели с ×0,1. Обычный запрос в чате — это 2–5 тысяч токенов на вход и выход суммарно.

  • КэшCache — если повторяете длинный неизменный промпт, часть входа считается по сниженной цене и показывается отдельно в логах (колонка «Кэш»); — if you repeat a long, unchanged prompt, part of the input is counted at a reduced price and shown separately in the logs (the “Cache” column);
  • Ошибка запросаA failed request — токены не списываются (исключение — уже сгенерированная часть ответа); — no tokens are charged (the exception is the part of the reply already generated);
  • Неиспользованные токены не сгораютUnused tokens never expire — лежат на балансе ключа, пока вы их не потратите. — they stay on the key's balance until you spend them.

12. Ошибки и повторы

Ошибка приходит JSON-ом вида An error arrives as JSON of the form {"error":{"message":"…","type":"…","code":"…"}}. Что делать по каждому коду:. What to do for each code:

КодЧто значитЧто делать
400Ошибка в запросе: имя модели, кривой JSON, лишний параметрSomething is wrong in the request: the model name, malformed JSON, an extra parameterПроверьте ID модели по Check the model ID against the таблицеtable и формат запроса and your request format
401Ключ неверный, отозван или скопирован не полностьюThe key is wrong, revoked, or was copied incompletelyСкопируйте ключ заново, без пробеловCopy the key again, with no spaces
402Баланс ключа исчерпанThe key's balance is exhaustedПополните в кабинете или напишите продавцуTop up in your account or message the seller
403Действие запрещено для этого ключаThis action is not allowed for this keyВыберите другую модель или уточните лимиты у продавцаPick another model or check the limits with the seller
429Слишком много запросов подряд (rate limit)Too many requests in a row (rate limit)Подождите 10–60 секунд; в заголовке Retry-After — сколько именноWait 10–60 seconds; the Retry-After header says exactly how long
503Временная перегрузкаA temporary overloadПовторите через несколько секунд; токены не списываютсяRetry in a few seconds; no tokens are charged

Повторять безопасно только Only 429 и and 503 — они транзиентные. При are safe to retry — they are transient. For 400/401/402/403 повтор с тем же запросом бессмысленен. Полный разбор — в , repeating the same request is pointless. The full breakdown is in the FAQ.