Skip to main content

Справочник Gonka API

Полный справочник API GonkaGate. OpenAI-совместимые эндпоинты с документацией параметров.

К быстрому старту

Base URL

Все API запросы должны отправляться на:

https://api.gonkagate.com/v1
Попробовать в Playground

Аутентификация

Авторизуйте API запросы с помощью Bearer токена в заголовке Authorization.

HTTP Header
Authorization: Bearer YOUR_API_KEY

Эндпоинты

Создать Chat Completion

POST/chat/completions

Создаёт ответ для чат-диалога.

Тело запроса

model
Тип
string
Обязателен
Да
По умолчанию
Описание
Model ID (e.g., Qwen/Qwen3-32B-FP8)
messages
Тип
array
Обязателен
Да
По умолчанию
Описание
Array of message objects with role and content
stream
Тип
boolean
Обязателен
Нет
По умолчанию
false
Описание
Enable streaming responses
temperature
Тип
number
Обязателен
Нет
По умолчанию
1.0
Описание
Sampling temperature (0-2)
max_tokens
Тип
integer
Обязателен
Нет
По умолчанию
4096
Описание
Maximum tokens in response
top_p
Тип
number
Обязателен
Нет
По умолчанию
1.0
Описание
Nucleus sampling threshold
stop
Тип
string | array
Обязателен
Нет
По умолчанию
null
Описание
Stop sequences

Ответ

json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1735500000,
  "model": "Qwen/Qwen3-32B-FP8",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 10,
    "total_tokens": 35,
    "base_cost_usd": 0.000175,
    "platform_fee_usd": 0.0000175,
    "total_cost_usd": 0.0001925
  }
}

Примеры кода

chat_completions.py
from openai import OpenAI

client = OpenAI(
    base_url="https://api.gonkagate.com/v1",
    api_key="your-gonkagate-api-key"
)

response = client.chat.completions.create(
    model="Qwen/Qwen3-32B-FP8",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ],
    temperature=0.7,
    max_tokens=1000
)

print(response.choices[0].message.content)
print(f"Usage: {response.usage.total_tokens} tokens")

Список моделей

GET/models

Возвращает список доступных моделей.

Ответ

json
{
  "data": [
    {
      "id": "Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
      "name": "Qwen3 235B A22B Instruct 2507 FP8",
      "description": "A powerful 235B parameter model for complex reasoning tasks.",
      "context_length": 131072,
      "pricing": {
        "prompt": "0.000000350",
        "completion": "0.000000350"
      }
    },
    {
      "id": "Qwen/QwQ-32B",
      "name": "QwQ 32B",
      "description": "Compact reasoning model with strong logic capabilities.",
      "context_length": 32768,
      "pricing": {
        "prompt": "0.000000580",
        "completion": "0.000000580"
      }
    }
  ]
}

Примеры кода

list_models.py
import requests

response = requests.get(
    "https://api.gonkagate.com/v1/models",
    headers={"Authorization": "Bearer your-gonkagate-api-key"}
)

models = response.json()["data"]

for model in models:
    price_per_m = float(model["pricing"]["prompt"]) * 1_000_000
    print(f"{model['name']}: ${price_per_m:.2f}/1M tokens")

Смотреть список моделей

Параметры

Полный справочник параметров запроса.

Совместимость с OpenAI

GonkaGate поддерживает все стандартные параметры OpenAI Chat Completions. Справочник OpenAI API
model
Тип
string
Обязателен
Да
По умолчанию
Описание

Model ID to use for completion

The model ID specifies which Gonka Network model to use. Example: `Qwen/Qwen3-32B-FP8`.

messages
Тип
array
Обязателен
Да
По умолчанию
Описание

Array of message objects with `role` and `content`

A list of messages comprising the conversation. Each message has a `role` (system, user, assistant, or tool) and `content`. See Messages Schema below for full structure.

stream
Тип
boolean
Обязателен
Нет
По умолчанию
false
Описание

Enable streaming responses

If true, partial message deltas are sent as Server-Sent Events (SSE). Tokens are sent as they become available.

max_tokens
Тип
integer
Обязателен
Нет
По умолчанию
4096
Описание

Maximum tokens in response

The maximum number of tokens to generate. The model will stop when this limit is reached.

Ограничения: 1 to context window size

Схема массива messages

Схема массива messages

Структура параметра messages. Каждое сообщение — объект с role и content.

role
Тип
string
Обязательно
Да
Описание

The role of the message author

Допустимые значения: system, user, assistant, developer

content
Тип
string | null
Обязательно
Да
Описание

The message content. Can be null for assistant messages with tool_calls.

name
Тип
string
Обязательно
Нет
Описание

Optional name for the participant. Useful for multi-agent conversations.

tool_calls
Тип
array
Обязательно
Нет
Описание

Tool calls made by the assistant. Only present in assistant messages.

tool_call_id
Тип
string
Обязательно
Нет
Описание

ID of the tool call this message is responding to. Required for tool role.

Примеры
json
[
  {
    "role": "user",
    "content": "Hello!"
  }
]

Схемы ответов

Структура API ответов.

Ответ Chat Completion

Ответ Chat Completion

ПолеТипОписание
idstringUnique identifier for the completion
objectstringAlways "chat.completion"
createdintegerUnix timestamp when created
modelstringModel used for the completion
choicesarrayArray of completion choices
indexintegerIndex of this choice
messageobjectThe generated message
rolestringAlways "assistant"
contentstring | nullThe generated text
tool_callsarrayTool calls (if any)
finish_reasonstring"stop", "length", "tool_calls", or "content_filter"
usageobjectToken usage and cost statistics
prompt_tokensintegerTokens in the input prompt
completion_tokensintegerTokens in the response
total_tokensintegerTotal tokens used
base_cost_usdnumberBase cost before platform fee (USD)
platform_fee_usdnumberPlatform fee — 10% of base cost (USD)
total_cost_usdnumberTotal cost deducted from balance (USD)
json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1735500000,
  "model": "Qwen/Qwen3-32B-FP8",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 10,
    "total_tokens": 35,
    "base_cost_usd": 0.000175,
    "platform_fee_usd": 0.0000175,
    "total_cost_usd": 0.0001925
  }
}

Streaming ответ

При stream: true ответы отправляются как Server-Sent Events (SSE).

Формат чанка

ПолеТипОписание
idstringSame ID for all chunks in a stream
objectstringAlways "chat.completion.chunk"
createdintegerUnix timestamp
modelstringModel used
choicesarrayArray with incremental content
indexintegerChoice index
deltaobjectIncremental content
rolestringRole (first chunk only)
contentstringText content to append
finish_reasonstring | nullnull until final chunk, then "stop"
usageobject | undefinedToken usage and cost (only in final chunk before [DONE])
prompt_tokensintegerTokens in the input prompt
completion_tokensintegerTokens in the response
total_tokensintegerTotal tokens used
base_cost_usdnumberBase cost before platform fee (USD)
platform_fee_usdnumberPlatform fee — 10% of base cost (USD)
total_cost_usdnumberTotal cost deducted from balance (USD)
json
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1735500000,"model":"Qwen/Qwen3-32B-FP8","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1735500000,"model":"Qwen/Qwen3-32B-FP8","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1735500000,"model":"Qwen/Qwen3-32B-FP8","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","created":1735500000,"model":"Qwen/Qwen3-32B-FP8","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"base_cost_usd":0.000075,"platform_fee_usd":0.0000075,"total_cost_usd":0.0000825}}

data: [DONE]

Ответ списка моделей

Ответ списка моделей

ПолеТипОписание
dataarrayArray of model objects
idstringModel identifier for API requests
namestringHuman-readable model name
descriptionstring | nullModel description (from HuggingFace)
context_lengthnumber | nullMaximum context window in tokens
pricingobjectCost per token in USD
promptstringCost per input token in USD
completionstringCost per output token in USD
json
{
  "data": [
    {
      "id": "Qwen/Qwen3-235B-A22B-Instruct-2507-FP8",
      "name": "Qwen3 235B A22B Instruct 2507 FP8",
      "description": "A powerful 235B parameter model for complex reasoning tasks.",
      "context_length": 131072,
      "pricing": {
        "prompt": "0.000000350",
        "completion": "0.000000350"
      }
    },
    {
      "id": "Qwen/QwQ-32B",
      "name": "QwQ 32B",
      "description": "Compact reasoning model with strong logic capabilities.",
      "context_length": 32768,
      "pricing": {
        "prompt": "0.000000580",
        "completion": "0.000000580"
      }
    }
  ]
}

Коды ошибок

GonkaGate использует стандартные HTTP коды и OpenAI-совместимые ответы об ошибках. Нажмите на ошибку, чтобы увидеть причины, решения и пример ответа.

HTTP коды статусов

Все возможные ответы об ошибках API с их значениями.

Обработка ошибок

Реализуйте логику повторных попыток с экспоненциальной задержкой для rate limits и серверных ошибок. Клиентские ошибки (4xx кроме 429) повторять не нужно.

error_handling.py
import openai
import time

client = openai.OpenAI(
    api_key="your-gonkagate-api-key",
    base_url="https://api.gonkagate.com/v1"
)

def chat_with_retry(messages, max_retries=3):
    """Make API request with exponential backoff retry logic."""
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="Qwen/Qwen3-32B-FP8",
                messages=messages
            )
            return response.choices[0].message.content

        except openai.RateLimitError as e:
            # 429: Wait and retry with exponential backoff
            wait_time = 2 ** attempt
            print(f"Rate limited. Waiting {wait_time}s...")
            time.sleep(wait_time)

        except openai.AuthenticationError as e:
            # 401: Invalid API key - don't retry
            print(f"Auth error: {e.message}")
            raise

        except openai.BadRequestError as e:
            # 400: Invalid request - don't retry
            print(f"Bad request: {e.message}")
            raise

        except openai.APIStatusError as e:
            # 5xx: Server error - retry with backoff
            if e.status_code >= 500:
                wait_time = 2 ** attempt
                print(f"Server error {e.status_code}. Retrying in {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise

    raise Exception("Max retries exceeded")

# Usage
result = chat_with_retry([{"role": "user", "content": "Hello!"}])
print(result)

Лимиты запросов

Лимиты API применяются на IP-адрес для обеспечения справедливого использования.

ЛимитЗначениеОбласть
Запросов в минуту100На IP
Токенов в минуту100,000На IP
Запросов в день10,000На IP

При превышении лимита проверьте заголовок Retry-After для времени ожидания. Реализуйте экспоненциальную задержку для повторных попыток.

Предупреждение о низком балансе

Когда ваш баланс опускается ниже $5, вы увидите предупреждение в Dashboard. Рекомендуем пополнить баланс, чтобы избежать прерывания сервиса.

Была ли эта страница полезной?