← GhostGPT

GhostGPT API

OpenAI-совместимый HTTP API к модели GhostGPT. Работает по ключу и оплачивается отдельно от чата — API-тарифом. Веб-чат: ghostgpt.io

OpenAI-compatible HTTP API for the GhostGPT model. Works with an API key and is paid separately from the chat, with an API plan. Web chat: ghostgpt.io

Главная ссылка для интеграции (Base URL): Main integration link (Base URL): https://api.ghostgpt.io/v1

С чего начать

Getting started

Три шага, каждый занимает минуту.

Three steps, a minute each.

  1. Зарегистрируйтесь на ghostgpt.io: почта и пароль, Google или Telegram. Телефон не нужен.
  2. На странице API-ключа выберите API-тариф — API Start или API Pro — и оплатите криптовалютой, зарубежной картой (Visa / Mastercard) или через СБП по QR (для России). Платёж разовый, без автосписаний. С оплаченной подпиской на чат API можно сначала попробовать на небольшом пробном лимите.
  3. Там же нажмите «Получить API-ключ». Ключ показывается ровно один раз.
  1. Sign up at ghostgpt.io: email and password, Google or Telegram. No phone number.
  2. On the API key page choose an API plan — API Start or API Pro — and pay with crypto, a Visa / Mastercard card, or SBP QR (Russia). One-off payment, no recurring charges. With a paid chat subscription you can first try the API on a small trial allowance.
  3. Press “Get an API key” on the same page. The key is shown exactly once.

Дальше — настройки клиента:

Then configure your client:

ПолеЗначение
Base URL / API URLhttps://api.ghostgpt.io/v1
Modelghostgpt
API KeySK-… (заголовок Authorization: Bearer)
FieldValue
Base URL / API URLhttps://api.ghostgpt.io/v1
Modelghostgpt
API KeySK-… (Authorization: Bearer header)

Проверка одной командой — она не тратит квоту:

One-command check — it does not consume quota:

curl https://api.ghostgpt.io/v1/models \
  -H "Authorization: Bearer SK-YOUR-KEY"

Машиночитаемый манифест: /api.json

Machine-readable manifest: /api.json

Важно: https://api.ghostgpt.io/v1 — это Base URL для клиента, а не страница в браузере. Документация живёт на /, проверка ключа — на /v1/models.

Note: https://api.ghostgpt.io/v1 is a client Base URL, not a browsable page. Docs live at /; check the key at /v1/models.

Тарифы API

API plans

Документация открыта всем. Сам API оплачивается отдельно от чата: подписка на чат его не включает (кроме небольшого пробного лимита), а API-тариф ничего не добавляет в чат. Счётчики у них тоже раздельные — запросы по ключу не тратят сообщения чата.

The documentation is public. The API itself is paid separately from the chat: a chat subscription does not include it (apart from a small trial allowance), and an API plan adds nothing to the chat. Their counters are separate too — requests by key never spend chat messages.

ТарифЦена за 30 днейТокенов ответа в суткиЗапросов в суткиОдновременно
API Start$15 или 1 490 ₽300 0001 5001
API Pro$39 или 3 890 ₽1 000 0006 0002
Пробный лимит — при оплаченной подписке на чатвходит в подписку20 000501
PlanPrice per 30 daysOutput tokens a dayRequests a dayAt once
API Start$15 or 1,490 ₽300,0001,5001
API Pro$39 or 3,890 ₽1,000,0006,0002
Trial allowance — with a paid chat subscriptionincluded in it20,000501

Главная мера — токены ответа. Ответ на 4 096 токенов занимает видеокарту столько же, сколько сорок коротких, поэтому суточный лимит считается в выданных моделью токенах (usage.completion_tokens), а число запросов — лишь защита от шквала мелких. Токены вашего вопроса в лимит не входят.

Output tokens are the main measure. A 4,096-token answer takes the GPU as long as forty short ones, so the daily limit counts the tokens the model produced (usage.completion_tokens); the request count only guards against a flood of tiny calls. Your prompt tokens do not count.

Мест на API Pro немного. Сервис работает на одной видеокарте вместе с чатом, поэтому одновременно действующих тарифов Pro — несколько. Когда места заняты, страница оплаты говорит об этом до платежа; продлить свой Pro можно всегда, пока он действует и ещё 72 часа после его конца.

API Pro has a few seats. The service runs on one GPU together with the chat, so only a few Pro plans can be active at once. When all seats are taken the payment page says so before you pay; renewing your own Pro is always possible while it runs and for 72 hours after it ends.

СостояниеЧто даёт ключ
API-тариф действуетлимиты тарифа
Первые 72 часа после конца тарифадо конца тех суток (UTC), в которые тариф кончился, — его лимиты, дальше пробный лимит; всё это время заголовок Warning
Тарифа нет, подписка на чат оплаченапробный лимит
Ни того ни другого402 api_plan_required
StateWhat the key gets
API plan in forcethe plan’s limits
First 72h after the plan endsthe plan’s limits until the end of that UTC day, then the trial allowance; a Warning header all along
No plan, paid chat subscriptiontrial allowance
Neither402 api_plan_required

72 часа после конца тарифа — не подарок, а защита от простоя: тариф может кончиться в три часа ночи, и ваш продакшен обязан дожить до утра. В эти часы каждый ответ несёт заголовок Warning: 199 ghostgpt "…"; до конца суток, в которые тариф кончился, действуют его лимиты (расход этих суток уже на счётчиках), со следующих — пробный. Тот же заголовок приходит и за трое суток до конца.

The 72-hour window is not a gift but downtime protection: a plan can end at 3 a.m., and your production must survive until morning. During that window every response carries Warning: 199 ghostgpt "…"; for the rest of the UTC day the plan ended its limits still apply (that day’s use is already on the counters), from the next day the trial allowance does. The same header also arrives during the three days before the end.

Продление и смена тарифа. Покупка того же тарифа добавляет 30 дней к остатку. Покупка другого не сжигает оплаченное: оставшиеся дни пересчитываются по ценам тарифов, так что ни в одну сторону это не выгоднее и не дороже прямой покупки (с Start на Pro — ×0,38, с Pro на Start — ×2,6), и к ним добавляются 30 дней нового тарифа. Ключ после оплаты оживает сам — перевыпускать его не нужно.

Renewing and switching. Buying the same plan adds 30 days to what is left. Buying the other one does not burn what you paid: the remaining days are converted at the plans’ prices, so neither direction is worth more or less than buying outright (Start to Pro ×0.38, Pro to Start ×2.6), and the new plan’s 30 days are added on top. After payment the key comes back by itself — no re-issue needed.

Ключи, выданные до 12.10.2026, когда API входил в подписку на чат, сохраняют прежние лимиты (250 запросов и 150 000 токенов в сутки) до конца уже оплаченного срока подписки. Дальше — API-тариф.

Keys issued before 12.10.2026, when the API came with the chat subscription, keep the previous limits (250 requests and 150,000 tokens a day) until the end of the subscription already paid for. After that, an API plan.

Действующие цены — на странице API-ключа, они главнее этой таблицы. API-тарифы продаются на сайте — криптовалютой, зарубежной картой или через СБП; оплата разовая: автосписаний нет, карта не привязывается. Для всех стран цена одна.

Current prices are on the API key page and take precedence over this table. API plans are sold on the site, with crypto, a card or SBP; payments are one-off: no recurring charges, no stored cards. The price is the same for every country.

Ключ

API key

Authorization: Bearer SK-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX

Управление ключом

Managing the key

Через интерфейс — на странице API-ключа: получить, заменить, отключить. Через HTTP — с cookie сессии сайта, то есть после входа почтой, через Google или Telegram. POST принимается только со страниц самого сайта (проверяется заголовок Origin, иначе 403 {"error": "bad_origin"}) — например, из консоли браузера на открытой вкладке ghostgpt.io:

Through the UI — on the API key page: get, replace, turn off. Over HTTP — with the site's session cookie, that is after signing in by email, Google or Telegram. A POST is accepted only from the site’s own pages (the Origin header is checked, otherwise 403 {"error": "bad_origin"}) — for example, from the browser console on an open ghostgpt.io tab:

МетодПутьЧто делает
GETghostgpt.io/api/access/apikeyЕсть ли ключ, когда создан, когда им пользовались; тариф, его срок и расход лимитов за сегодня. Секрета не отдаёт.
POSTghostgpt.io/api/access/apikeyВыдать или перевыпустить. Требует API-тарифа (или оплаченной подписки на чат — с пробным лимитом), иначе 402 api_plan_required.
POSTghostgpt.io/api/access/apikey/revokeПогасить ключ. Действует немедленно.
MethodPathWhat it does
GETghostgpt.io/api/access/apikeyWhether a key exists, when it was created and last used; the plan, its term and today’s use of its limits. Never returns the secret.
POSTghostgpt.io/api/access/apikeyIssue or rotate. Requires an API plan (or a paid chat subscription — with the trial allowance), otherwise 402 api_plan_required.
POSTghostgpt.io/api/access/apikey/revokeRevoke the key. Takes effect immediately.
{
  "key": {"key_id": "K7ZQ3M2X1", "created_at": 1787930020, "last_used_at": null},
  "api": {
    "plan": "start",
    "until": 1790522020,
    "grace": false,
    "daily_requests": 1500,
    "daily_out_tokens": 300000,
    "concurrency": 1,
    "used_requests": 12,
    "used_out_tokens": 8400,
    "reset_at": 1787961600
  },
  "secret": "SK-…"
}

api.plan — start, pro, legacy (ключи до 12.10.2026), trial (пробный лимит подписки на чат) или null, если API недоступен. grace: true — тариф кончился и идут 72 часа льготы: до конца тех суток (UTC), в которые он кончился, — его лимиты, дальше пробный; plan всё это время называет кончившийся тариф.

api.plan is start, pro, legacy (keys from before 12.10.2026), trial (the trial allowance of a chat subscription) or null when the API is not available. grace: true means the plan has ended and its 72-hour grace is running: the plan’s limits until the end of the UTC day it ended, then the trial allowance; all the while plan names the plan that ended.

Поле secret приходит только в ответе на выдачу — больше нигде и никогда.

The secret field appears only in the issue response — nowhere else, ever.

Где принимается ключ

Where the key is accepted

На api.ghostgpt.io (основной адрес), на ghostgpt.io — второй оставлен для клиентов, заведённых до появления отдельного домена, — и на onion-зеркале (см. ниже). Cookie веб-чата работает на ghostgpt.io, app.ghostgpt.io и на зеркале, но не на api.ghostgpt.io.

On api.ghostgpt.io (the main address), on ghostgpt.io — the latter is kept for clients set up before the separate domain existed — and on the onion mirror (see below). The web-chat cookie works on ghostgpt.io, app.ghostgpt.io and on the mirror, but not on api.ghostgpt.io.

Если в Authorization положить старый токен входа (GG-…, их выдавали до 11.10.2026) вместо ключа, ответ будет 401 use_api_key: токен открывает сайт, а программам нужен ключ SK-…. Код назван отдельно, чтобы вы не искали опечатку.

Putting an old sign-in token (GG-…, issued until 11.10.2026) into Authorization instead of a key returns 401 use_api_key: the token opens the site, programs need an SK-… key. The code is separate so you do not go hunting for a typo.

Ключи из старого общего списка, выданные до ключей аккаунтов, принимаются до 31.12.2026. Ответы на них несут заголовки Deprecation: true, Sunset: Wed, 31 Dec 2026 23:59:59 GMT и Link на этот раздел; после этой даты такой ключ получает 401 invalid_api_key. Замените его своим ключом SK-… со страницы ключа.

Keys from the old shared list, issued before account keys, are accepted until 31.12.2026. Responses to them carry Deprecation: true, Sunset: Wed, 31 Dec 2026 23:59:59 GMT and a Link to this section; after that date such a key gets 401 invalid_api_key. Replace it with your own SK-… key from the key page.

Доступ через Tor

Access over Tor

Тот же API отвечает на onion-зеркале — без выхода в обычный интернет и без DNS:

The same API answers on the onion mirror — with no exit to the ordinary internet and no DNS:

http://ghostgptdcxf76dzznn6wv4gzruvfs4h4bx7rootrwluxxvbtujiueqd.onion/v1

Ключ предъявляется так же, тем же заголовком Authorization; отдельного адреса вида api.…onion нет и не нужно. Схема только http: сертификата для .onion не существует, шифрование и подлинность адреса обеспечивает сама сеть Tor.

The key is presented the same way, in the same Authorization header; there is no separate api.…onion address and none is needed. The scheme is http only: no certificate exists for .onion, and encryption plus address authenticity come from the Tor network itself.

curl --socks5-hostname 127.0.0.1:9050 \
  http://ghostgptdcxf76dzznn6wv4gzruvfs4h4bx7rootrwluxxvbtujiueqd.onion/v1/chat/completions \
  -H "Authorization: Bearer SK-…" \
  -H "Content-Type: application/json" \
  -d '{"model":"ghostgpt","messages":[{"role":"user","content":"ping"}]}'

В библиотеке OpenAI достаточно подменить base_url и направить транспорт в SOCKS5-порт Tor (обычно 9050; в Tor Browser — 9150).

With the OpenAI library it is enough to swap base_url and point the transport at Tor's SOCKS5 port (usually 9050; 9150 in Tor Browser).

Предел «запросов в минуту с адреса» на зеркале считается по ключу. Адреса клиента там не существует: соединение приходит от локального демона Tor, и по адресу все гости зеркала неотличимы. Поэтому запрос с ключом считается по самому ключу: у каждого ключа своё ведро с той же ставкой в минуту, что у адреса на api.ghostgpt.io. Предел одновременных запросов вашего тарифа действует одинаково везде.

On the mirror the per-IP rate limit counts per key. There is no client address there: the connection arrives from the local Tor daemon, so by address all mirror visitors are indistinguishable. A request with a key is therefore counted by the key itself: each key gets its own bucket at the same per-minute rate an address gets on api.ghostgpt.io. Your plan’s limit on concurrent requests applies everywhere alike.

Модель

Model

СвойствоЗначение
Идентификаторghostgpt
Псевдонимыghostgpt, default, auto
Контекст32 768 токенов на запрос
Ответдо 16 384 токенов
Модальноститекст и изображения на входе, текст на выходе
Одна картинкадо 768 токенов
Цепочка рассужденийвыключена — ответ приходит сразу
PropertyValue
Identifierghostgpt
Aliasesghostgpt, default, auto
Context32,768 tokens per request
Responseup to 16,384 tokens
Modalitiestext and images in, text out
One imageup to 768 tokens
Reasoning tracesoff — the answer arrives directly

Любое значение поля model переписывается на текущую модель. Прислали gpt-4o — получите тот же ghostgpt, ошибки не будет. В ответе всегда стоит "model": "ghostgpt".

Whatever you put in model is rewritten to the current model. Send gpt-4o and you still get ghostgpt, without an error. Responses always carry "model": "ghostgpt".

Модель обслуживает два запроса одновременно на весь сервис. Запросам по ключам — всем аккаунтам вместе — отдан один из двух, второй всегда остаётся веб-чату, поэтому ключам модель отвечает по одному. Предел на аккаунт — сколько запросов может быть открыто сразу: Start — 1, Pro — 2, пробный — 1. Пока место ключей занято другим ответом, запрос ждёт своей очереди: у Pro второй запрос встанет в очередь, а не получит 429. См. Лимиты.

The model serves two requests at a time for the whole service. Requests by key, all accounts together, get one of the two; the other always stays with the web chat, so the model answers keys one at a time. The per-account limit is how many requests may be open at once: Start 1, Pro 2, trial 1. While the keys' slot is busy with another answer, a request waits its turn: on Pro a second request joins the line instead of getting a 429. See Limits.

Эндпоинты

Endpoints

МетодПутьНазначениеТратит квоту
POST/v1/chat/completionsЧат — единственная ручка генерациида: 1 запрос и токены ответа
GET/v1/modelsСписок моделей, проверка ключанет
GET/healthЖив ли сервис (без ключа)нет
MethodPathPurposeCosts quota
POST/v1/chat/completionsChat — the only generation endpointyes: 1 request plus the output tokens
GET/v1/modelsList models, verify the keyno
GET/healthService liveness (no key needed)no

Любой другой путь под /v1/ отвечает 404 unknown_endpoint в формате ошибки OpenAI — в том числе /v1/completions, /v1/embeddings, /v1/responses, /v1/messages.

Any other path under /v1/ returns 404 unknown_endpoint in the OpenAI error format — including /v1/completions, /v1/embeddings, /v1/responses, /v1/messages.

/v1/models никогда не отвечает 402. Это ручка, которой библиотеки проверяют связь при старте: отказ по выбранной квоте означал бы, что приложение не может подняться до полуночи UTC, не потратив ни одного токена.

/v1/models never returns 402. Client libraries call it at startup: refusing on an exhausted quota would mean the app cannot even boot until midnight UTC without spending a single token.

Chat Completions

Формат — как у OpenAI Chat API. Совместимость проверена на официальном SDK openai для Python и Node без единой правки.

Same shape as the OpenAI Chat API. Verified against the official openai SDK for Python and Node with no changes.

curl

curl https://api.ghostgpt.io/v1/chat/completions \
  -H "Authorization: Bearer SK-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ghostgpt",
    "messages": [
      {"role": "user", "content": "Hello! What is GhostGPT API?"}
    ],
    "max_tokens": 512
  }'

Python (openai)

pip install openai

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.ghostgpt.io/v1",
    api_key=os.environ["GHOSTGPT_API_KEY"],   # the key lives in the environment, not in the code
)

resp = client.chat.completions.create(
    model="ghostgpt",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=512,
)
print(resp.choices[0].message.content)
print(resp.usage.completion_tokens)          # output tokens are always counted

Node (openai)

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.ghostgpt.io/v1",
  apiKey: process.env.GHOSTGPT_API_KEY,
});

const r = await client.chat.completions.create({
  model: "ghostgpt",
  messages: [{ role: "user", content: "Hello" }],
  max_tokens: 512,
});
console.log(r.choices[0].message.content);

Обработка отказов

Handling refusals

import os, time
import openai

client = openai.OpenAI(
    base_url="https://api.ghostgpt.io/v1",
    api_key=os.environ["GHOSTGPT_API_KEY"],
    max_retries=0,                             # retries are decided below
)

def ask(messages, tries=3):
    for _ in range(tries):
        try:
            return client.chat.completions.create(model="ghostgpt", messages=messages)
        except openai.APIStatusError as e:
            if e.code == "capacity_exhausted":     # service-wide ceiling: back after 00:00 UTC
                raise
            if e.status_code in (429, 503):        # your own parallel request, or a busy model
                time.sleep(int(e.response.headers.get("Retry-After", 5)))
                continue
            raise                                  # 401 and 402 do not pass on retry
    raise RuntimeError("giving up")

Повторять стоит только 429 и 503 — кроме 503 capacity_exhausted: общий суточный потолок сервиса освободится только в 00:00 UTC, и повтор по его Retry-After: 300 лишь потратит ваши попытки. 401 означает неверный ключ, 402 — нет тарифа или кончились его лимиты на сегодня: ни то ни другое от повтора не исправится. Встроенные повторы SDK выключены (max_retries=0), чтобы решал ваш код, а не библиотека: сама она повторила бы и capacity_exhausted.

Only 429 and 503 are worth retrying — except 503 capacity_exhausted: the service-wide daily ceiling frees up only at 00:00 UTC, and retrying on its Retry-After: 300 just burns your attempts. 401 means a bad key, 402 means there is no plan or its limits for today are spent: neither is fixed by retrying. The SDK’s own retries are off (max_retries=0) so that your code decides, not the library: left on, it would retry capacity_exhausted too.

Стриминг

Streaming

Добавьте "stream": true — ответ пойдёт чанками SSE, как в OpenAI.

Add "stream": true and the answer arrives as SSE chunks, OpenAI-style.

curl -N https://api.ghostgpt.io/v1/chat/completions \
  -H "Authorization: Bearer SK-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ghostgpt",
    "stream": true,
    "messages": [{"role": "user", "content": "Write a short poem"}]
  }'

Изображения

Images

Формат OpenAI: base64 data-URI или ссылка.

OpenAI format: base64 data-URI or a URL.

{
  "model": "ghostgpt",
  "messages": [{
    "role": "user",
    "content": [
      {"type": "text", "text": "What is in this image?"},
      {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,..."}}
    ]
  }]
}

Что сервер меняет в запросе

What the server rewrites

Шлюз не проксирует тело как есть. Перечислено всё, что он трогает, — остальное уходит в модель нетронутым.

The gateway does not pass the body through untouched. Everything it changes is listed below; the rest goes to the model as is.

ПолеЧто происходит
modelПереписывается на текущую модель.
messages[role=system], messages[role=developer]Клиентский системный промпт отбрасывается — роль developer считается тем же system, — подставляется серверный. Личность и правила GhostGPT переопределить нельзя.
max_tokensПриводится к диапазону 32…16384. Нет поля, ноль, отрицательное или не целое — 16384. Меньше 32 — поднимается до 32.
repeat_penalty, frequency_penalty, repeat_last_nrepeat_penalty и frequency_penalty поднимаются до нижней границы (1.12 / 0.25). repeat_last_n меньше 64 (или не целое) заменяется на 128; 64 и больше проходит как есть. Ниже — модель уходит в петлю и жжёт GPU впустую.
grammar, grammar_type, grammar_lazy, grammar_triggers, json_schemaУдаляются. Грамматика — это способ повесить движок одним запросом.
response_formatjson_object и json_schema удаляются; ответ придёт текстом с кодом 200. Строгого JSON нет.
logit_bias и родственныеУдаляются.
tools, tool_choice, parallel_tool_calls, functions, function_callУдаляются; запрос идёт обычным чатом. Вызова функций нет.
chat_template_kwargsУдаляется; параметры шаблона диалога задаёт сервер.
stream_options.include_usageПринудительно true для потоковых запросов.
FieldWhat happens
modelRewritten to the current model.
messages[role=system], messages[role=developer]Your system prompt is dropped — the developer role is treated as system — and the server’s one is injected. GhostGPT’s persona and rules cannot be overridden.
max_tokensClamped to 32…16384. Missing, zero, negative or not an integer becomes 16384. Below 32 is raised to 32.
repeat_penalty, frequency_penalty, repeat_last_nrepeat_penalty and frequency_penalty are raised to the floor (1.12 / 0.25). repeat_last_n below 64 (or not an integer) is replaced with 128; 64 and above passes unchanged. Below that the model loops and burns GPU for nothing.
grammar, grammar_type, grammar_lazy, grammar_triggers, json_schemaRemoved. A grammar is a way to hang the engine with a single request.
response_formatjson_object and json_schema are removed; you get plain text with status 200. There is no strict JSON mode.
logit_bias and relativesRemoved.
tools, tool_choice, parallel_tool_calls, functions, function_callRemoved; the request goes on as a plain chat. There is no function calling.
chat_template_kwargsRemoved; the parameters of the dialogue template are set by the server.
stream_options.include_usageForced to true for streaming requests.

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

Three output guards are in place: internal-prompt leakage, degenerate repetition, and FX rates quoted without web data. Leakage and FX rates are cut short in streamed and plain answers alike, degenerate repetition in streams only.

Лимиты

Limits

ЧтоСколькоЧто при превышении
Токенов ответа в суткиStart — 300 000, Pro — 1 000 000, пробный — 20 000402 token_quota_exceeded
Запросов в суткиStart — 1 500, Pro — 6 000, пробный — 50402 api_quota_exceeded
Одновременных запросов на аккаунтStart — 1, Pro — 2, пробный — 1429 concurrent_request, Retry-After: 5
Генераций по всем ключам сразу1 — второе место у модели за веб-чатомочередь до 240 с, затем 503 model_busy
Запросов в минуту с адреса30, всплеск до 15429 rate_limit
Размер тела32 МБ413 payload_too_large
Ответ без потока600 секунд504 generation_timeout, без повтора; поток по времени не режется
Общий потолок сервиса на сутки — для всех ключей вместев токенах ответа503 capacity_exhausted до 00:00 UTC
WhatHow muchOn excess
Output tokens per dayStart — 300,000, Pro — 1,000,000, trial — 20,000402 token_quota_exceeded
Requests per dayStart — 1,500, Pro — 6,000, trial — 50402 api_quota_exceeded
Concurrent requests per accountStart — 1, Pro — 2, trial — 1429 concurrent_request, Retry-After: 5
Generations for all keys together1 — the model's other slot is the web chat'squeued up to 240 s, then 503 model_busy
Requests per minute per IP30, burst 15429 rate_limit
Body size32 MB413 payload_too_large
An answer without a stream600 seconds504 generation_timeout, not retried; streams are not cut on time
Service-wide daily ceiling — all keys togetherin output tokens503 capacity_exhausted until 00:00 UTC

Счётчики обнуляются в 00:00 UTC. Точное время сброса приходит заголовком, гадать не нужно. Лимит токенов проверяется перед запросом: запрос, который его перешагнёт, доработает до конца, отказ получит следующий. Поток, оборванный вашей стороной, тоже учитывается — по тому, сколько текста успело уйти.

Общий потолок защищает веб-чат: он работает на той же видеокарте, а лимиты всех тарифов вместе могут превысить то, что она выдаёт за сутки. Когда потолок выбран, запросы по ключам получают 503 capacity_exhausted до 00:00 UTC, даже если лимит вашего тарифа ещё не выбран. Повторять такой ответ раньше полуночи бессмысленно — см. Обработка отказов.

Counters reset at 00:00 UTC. The exact reset time comes back in a header, no guessing needed. The token limit is checked before a request: the request that crosses it runs to the end, the next one is refused. A stream you close early is counted too — by how much text had already gone out.

The service-wide ceiling protects the web chat: it runs on the same GPU, and the limits of all plans added together can exceed what the card produces in a day. Once the ceiling is reached, key requests get 503 capacity_exhausted until 00:00 UTC, even if your plan’s own limit is not spent. Retrying before midnight is pointless — see Handling refusals.

Заголовки состояния

State headers

ЗаголовокЗначение
X-GhostGPT-API-PlanТариф ключа: start, pro, legacy или trial
X-GhostGPT-Quota-LimitСколько запросов в сутки даёт тариф
X-GhostGPT-Quota-RemainingСколько запросов осталось прямо сейчас
X-GhostGPT-Token-LimitСколько токенов ответа в сутки даёт тариф
X-GhostGPT-Token-RemainingСколько токенов ответа осталось: в потоке — до этого запроса, без потока — уже за его вычетом
X-GhostGPT-Quota-ResetUnix-время обнуления счётчиков
X-GhostGPT-API-UntilUnix-время конца тарифа (у пробного лимита — конца подписки на чат). X-GhostGPT-Subscription-Until — то же значение под прежним именем
X-GhostGPT-Key-IdПубличный ярлык ключа
Warning: 199 ghostgpt "…"Тариф кончается меньше чем через 72 часа или уже кончился; после конца — какие лимиты действуют и до какого часа (UTC)
X-Request-IDИдентификатор запроса — назовите его в письме, и мы найдём вашу строку в журнале
HeaderMeaning
X-GhostGPT-API-PlanThe key’s plan: start, pro, legacy or trial
X-GhostGPT-Quota-LimitRequests a day the plan gives
X-GhostGPT-Quota-RemainingRequests left right now
X-GhostGPT-Token-LimitOutput tokens a day the plan gives
X-GhostGPT-Token-RemainingOutput tokens left: before this request on a stream, after it on a plain answer
X-GhostGPT-Quota-ResetUnix time when counters reset
X-GhostGPT-API-UntilUnix time when the plan ends (for the trial allowance, when the chat subscription ends). X-GhostGPT-Subscription-Until carries the same value under its old name
X-GhostGPT-Key-IdPublic label of the key
Warning: 199 ghostgpt "…"The plan ends in under 72 hours, or has ended; after the end, which limits apply and until what time (UTC)
X-Request-IDRequest identifier — quote it in an email and we will find your log line

Почему одновременных запросов мало. Модель обслуживает два запроса на весь сервис: один — всем ключам вместе, второй — веб-чату. Пул из десяти потоков всё равно получит ответы по одному, а остальные его запросы простоят в очереди. Ограничитель не «сколько в минуту» (это делает отдельный лимит по адресу), а «сколько прямо сейчас»; он один на аккаунт, на все процессы шлюза сразу.

Why so few requests at once. The model serves two requests for the entire service: one for all keys together, the other for the web chat. A ten-thread pool would still get its answers one at a time, with the rest of its requests waiting in line. This limiter is not about “per minute” (that is the separate per-IP limit) but about “right now”; it holds per account, across all gateway processes.

Квота занимается до обращения к модели и возвращается, если модель не ответила или поток лопнул, не отдав ни байта. Обрыв соединения вашей стороной возвратом не считается.

Quota is reserved before the model call and refunded if the model failed or the stream broke without a single byte. Your own disconnect is not a refund case.

Ошибки

Errors

Тело ошибки на /v1/* — JSON в формате OpenAI; на api.ghostgpt.io так отвечает и сам прокси (404, 413, 429, а пока шлюз перезапускается — 502, 503, 504), а на запасном ghostgpt.io/v1 ошибки прокси приходят его HTML-страницей. Вспомогательные ручки ghostgpt.io/api/* на собственные ошибки отвечают плоским {"error": "<code>"} (и на лимит частоты — {"error": "rate_limit"}), а отказ по ключу — 401, 402, 403 — приходит тем же телом в формате OpenAI и с теми же кодами, что на /v1.

Error bodies on /v1/* are JSON in the OpenAI format; on api.ghostgpt.io this includes the proxy’s own responses (404, 413, 429, and 502, 503, 504 while the gateway restarts), while on the legacy ghostgpt.io/v1 proxy errors come as its HTML page. The auxiliary endpoints on ghostgpt.io/api/* reply to their own errors with a flat {"error": "<code>"} (a rate limit included: {"error": "rate_limit"}), while a refusal by key — 401, 402, 403 — comes in the same OpenAI shape and with the same codes as on /v1.

{
  "error": {
    "message": "Human-readable explanation",
    "type": "insufficient_quota",
    "code": "api_plan_required",
    "plans_url": "https://ghostgpt.io/join-en.html?api=1",
    "request_id": "09ba82f5aa9ed61b"
  }
}
HTTPcodeЧто случилось и что делать
400invalid_request_bodyТело — не валидный JSON. Чаще всего большое вложение не догрузилось целиком: повторите или уменьшите файл.
400context_length_exceededДиалог длиннее окна контекста модели. В теле tokens_requested и context_window, если движок сообщил числа. Начните новый диалог или уберите старые сообщения.
400invalid_requestМодель не приняла запрос: в нём параметр или вложение, которых она не поддерживает. В message — причина, если в ней нет внутренних подробностей. Исправьте запрос: тот же самый не пройдёт и при повторе. Запрос из квоты не списан.
401unauthorizedЗаголовка Authorization нет вовсе или в нём нет схемы Bearer (например, ключ прислан без этого слова).
401invalid_api_keyКлюч не найден. Проверьте, что скопирован целиком, вместе с SK-.
401revoked_api_keyКлюч отозван — вами или перевыпуском. Получите новый.
401use_api_keyВ Authorization лежит старый токен входа GG-…. Нужен ключ SK-… со страницы ключа.
402api_plan_requiredНет API-тарифа (и 72 часа после него прошли), а подписки на чат с пробным лимитом тоже нет. В теле expired_at и plans_url — страница тарифов.
402api_quota_exceededВыбраны запросы тарифа на сегодня. В теле api_plan, daily_limit, reset_at.
402token_quota_exceededВыбраны токены тарифа на сегодня. В теле api_plan, daily_out_tokens, reset_at.
403account_blockedАккаунт заблокирован. Повторы не помогут — напишите нам.
404unknown_endpointТакой ручки нет. Список — в разделе «Эндпоинты».
413request_too_largeТело больше 32 МБ — ответ шлюза, с request_id. Уменьшите вложение или разбейте диалог.
413payload_too_largeТело больше 32 МБ — на api.ghostgpt.io его отрезает прокси ещё до шлюза, без request_id. Что делать — то же: уменьшить вложение или разбить диалог.
429rate_limitСлишком часто с одного адреса. Ждите Retry-After.
429concurrent_requestУ аккаунта уже идёт столько запросов, сколько разрешает тариф (поле limit). Дождитесь ответа, потом шлите следующий.
500internal_errorНеобработанная ошибка сервиса или сбой движка. Повторите запрос; если повторяется — пришлите X-Request-ID.
503model_loadingМодель поднимается или перезапущена сторожем. Повторить через 5 секунд.
503model_busyОчередь к модели не рассосалась за 240 секунд ожидания: модель или место ключей были заняты другими ответами. Запрос из квоты не списан. Повторить через Retry-After (15 секунд).
503capacity_exhaustedСервис исчерпал общую суточную ёмкость для API (в токенах ответа). Повторить после 00:00 UTC.
503service_unavailableСервис на мгновение не смог проверить доступ: его хранилище занято или перезапускается. Либо, на api.ghostgpt.io, прокси не достучался до шлюза — тогда без request_id и с HTTP 502, 503 или 504. Запрос из квоты не списан. Повторить через 5 секунд (Retry-After).
504generation_timeoutОтвет без потока не уложился в 600 секунд и оборван; сервис его не повторяет, сообщение не списывается. Тот же запрос займёт столько же — уменьшите max_tokens или включите stream: true. Заголовок x-should-retry: false не даёт официальным библиотекам OpenAI повторить его самим.
HTTPcodeWhat happened and what to do
400invalid_request_bodyThe body is not valid JSON. Usually a large attachment did not upload completely: retry or use a smaller file.
400context_length_exceededThe conversation is longer than the model’s context window. The body carries tokens_requested and context_window when the engine reported the numbers. Start a new chat or drop older messages.
400invalid_requestThe model would not take the request: it has a parameter or an input the model does not support. message gives the reason, unless it carried internal detail. Fix the request: the same one fails again on a retry. The request is not charged.
401unauthorizedNo Authorization header at all, or one without the Bearer scheme (for example, the key sent without that word).
401invalid_api_keyKey not found. Check it was copied whole, including SK-.
401revoked_api_keyThe key was revoked — by you or by a rotation. Issue a new one.
401use_api_keyAuthorization carries an old sign-in token GG-…. An SK-… key from the key page is required.
402api_plan_requiredNo API plan (and its 72 hours have passed), and no chat subscription with the trial allowance either. The body carries expired_at and plans_url, the plans page.
402api_quota_exceededThe plan’s requests for today are spent. The body carries api_plan, daily_limit, reset_at.
402token_quota_exceededThe plan’s output tokens for today are spent. The body carries api_plan, daily_out_tokens, reset_at.
403account_blockedThe account is blocked. Retrying will not help — contact us.
404unknown_endpointNo such endpoint. See the Endpoints section.
413request_too_largeBody over 32 MB, as answered by the gateway, with a request_id. Shrink the attachment or split the conversation.
413payload_too_largeBody over 32 MB, cut off by the proxy on api.ghostgpt.io before the gateway, with no request_id. Same remedy: shrink the attachment or split the conversation.
429rate_limitToo frequent from one address. Wait for Retry-After.
429concurrent_requestThe account already runs as many requests as its plan allows (the limit field). Wait for one to finish, then send the next.
500internal_errorUnhandled service error, or a failure in the engine. Retry the request; if it persists, send us the X-Request-ID.
503model_loadingThe model is starting or was restarted by the watchdog. Retry in 5 seconds.
503model_busyThe queue to the model did not clear within the 240-second wait: the model, or the keys' slot, was busy with other answers. The request is not charged to your quota. Retry after Retry-After (15 seconds).
503capacity_exhaustedThe service ran out of its overall daily API capacity (in output tokens). Retry after 00:00 UTC.
503service_unavailableFor a moment the service could not check access: its store was busy or restarting. Or, on api.ghostgpt.io, the proxy could not reach the gateway — then with no request_id and with HTTP 502, 503 or 504. The request is not charged. Retry in 5 seconds (Retry-After).
504generation_timeoutAn answer without a stream did not finish within 600 seconds and was cut off; the service does not run it again, and the message is not charged. The same request would take as long — lower max_tokens or send stream: true. The header x-should-retry: false keeps the official OpenAI libraries from retrying it on their own.

Чего API не умеет

What the API does not do

Здесь честнее сказать сразу, чем оставить это на первый день интеграции.

Better said upfront than discovered on day one of your integration.

Вспомогательные ручки (ghostgpt.io)

Auxiliary endpoints (ghostgpt.io)

Это не часть OpenAI-совместимого /v1. Они живут на основном домене, принимают тот же ключ и требуют API-тарифа (или оплаченной подписки на чат с пробным лимитом). Лимиты тарифа не тратят, но у каждой свой предел частоты.

These are not part of the OpenAI-compatible /v1. They live on the main domain, accept the same key and require an API plan (or a paid chat subscription with the trial allowance). They do not spend the plan’s limits, but each has its own rate limit.

ПутьЧто делаетВ минуту
POST /api/fetch-urlСкачивает страницу и отдаёт текст (до 80 000 символов), заголовок, описание, иконку40
POST /api/web-researchПодбирает источники по вопросу: курсы валют, погода25
POST /api/pdf/extractТекст из PDF (до 50 МБ, до 400 страниц)60
POST /api/transcribeРаспознавание речи (до 25 МБ и 30 минут звука, модель whisper small)8
POST /api/shareПубличная ссылка на диалог (до 2 МБ)30
GET /api/share/{id}Снимок диалога — публично, без ключа30
PathWhat it doesPer minute
POST /api/fetch-urlFetches a page and returns text (up to 80,000 chars), title, description, favicon40
POST /api/web-researchPicks sources for a query: FX rates, weather25
POST /api/pdf/extractText from PDF (up to 50 MB, 400 pages)60
POST /api/transcribeSpeech recognition (up to 25 MB and 30 minutes of audio, whisper small)8
POST /api/sharePublic link to a conversation (up to 2 MB)30
GET /api/share/{id}Conversation snapshot — public, no key30

Отказ по ключу здесь тот же, что на /v1: 401 invalid_api_key, revoked_api_key или use_api_key, 402 api_plan_required, 403 account_blocked — в формате OpenAI. Остальные ошибки — плоский {"error": "<code>"}; превышение частоты — 429 {"error": "rate_limit"} с Retry-After. Разбор PDF идёт в несколько мест на весь сервис: если все заняты дольше 20 секунд, /api/pdf/extract отвечает 429 {"error": "busy"} с Retry-After; так же отвечает /api/transcribe, пока занято распознавание.

A refusal by key is the same as on /v1: 401 invalid_api_key, revoked_api_key or use_api_key, 402 api_plan_required, 403 account_blocked, in the OpenAI shape. Other errors are a flat {"error": "<code>"}; a rate limit is 429 {"error": "rate_limit"} with Retry-After. PDF extraction runs in a few slots for the whole service: when all of them stay taken for more than 20 seconds, /api/pdf/extract answers 429 {"error": "busy"} with Retry-After; /api/transcribe answers the same way while speech recognition is taken.

curl -X POST https://ghostgpt.io/api/fetch-url \
  -H "Authorization: Bearer SK-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com"}'

Модель сама курсы валют не называет: и она, и сторож на выходе принимают курс только из блока «Данные с сайта» в сообщениях. Если вам нужны курсы, вызовите /api/web-research и допишите поле context из ответа в конец сообщения пользователя как есть — это тот же блок, что подставляет чат. Пустой context значит, что ни один источник не ответил. Свои данные передавайте так же — блоком между такими строками:

The model will not quote FX rates by itself: both the model and an output guard take a rate only from a «Данные с сайта» (site data) block in the messages. If you need rates, call /api/web-research and append the context field of its answer to the end of the user message as is — it is the same block the web chat adds. An empty context means no source answered. Pass your own data the same way, in a block between these lines:

--- Данные с сайта ---
USD: 81.5 RUB за 1 USD
--- конец ---

Приватность

Privacy

Вопросы

FAQ

Ключ перестал работать посреди дня — почему?

The key stopped working mid-day — why?

Посмотрите code в теле ответа. token_quota_exceeded или api_quota_exceeded — выбраны лимиты тарифа на сегодня, сбросятся в 00:00 UTC (остаток видно заранее в X-GhostGPT-Token-Remaining и X-GhostGPT-Quota-Remaining). api_plan_required — кончился тариф. revoked_api_key — ключ перевыпущен, и где-то работает старая копия.

Check code in the response body. token_quota_exceeded or api_quota_exceeded — the plan’s limits for today are spent and reset at 00:00 UTC (the remainder is visible in advance in X-GhostGPT-Token-Remaining and X-GhostGPT-Quota-Remaining). api_plan_required — the plan ended. revoked_api_key — the key was rotated and an old copy is still deployed somewhere.

Можно один ключ на команду?

Can a team share one key?

Технически да, но лимиты одни на аккаунт, а открытых запросов сразу — столько, сколько даёт тариф (Start — 1, Pro — 2); отвечает модель всем ключам по одному. Для независимых нагрузок дешевле Pro или два аккаунта, чем очередь из 429.

Technically yes, but the limits are per account, and an account may have as many requests open at once as its plan gives (Start 1, Pro 2); the model answers all keys one at a time. For independent workloads, Pro or two accounts are cheaper than a queue of 429s.

Как проверить ключ, не тратя квоту?

How do I verify a key without spending quota?

GET /v1/models. Она не тратит ничего и никогда не отвечает 402; заодно вернёт заголовки с тарифом, остатком лимитов и сроком тарифа.

GET /v1/models. It costs nothing and never returns 402; it also brings back headers with the plan, the remaining limits and the plan’s end.

Ответы иногда обрываются на середине

Answers sometimes cut off mid-sentence

Если finish_reason: "length" — упёрлись в max_tokens или сработал сторож повторов. Если "stop" и текст короткий — сработал сторож на утечку промпта или на курсы валют без данных.

With finish_reason: "length" you hit max_tokens or the repetition guard. With "stop" and a short text, the prompt-leak or FX guard fired.

Работает ли OpenAI SDK без правок?

Does the OpenAI SDK work unchanged?

Да. Достаточно подменить base_url и api_key. Модель называйте ghostgpt — впрочем, любое имя всё равно будет переписано.

Yes. Just swap base_url and api_key. Use ghostgpt as the model name — although any name gets rewritten anyway.

Что будет с интеграцией, если я забуду продлить?

What happens to my integration if I forget to renew?

72 часа она проживёт с заголовком Warning: до конца суток (UTC), в которые кончился тариф, — на его лимитах, дальше на пробном. За трое суток до конца тарифа тот же заголовок приходит заранее — повесьте на него алерт, и сюрприза не будет.

It survives 72 hours with a Warning header: on the plan’s limits until the end of the UTC day it ended, then on the trial allowance. The same header appears three days before the plan ends — hook an alert to it and there will be no surprise.

Куда писать, если что-то сломалось?

Where do I report a problem?

Через ghostgpt.io. Приложите X-Request-ID и key_id — этого хватит, чтобы найти вашу строку. Сам ключ присылать не нужно и не следует.

Via ghostgpt.io. Include X-Request-ID and key_id — that is enough to find your log line. Do not send the key itself.