Skip to main content
POST
CometAPI es compatible de forma nativa con la Anthropic Messages API, lo que te da acceso directo a los modelos Claude con funciones específicas de Anthropic. Usa este endpoint para capacidades de Claude como pensamiento adaptativo, caché de prompts y control de esfuerzo.
Usa la referencia oficial de la Anthropic Messages API como fuente autorizada para la lista completa de parámetros, el esquema de respuesta y el comportamiento específico de Claude. Esta página de CometAPI explica cómo enviar ese formato de solicitud a través de CometAPI.
Los parámetros de solicitud y los campos de respuesta de Anthropic pueden cambiar a medida que evolucionan las funciones de Claude. Consulta la documentación de Anthropic Messages API para ver la lista completa más reciente de parámetros y el comportamiento específico del proveedor.
Muchos modelos Claude más recientes rechazan valores no predeterminados de temperature, top_p y top_k en la Messages API. Omite estos campos de muestreo a menos que hayas verificado la compatibilidad del modelo seleccionado. Si un modelo devuelve un error de parámetro no compatible o desaprobado, elimina el campo de la solicitud.
Se admiten tanto los encabezados x-api-key como Authorization: Bearer para la autenticación. Los SDK oficiales de Anthropic usan x-api-key de forma predeterminada.

Inicio rápido

Para usar el SDK oficial de Anthropic con CometAPI, configura la URL base:

Controlar el pensamiento adaptativo

Usa el pensamiento adaptativo con output_config.effort para controlar cuánto trabajo aplica Claude a una respuesta. Los modelos Claude más recientes rechazan la estructura manual heredada de thinking thinking={"type": "enabled", "budget_tokens": ...}.
Los Tokens de thinking cuentan para tu límite de max_tokens. Configura max_tokens con un valor lo suficientemente alto para cubrir tanto el thinking como la respuesta final cuando uses niveles de esfuerzo más altos.

Cache prompts

Para reducir la latencia y el costo en solicitudes posteriores, almacena en caché prompts de sistema grandes o prefijos de conversación. Agrega cache_control a los bloques de contenido que deban almacenarse en caché:
El uso de la caché se informa en el campo usage de la respuesta:
  • cache_creation_input_tokens — Tokens escritos en la caché (facturados a una tarifa más alta)
  • cache_read_input_tokens — Tokens leídos desde la caché (facturados a una tarifa reducida)
El almacenamiento en caché de prompts requiere un mínimo de 1,024 tokens en el bloque de contenido almacenado en caché. El contenido más corto que esto no se almacenará en caché.

Stream responses

Para transmitir Responses usando Server-Sent Events (SSE), establece stream: true. Los eventos llegan en este orden:
  1. message_start — contiene los metadatos del mensaje y el uso inicial
  2. content_block_start — marca el inicio de cada bloque de contenido
  3. content_block_delta — fragmentos de texto incrementales (text_delta)
  4. content_block_stop — marca el final de cada bloque de contenido
  5. message_deltastop_reason final y usage completo
  6. message_stop — señala el final del stream

Control effort

Para controlar cuánto esfuerzo pone Claude en generar una respuesta, usa output_config.effort:

Use server tools

Claude admite herramientas del lado del servidor que se ejecutan en la infraestructura de Anthropic:
Obtén y analiza contenido desde URLs:

Response example

Una respuesta típica del endpoint de Anthropic de CometAPI:

Comparar con el endpoint compatible con OpenAI

Autorizaciones

x-api-key
string
header
requerido

Your CometAPI key passed via the x-api-key header. Authorization: Bearer $COMETAPI_KEY is also supported.

Encabezados

anthropic-version
string
predeterminado:2023-06-01

The Anthropic API version to use. Defaults to 2023-06-01.

Ejemplo:

"2023-06-01"

anthropic-beta
string

Comma-separated list of beta features to enable. Examples: max-tokens-3-5-sonnet-2024-07-15, pdfs-2024-09-25, output-128k-2025-02-19.

Cuerpo

application/json
model
string
requerido

The Claude model to use. See the Models page for available Claude model IDs.

Ejemplo:

"claude-sonnet-5"

messages
object[]
requerido

The conversation messages. Must alternate between user and assistant roles. Each message's content can be a string or an array of content blocks (text, image, document, tool_use, tool_result). There is a limit of 100,000 messages per request.

max_tokens
integer
requerido

The maximum number of tokens to generate. The model may stop before reaching this limit. When using thinking, the thinking tokens count towards this limit.

Rango requerido: x >= 1
Ejemplo:

1024

system

System prompt providing context and instructions to Claude. Can be a plain string or an array of content blocks (useful for prompt caching).

temperature
number
predeterminado:1

Model-dependent sampling control. Many newer Claude models reject non-default temperature values on the Messages API. Omit this field unless you have verified that the selected model accepts it; if the model returns an unsupported or deprecated-parameter error, remove the field instead of substituting another sampling value.

Rango requerido: 0 <= x <= 1
Ejemplo:

1

top_p
number

Model-dependent nucleus sampling control. Many newer Claude models reject non-default top_p values on the Messages API. Omit this field unless you have verified support for the selected model. Do not set temperature and top_p together.

Rango requerido: 0 <= x <= 1
Ejemplo:

1

top_k
integer

Model-dependent top-k sampling control. Many newer Claude models reject non-default top_k values on the Messages API. Omit this field unless you have verified support for the selected model.

Rango requerido: x >= 0
Ejemplo:

0

stream
boolean
predeterminado:false

If true, stream the response incrementally using Server-Sent Events (SSE). Events include message_start, content_block_start, content_block_delta, content_block_stop, message_delta, and message_stop.

stop_sequences
string[]

Custom strings that cause the model to stop generating when encountered. The stop sequence is not included in the response.

thinking
object

Controls Claude thinking when the selected model supports a configurable thinking mode. For newer adaptive-thinking models, use {"type":"adaptive"} with output_config.effort, or omit thinking when adaptive thinking is already the model default. Manual {"type":"enabled","budget_tokens":...} is supported only by older models and is rejected by newer Claude models.

tools
object[]

Tools the model may use. Supports client-defined functions, web search (web_search_20250305), web fetch (web_fetch_20250910), code execution (code_execution_20250522), and more.

tool_choice
object

Controls how the model uses tools.

metadata
object

Request metadata for tracking and analytics.

output_config
object

Configuration for response effort and output format. Field support depends on the selected Claude model.

service_tier
enum<string>

The service tier to use. auto tries priority capacity first, standard_only uses only standard capacity.

Opciones disponibles:
auto,
standard_only

Respuesta

200 - application/json

Successful response. When stream is true, the response is a stream of SSE events.

id
string

Unique identifier for this message (e.g., msg_01XFDUDYJgAACzvnptvVoYEL).

type
enum<string>

Always message.

Opciones disponibles:
message
role
enum<string>

Always assistant.

Opciones disponibles:
assistant
content
object[]

The response content blocks. May include text, thinking, tool_use, and other block types.

model
string

The specific model version that generated this response, such as claude-sonnet-5.

stop_reason
enum<string>

Why the model stopped generating. refusal can be returned as a successful HTTP response when the model declines a request.

Opciones disponibles:
end_turn,
max_tokens,
stop_sequence,
tool_use,
pause_turn,
refusal
stop_sequence
string | null

The stop sequence that caused the model to stop, if applicable.

usage
object

Token usage statistics.