Chat Completions
Використовуйте CometAPI POST /v1/chat/completions, щоб надсилати розмови з кількох повідомлень і отримувати відповіді LLM із керуванням streaming, temperature і max_tokens.
CometAPI маршрутизує Chat Completions до кількох провайдерів — зокрема OpenAI, Claude і Gemini — через єдиний OpenAI-compatible інтерфейс. Перемикайтеся між моделями, змінюючи параметр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-compatible SDK працюють, якщо встановити base_url на https://api.cometapi.com/v1.
Ролі повідомлень
| Role | Description |
|---|---|
system | Визначає поведінку та стиль асистента. Розміщується на початку розмови. |
developer | Замінює system для новіших моделей (o1+). Надає інструкції, яких модель має дотримуватися незалежно від введення користувача. |
user | Повідомлення від кінцевого користувача. |
assistant | Попередні відповіді моделі, що використовуються для збереження історії розмови. |
tool | Результати викликів tool/function. Має містити tool_call_id, що відповідає початковому виклику tool. |
Надсилання multimodal input
Багато моделей підтримують зображення й аудіо разом із текстом. Щоб надсилати multimodal-повідомлення, використовуйте формат масиву дляcontent:
detail керує глибиною аналізу зображення:
low— швидше, використовує менше tokens (фіксована вартість)high— детальний аналіз, споживається більше tokensauto— модель вирішує сама (за замовчуванням)
Streaming відповідей
Щоб отримувати інкрементальний вивід, установіть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.
Примітки щодо роботи з різними провайдерами
Підтримка параметрів у різних провайдерів
Підтримка параметрів у різних провайдерів
| Параметр | OpenAI GPT | Claude (через compat) | Gemini (через 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 role
system vs developer role
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 sequence. |
length | Досягнуто ліміту max_tokens або max_completion_tokens. |
tool_calls | Модель викликала один або кілька викликів tool/function. |
content_filter | Вивід було відфільтровано через політику щодо контенту. |
Як контролювати витрати?
- Використовуйте
max_completion_tokens, щоб обмежити довжину виводу. - Обирайте економічно ефективні моделі (наприклад,
gpt-5.4-miniабоgpt-5.4-nanoдля простіших завдань). - Пишіть Prompt лаконічно — уникайте надлишкового контексту.
- Відстежуйте використання token у полі відповіді
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"