Chat Completions
Usa CometAPI POST /v1/chat/completions para enviar conversaciones de múltiples mensajes y obtener respuestas de LLM con controles de streaming, temperature y max_tokens.
CometAPI enruta Chat Completions a múltiples proveedores — incluidos OpenAI, Claude y Gemini — a través de una única interfaz compatible con OpenAI. Cambia entre modelos modificando el 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; la mayoría de los SDK compatibles con OpenAI funcionan configurando base_url en https://api.cometapi.com/v1.
Roles de mensaje
| Role | Description |
|---|---|
system | Establece el comportamiento y la personalidad del asistente. Se coloca al inicio de la conversación. |
developer | Reemplaza a system para los modelos más recientes (o1+). Proporciona instrucciones que el modelo debe seguir independientemente de la entrada del usuario. |
user | Mensajes del usuario final. |
assistant | Respuestas anteriores del modelo, utilizadas para mantener el historial de la conversación. |
tool | Resultados de llamadas a herramientas/funciones. Debe incluir tool_call_id que coincida con la llamada a herramienta original. |
Enviar entrada multimodal
Muchos modelos admiten imágenes y audio junto con texto. Para enviar mensajes multimodales, usa el formato de arreglo paracontent:
detail controla la profundidad del análisis de la imagen:
low— más rápido, usa menos tokens (costo fijo)high— análisis detallado, consume más tokensauto— el modelo decide (predeterminado)
Transmitir respuestas
Para recibir salida incremental, establecestream en true. La respuesta se entrega como Server-Sent Events (SSE), donde cada evento contiene un objeto chat.completion.chunk:
Solicitar salida estructurada
Para forzar al modelo a devolver JSON válido que coincida con un esquema específico, usaresponse_format:
json_schema) garantiza que la salida coincida exactamente con tu esquema. El modo JSON Object (json_object) solo garantiza JSON válido; la estructura no se aplica.Llamar herramientas y funciones
Para permitir que el modelo llame funciones externas, proporciona definiciones de herramientas:finish_reason: "tool_calls" y el arreglo message.tool_calls contendrá el nombre de la función y los argumentos. Luego ejecutas la función y envías el resultado de vuelta como un mensaje tool con el tool_call_id correspondiente.
Notas entre proveedores
Compatibilidad de parámetros entre proveedores
Compatibilidad de parámetros entre proveedores
| Parámetro | 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 | solo 1 | 1–8 |
stop | Hasta 4 | Hasta 4 | Hasta 5 |
tools | ✅ | ✅ | ✅ |
response_format | ✅ | ✅ (json_schema) | ✅ |
logprobs | ✅ | ❌ | ❌ |
reasoning_effort | o-series, GPT-5.1+ | ❌ | ❌ (usa thinking para Gemini native) |
max_tokens vs max_completion_tokens
max_tokens vs max_completion_tokens
max_tokens— El parámetro heredado. Funciona con la mayoría de los modelos, pero está en desuso para los modelos OpenAI más nuevos.max_completion_tokens— El parámetro recomendado para los modelos GPT-4.1, serie GPT-5 y o-series. Es obligatorio para los modelos de razonamiento, ya que incluye tanto los tokens de salida como los tokens de razonamiento.
system vs developer role
system vs developer role
system— El rol de instrucción tradicional. Funciona con todos los modelos.developer— Introducido con los modelos o1. Proporciona un seguimiento de instrucciones más sólido para los modelos más nuevos. Vuelve al comportamiento desystemen modelos más antiguos.
developer para proyectos nuevos dirigidos a modelos GPT-4.1+ u o-series.Preguntas frecuentes
¿Cómo manejar los límites de tasa?
Cuando te encuentres con429 Too Many Requests, implementa retroceso exponencial:
¿Cómo mantener el contexto de la conversación?
Incluye el historial completo de la conversación en el arreglomessages:
¿Qué significa finish_reason?
| Valor | Significado |
|---|---|
stop | Finalización natural o se alcanzó una secuencia de parada. |
length | Se alcanzó el límite de max_tokens o max_completion_tokens. |
tool_calls | El modelo invocó una o más llamadas a herramientas/funciones. |
content_filter | La salida fue filtrada debido a la política de contenido. |
¿Cómo controlar los costos?
- Usa
max_completion_tokenspara limitar la longitud de la salida. - Elige modelos rentables (p. ej.,
gpt-5.4-miniogpt-5.4-nanopara tareas más simples). - Mantén los prompts concisos; evita contexto redundante.
- Supervisa el uso de tokens en el campo
usagede la respuesta.
Autorizaciones
Bearer token authentication. Use your CometAPI key.
Cuerpo
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 Respuesta
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"