Chat Completions
Use o CometAPI POST /v1/chat/completions para enviar conversas com múltiplas mensagens e obter respostas de LLM com controles de streaming, temperature e max_tokens.
O CometAPI encaminha Chat Completions para vários provedores — incluindo OpenAI, Claude e Gemini — por meio de uma única interface compatível com OpenAI. Alterne entre modelos mudando o parâmetroDocumentation 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; a maioria dos SDKs compatíveis com OpenAI funciona ao definir base_url como https://api.cometapi.com/v1.
Papéis de mensagem
| Role | Description |
|---|---|
system | Define o comportamento e a personalidade do assistente. Fica no início da conversa. |
developer | Substitui system nos modelos mais novos (o1+). Fornece instruções que o modelo deve seguir independentemente da entrada do usuário. |
user | Mensagens do usuário final. |
assistant | Respostas anteriores do modelo, usadas para manter o histórico da conversa. |
tool | Resultados de chamadas de tool/function. Deve incluir tool_call_id correspondente à chamada de tool original. |
Enviar entrada multimodal
Muitos modelos oferecem suporte a imagens e áudio junto com texto. Para enviar mensagens multimodais, use o formato de array paracontent:
detail controla a profundidade da análise da imagem:
low— mais rápido, usa menos tokens (custo fixo)high— análise detalhada, mais tokens consumidosauto— o modelo decide (padrão)
Transmitir respostas por Streaming
Para receber saída incremental, definastream como true. A resposta é entregue como Server-Sent Events (SSE), em que cada evento contém um objeto chat.completion.chunk:
Solicitar saída estruturada
Para forçar o modelo a retornar JSON válido que corresponda a um schema específico, useresponse_format:
json_schema) garante que a saída corresponda exatamente ao seu schema. O modo JSON Object (json_object) garante apenas JSON válido — a estrutura não é imposta.Chamar tools e functions
Para permitir que o modelo chame funções externas, forneça definições de tools:finish_reason: "tool_calls" e o array message.tool_calls conterá o nome da função e os argumentos. Em seguida, você executa a função e envia o resultado de volta como uma mensagem tool com o tool_call_id correspondente.
Observações entre provedores
Parameter support across providers
Parameter support across providers
| 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 | apenas 1 | 1–8 |
stop | Até 4 | Até 4 | Até 5 |
tools | ✅ | ✅ | ✅ |
response_format | ✅ | ✅ (json_schema) | ✅ |
logprobs | ✅ | ❌ | ❌ |
reasoning_effort | série o, GPT-5.1+ | ❌ | ❌ (use thinking para Gemini nativo) |
max_tokens vs max_completion_tokens
max_tokens vs max_completion_tokens
max_tokens— O parâmetro legado. Funciona com a maioria dos modelos, mas está obsoleto para os modelos OpenAI mais novos.max_completion_tokens— O parâmetro recomendado para GPT-4.1, série GPT-5 e modelos da série o. Obrigatório para modelos de raciocínio, pois inclui tanto tokens de saída quanto tokens de raciocínio.
system vs developer role
system vs developer role
system— O papel tradicional de instrução. Funciona com todos os modelos.developer— Introduzido com os modelos o1. Fornece um seguimento de instruções mais forte para modelos mais novos. Recorre ao comportamento desystemem modelos mais antigos.
developer em novos projetos voltados para GPT-4.1+ ou modelos da série o.FAQ
Como lidar com rate limits?
Ao encontrar429 Too Many Requests, implemente exponential backoff:
Como manter o contexto da conversa?
Inclua o histórico completo da conversa no arraymessages:
O que finish_reason significa?
| Value | Meaning |
|---|---|
stop | Conclusão natural ou atingiu uma sequência de parada. |
length | Atingiu o limite de max_tokens ou max_completion_tokens. |
tool_calls | O modelo invocou uma ou mais chamadas de tool/function. |
content_filter | A saída foi filtrada devido à política de conteúdo. |
Como controlar custos?
- Use
max_completion_tokenspara limitar o comprimento da saída. - Escolha modelos com bom custo-benefício (por exemplo,
gpt-5.4-miniougpt-5.4-nanopara tarefas mais simples). - Mantenha os prompts concisos — evite contexto redundante.
- Monitore o uso de tokens no campo de resposta
usage.
Autorizações
Bearer token authentication. Use your CometAPI key.
Corpo
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 Resposta
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"