Chat Completions
Используйте CometAPI POST /v1/chat/completions, чтобы отправлять разговоры из нескольких сообщений и получать ответы LLM с управлением streaming, temperature и max_tokens.
CometAPI направляет Chat Completions к нескольким провайдерам — включая OpenAI, Claude и Gemini — через единый OpenAI-совместимый интерфейс. Переключайтесь между моделями, изменяя параметрDocumentation Index
Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
Use this file to discover all available pages before exploring further.
model; большинство OpenAI-совместимых SDK работают при установке base_url в https://api.cometapi.com/v1.
Роли сообщений
| Role | Description |
|---|---|
system | Задает поведение и стиль assistant. Размещается в начале разговора. |
developer | Заменяет system для более новых моделей (o1+). Предоставляет инструкции, которым модель должна следовать независимо от ввода пользователя. |
user | Сообщения от конечного пользователя. |
assistant | Предыдущие ответы модели, используются для сохранения истории разговора. |
tool | Результаты вызовов tool/function. Должны включать tool_call_id, соответствующий исходному вызову tool. |
Отправка multimodal-ввода
Многие модели поддерживают изображения и аудио наряду с текстом. Чтобы отправлять multimodal-сообщения, используйте формат массива дляcontent:
detail управляет глубиной анализа изображения:
low— быстрее, использует меньше tokens (фиксированная стоимость)high— подробный анализ, расходуется больше tokensauto— модель решает сама (по умолчанию)
Потоковые ответы
Чтобы получать вывод по мере генерации, установитеstream в true. Ответ доставляется как Server-Sent Events (SSE), где каждое событие содержит объект chat.completion.chunk:
Запрос структурированного вывода
Чтобы заставить модель вернуть корректный JSON, соответствующий определенной схеме, используйтеresponse_format:
json_schema) гарантирует, что вывод точно соответствует вашей схеме. Режим JSON Object (json_object) гарантирует только корректный JSON — структура не проверяется.Вызов tools и functions
Чтобы позволить модели вызывать внешние функции, передайте определения tool:finish_reason: "tool_calls", а массив message.tool_calls будет содержать имя функции и аргументы. Затем вы выполняете функцию и отправляете результат обратно как сообщение tool с соответствующим tool_call_id.
Примечания по кросс-провайдерной совместимости
Поддержка параметров у разных провайдеров
Поддержка параметров у разных провайдеров
| Parameter | OpenAI GPT | Claude (via compat) | Gemini (via compat) |
|---|---|---|---|
temperature | 0–2 | 0–1 | 0–2 |
top_p | 0–1 | 0–1 | 0–1 |
n | 1–128 | Только 1 | 1–8 |
stop | До 4 | До 4 | До 5 |
tools | ✅ | ✅ | ✅ |
response_format | ✅ | ✅ (json_schema) | ✅ |
logprobs | ✅ | ❌ | ❌ |
reasoning_effort | o-series, GPT-5.1+ | ❌ | ❌ (используйте thinking для нативного Gemini) |
max_tokens vs max_completion_tokens
max_tokens vs max_completion_tokens
max_tokens— Устаревший параметр. Работает с большинством моделей, но считается deprecated для более новых моделей OpenAI.max_completion_tokens— Рекомендуемый параметр для моделей GPT-4.1, серии GPT-5 и моделей o-series. Обязателен для reasoning-моделей, так как включает и output tokens, и reasoning tokens.
Роль system vs developer
Роль system vs developer
system— Традиционная роль для инструкций. Работает со всеми моделями.developer— Представлена в моделях o1. Обеспечивает более строгое следование инструкциям в новых моделях. Для старых моделей откатывается к поведениюsystem.
developer для новых проектов, ориентированных на модели GPT-4.1+ или o-series.FAQ
Как обрабатывать rate limits?
При возникновении429 Too Many Requests реализуйте экспоненциальный backoff:
Как поддерживать контекст разговора?
Включайте полную историю разговора в массивmessages:
Что означает finish_reason?
| Value | Meaning |
|---|---|
stop | Естественное завершение или срабатывание stop-последовательности. |
length | Достигнут лимит max_tokens или max_completion_tokens. |
tool_calls | Модель вызвала один или несколько вызовов tool/function. |
content_filter | Вывод был отфильтрован из-за политики контента. |
Как контролировать стоимость?
- Используйте
max_completion_tokens, чтобы ограничить длину вывода. - Выбирайте экономичные модели (например,
gpt-5.4-miniилиgpt-5.4-nanoдля более простых задач). - Делайте prompts краткими — избегайте избыточного контекста.
- Отслеживайте использование tokens в поле ответа
usage.
Авторизации
Bearer token authentication. Use your CometAPI key.
Тело
Model ID to use for this request. See the Models page for current options.
"gpt-4.1"
A list of messages forming the conversation. Each message has a role (system, user, assistant, or developer) and content (text string or multimodal content array).
If true, partial response tokens are delivered incrementally via server-sent events (SSE). The stream ends with a data: [DONE] message.
Sampling temperature between 0 and 2. Higher values (e.g., 0.8) produce more random output; lower values (e.g., 0.2) make output more focused and deterministic. Recommended to adjust this or top_p, but not both.
0 <= x <= 2Nucleus sampling parameter. The model considers only the tokens whose cumulative probability reaches top_p. For example, 0.1 means only the top 10% probability tokens are considered. Recommended to adjust this or temperature, but not both.
0 <= x <= 1Number of completion choices to generate for each input message. Defaults to 1.
Up to 4 sequences where the API will stop generating further tokens. Can be a string or an array of strings.
Maximum number of tokens to generate in the completion. The total of input + output tokens is capped by the model's context length.
Number between -2.0 and 2.0. Positive values penalize tokens based on whether they have already appeared, encouraging the model to explore new topics.
-2 <= x <= 2Number between -2.0 and 2.0. Positive values penalize tokens proportionally to how often they have appeared, reducing verbatim repetition.
-2 <= x <= 2A JSON object mapping token IDs to bias values from -100 to 100. The bias is added to the model's logits before sampling. Values between -1 and 1 subtly adjust likelihood; -100 or 100 effectively ban or force selection of a token.
A unique identifier for your end-user. Helps with abuse detection and monitoring.
An upper bound for the number of tokens to generate, including visible output tokens and reasoning tokens. Use this instead of max_tokens for GPT-4.1+, GPT-5 series, and o-series models.
Specifies the output format. Use {"type": "json_object"} for JSON mode, or {"type": "json_schema", "json_schema": {...}} for strict structured output.
A list of tools the model may call. Currently supports function type tools.
Controls how the model selects tools. auto (default): model decides. none: no tools. required: must call a tool.
Whether to return log probabilities of the output tokens.
Number of most likely tokens to return at each position (0-20). Requires logprobs to be true.
0 <= x <= 20Controls the reasoning effort for o-series and GPT-5.1+ models.
low, medium, high Options for streaming. Only valid when stream is true.
Specifies the processing tier.
auto, default, flex, priority Ответ
Successful chat completion response.
Unique completion identifier.
"chatcmpl-abc123"
chat.completion "chat.completion"
Unix timestamp of creation.
1774412483
The model used (may include version suffix).
"gpt-5.4-2025-07-16"
Array of completion choices.
"default"
"fp_490a4ad033"