Skip to main content
POST
O CometAPI oferece suporte nativo à API Anthropic Messages, dando a você acesso direto aos modelos Claude com recursos específicos da Anthropic. Use este endpoint para capacidades do Claude, como adaptive thinking, prompt caching e controle de effort.
Use a referência oficial da API Anthropic Messages como fonte oficial para a lista completa de parâmetros, o schema de resposta e o comportamento específico do Claude. Esta página da CometAPI explica como enviar esse formato de solicitação pela CometAPI.
Os parâmetros de solicitação e os campos de resposta da Anthropic podem mudar à medida que os recursos do Claude evoluem. Consulte a documentação da API Anthropic Messages para ver a lista completa mais recente de parâmetros e o comportamento específico do provedor.
Muitos modelos Claude mais recentes rejeitam valores não padrão de temperature, top_p e top_k na API Messages. Omita esses campos de sampling, a menos que você tenha verificado o suporte para o model selecionado. Se um modelo retornar um erro de parâmetro não suportado ou obsoleto, remova o campo da solicitação.
Tanto os cabeçalhos x-api-key quanto Authorization: Bearer são suportados para autenticação. Os SDKs oficiais da Anthropic usam x-api-key por padrão.

Início rápido

Para usar o SDK oficial da Anthropic com o CometAPI, defina a URL base:

Controlar adaptive thinking

Use adaptive thinking com output_config.effort para controlar quanto trabalho o Claude aplica a uma resposta. Modelos Claude mais recentes rejeitam o formato manual legado de thinking thinking={"type": "enabled", "budget_tokens": ...}.
Os Tokens de thinking contam para o seu limite de max_tokens. Defina max_tokens alto o suficiente para abranger tanto o thinking quanto a resposta final ao usar níveis de effort mais altos.

Cache prompts

Para reduzir a latência e o custo em solicitações subsequentes, coloque em cache grandes prompts de sistema ou prefixos de conversa. Adicione cache_control aos blocos de content que devem ser armazenados em cache:
O uso do cache é informado no campo usage da resposta:
  • cache_creation_input_tokens — Tokens gravados no cache (cobrados a uma taxa mais alta)
  • cache_read_input_tokens — Tokens lidos do cache (cobrados a uma taxa reduzida)
O cache de Prompt exige um mínimo de 1.024 Tokens no bloco de content armazenado em cache. Conteúdo menor que isso não será armazenado em cache.

Stream responses

Para fazer Streaming de respostas usando Server-Sent Events (SSE), defina stream: true. Os eventos chegam nesta ordem:
  1. message_start — contém os metadados da mensagem e o uso inicial
  2. content_block_start — marca o início de cada bloco de content
  3. content_block_delta — partes incrementais de texto (text_delta)
  4. content_block_stop — marca o fim de cada bloco de content
  5. message_deltastop_reason final e usage completo
  6. message_stop — sinaliza o fim do stream

Control effort

Para controlar quanto esforço Claude dedica à geração de uma resposta, use output_config.effort:

Use server tools

Claude oferece suporte a ferramentas do lado do servidor que são executadas na infraestrutura da Anthropic:
Busque e analise conteúdo de URLs:

Response example

Um exemplo típico de resposta do endpoint Anthropic da CometAPI:

Comparar com o endpoint compatível com OpenAI

Autorizações

x-api-key
string
header
obrigatório

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

Cabeçalhos

anthropic-version
string
padrão:2023-06-01

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

Exemplo:

"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.

Corpo

application/json
model
string
obrigatório

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

Exemplo:

"claude-sonnet-5"

messages
object[]
obrigatório

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
obrigatório

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.

Intervalo necessário: x >= 1
Exemplo:

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
padrão: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.

Intervalo necessário: 0 <= x <= 1
Exemplo:

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.

Intervalo necessário: 0 <= x <= 1
Exemplo:

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.

Intervalo necessário: x >= 0
Exemplo:

0

stream
boolean
padrão: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.

Opções disponíveis:
auto,
standard_only

Resposta

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.

Opções disponíveis:
message
role
enum<string>

Always assistant.

Opções disponíveis:
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.

Opções disponíveis:
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.