Створення chat completion
Використовуйте CometAPI POST /v1/chat/completions для надсилання багатоповідомленнєвих розмов до чат-моделей зі Streaming, структурованим виводом і викликом інструментів.
base_url="https://api.cometapi.com/v1" і вашого ключа API CometAPI.
У базовому прикладі, а також прикладах із зображеннями, Streaming і структурованим виводом використовується gpt-6-astra. У прикладі Function Calling використовується gpt-5.6-sol, а в прикладі з імовірностями журналу — gpt-4.1.
Ролі повідомлень
Надсилання multimodal input
Використовуйте масив частин вмісту, щоб надіслати зображення разом із текстом:image_url.detail для вибору рівня деталізації обробки зображення. У цьому прикладі використовується high.
Потокові відповіді
Щоб отримувати вивід поступово, установітьstream у значення true. Відповідь надсилається у форматі Server-Sent Events (SSE)). Текст надходить в об’єктах chat.completion.chunk; цей скорочений приклад містить фінальний чанк використання:
Запит структурованого виводу
Використовуйтеresponse_format, щоб запросити структурований вивід:
Виклик інструментів і функцій
Використовуйтеgpt-5.6-sol із визначенням функції:
finish_reason: "tool_calls" і масив message.tool_calls. Розберіть JSON-кодований arguments функції, виконайте свою функцію, а потім додайте повідомлення асистента та повідомлення з результатом tool із відповідним tool_call_id.
Вибір параметрів запиту
Параметри для конкретних моделей
Параметри для конкретних моделей
reasoning_effort і max_completion_tokens з GPT-6 Astra. Приклади Functions і Logprobs показують параметри запиту для gpt-5.6-sol і gpt-4.1 відповідно.Відомості про формати запитів, специфічні для Claude або Gemini, див. в Anthropic Messages і Gemini Generate content.max_tokens і max_completion_tokens
max_tokens і max_completion_tokens
max_completion_tokens, щоб обмежити кількість згенерованих tokens у прикладах GPT-6 Astra. Це включає міркування та видимий результат, тож залиште місце для обох. max_tokens — застарілий параметр.Ролі інструкцій
Ролі інструкцій
developer для інструкцій застосунку в прикладах GPT-6 Astra. Зберігайте вміст кінцевого користувача в повідомленнях user і зберігайте попередні відповіді асистента під час продовження розмови.Поширені запитання
Як працювати з обмеженнями швидкості?
У разі виникнення429 Too Many Requests реалізуйте експоненційну затримку між повторними спробами:
Як підтримувати контекст розмови?
Додайте всю історію розмови до масивуmessages:
Що означає finish_reason ?
Як контролювати витрати?
- Використовуйте
max_completion_tokens, щоб обмежити довжину виводу. - Порівняйте ціни на моделі та виберіть модель, що відповідає вимогам вашого робочого навантаження.
- Зберігайте Prompt лаконічними — уникайте надлишкового контексту.
- Відстежуйте використання токенів у полі відповіді
usage.
Авторизації
Bearer token authentication. Use your CometAPI key.
Тіло
Model ID to use for this request. See the Models page for current options.
"gpt-6-astra"
Conversation messages, including instructions, user input, assistant replies, and tool results.
If true, partial response tokens are delivered incrementally via server-sent events (SSE). The stream ends with a data: [DONE] message.
Sampling temperature. Omit this field for GPT-6 Astra.
0 <= x <= 2Nucleus sampling threshold. Omit this field for GPT-6 Astra. For sampling overrides, adjust either top_p or temperature.
0 <= x <= 1Number of completion choices to generate for each input message. Defaults to 1.
Stop string or list of up to four strings, for models that support stop sequences.
Legacy output-token limit. Use max_completion_tokens for the GPT-6 Astra examples.
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.
Maximum generated tokens, including visible output and reasoning. Leave enough room for both, as in the image-input example.
Specifies the output format. Use {"type": "json_object"} for JSON mode, or {"type": "json_schema", "json_schema": {...}} for strict structured output.
Function definitions for a model that supports tool calling on Chat Completions. The function example uses GPT-5.6 Sol; use Responses for GPT-6 Astra tool calls.
Controls how the model selects tools. auto (default): model decides. none: no tools. required: must call a tool.
Return token log probabilities. Use gpt-4.1 as shown in the Logprobs example.
Number of most likely tokens to return at each position (0-20). Requires logprobs to be true.
0 <= x <= 20Reasoning effort supported by the selected model. The GPT-6 Astra examples use low; the GPT-5.6 Sol function example uses none. See the model reference for other supported levels.
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_example"
Object type. Non-streaming responses use chat.completion.
chat.completion "chat.completion"
Unix timestamp of creation.
1788763703
The model used (may include version suffix).
"gpt-6-astra"
Array of completion choices.
Token accounting for this request. Billing uses these counts.
Service tier that processed the request, when returned.
Model configuration fingerprint, when returned.