> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Tạo một Message

> Sử dụng Anthropic Messages API thông qua CometAPI để gọi các model Claude với adaptive thinking, prompt caching, tool use, web search, streaming và effort control.

CometAPI hỗ trợ Anthropic Messages API một cách nguyên bản, cho phép bạn truy cập trực tiếp vào các model Claude với các tính năng dành riêng cho Anthropic. Hãy dùng endpoint này cho các khả năng của Claude như adaptive thinking, prompt caching và effort control.

<Tip>
  Sử dụng [tài liệu tham khảo Anthropic Messages API](https://platform.claude.com/docs/en/api/messages) chính thức làm nguồn chuẩn cho danh sách tham số đầy đủ, schema phản hồi và hành vi đặc thù của Claude. Trang CometAPI này giải thích cách gửi dạng request đó thông qua CometAPI.
</Tip>

<Warning>
  Các tham số request và trường response của Anthropic có thể thay đổi khi các tính năng của Claude phát triển. Hãy xem [tài liệu Anthropic Messages API](https://platform.claude.com/docs/en/api/messages) để biết danh sách tham số đầy đủ mới nhất và hành vi riêng của từng nhà cung cấp.
</Warning>

<Warning>
  Nhiều model Claude mới hơn từ chối các giá trị `temperature`, `top_p` và `top_k` không mặc định trên Messages API. Hãy bỏ qua các trường sampling này trừ khi bạn đã xác minh model được chọn có hỗ trợ. Nếu model trả về lỗi tham số không được hỗ trợ hoặc đã bị ngừng sử dụng, hãy xóa trường đó khỏi request.
</Warning>

<Note>
  Cả header `x-api-key` và `Authorization: Bearer` đều được hỗ trợ để xác thực. Các SDK Anthropic chính thức mặc định sử dụng `x-api-key`.
</Note>

## Bắt đầu nhanh

Để sử dụng SDK Anthropic chính thức với CometAPI, hãy đặt base URL:

<CodeGroup>
  ```python Python theme={null}
  import os
  import anthropic

  client = anthropic.Anthropic(
      base_url="https://api.cometapi.com",
      api_key=os.environ["COMETAPI_KEY"],
  )

  message = client.messages.create(
      model="claude-sonnet-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello!"}],
  )
  print(message.content[0].text)
  ```

  ```javascript JavaScript theme={null}
  import Anthropic from "@anthropic-ai/sdk";

  const client = new Anthropic({
      apiKey: process.env.COMETAPI_KEY,
      baseURL: "https://api.cometapi.com",
  });

  const message = await client.messages.create({
      model: "claude-sonnet-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello!" }],
  });
  console.log(message.content[0].text);
  ```
</CodeGroup>

## Kiểm soát adaptive thinking

Sử dụng adaptive thinking với `output_config.effort` để kiểm soát mức độ xử lý mà Claude áp dụng cho một response. Các model Claude mới hơn từ chối cấu trúc manual thinking cũ `thinking={"type": "enabled", "budget_tokens": ...}`.

```python theme={null}
message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=4096,
    thinking={"type": "adaptive"},
    output_config={"effort": "xhigh"},
    messages=[
        {
            "role": "user",
            "content": "Analyze the trade-offs between a monolithic architecture and microservices for a small engineering team.",
        }
    ],
)

for block in message.content:
    if block.type == "text":
        print(block.text)
```

<Warning>
  Thinking tokens được tính vào giới hạn `max_tokens` của bạn. Hãy đặt `max_tokens` đủ cao cho cả phần suy nghĩ và câu trả lời cuối cùng khi bạn sử dụng các mức effort cao hơn.
</Warning>

***

## Lưu cache prompt

Để giảm độ trễ và chi phí cho các yêu cầu tiếp theo, hãy lưu cache các system prompt lớn hoặc tiền tố hội thoại. Thêm `cache_control` vào các khối content cần được lưu cache:

```python theme={null}
message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are an expert code reviewer. [Long detailed instructions...]",
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": "Review this code..."}],
)
```

Mức sử dụng cache được báo cáo trong trường `usage` của phản hồi:

* `cache_creation_input_tokens` — tokens được ghi vào cache (được tính phí ở mức cao hơn)
* `cache_read_input_tokens` — tokens được đọc từ cache (được tính phí ở mức thấp hơn)

<Info>
  Prompt caching yêu cầu tối thiểu **1.024 tokens** trong khối content được lưu cache. Content ngắn hơn mức này sẽ không được lưu cache.
</Info>

***

## Stream phản hồi

Để stream phản hồi bằng Server-Sent Events (SSE), đặt `stream: true`. Các sự kiện sẽ đến theo thứ tự sau:

1. `message_start` — chứa metadata của message và usage ban đầu
2. `content_block_start` — đánh dấu phần bắt đầu của mỗi khối content
3. `content_block_delta` — các đoạn văn bản tăng dần (`text_delta`)
4. `content_block_stop` — đánh dấu phần kết thúc của mỗi khối content
5. `message_delta` — `stop_reason` cuối cùng và `usage` đầy đủ
6. `message_stop` — báo hiệu kết thúc luồng

```python theme={null}
with client.messages.stream(
    model="claude-sonnet-5",
    max_tokens=256,
    messages=[{"role": "user", "content": "Hello"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="")
```

***

## Kiểm soát mức độ nỗ lực

Để kiểm soát Claude bỏ ra bao nhiêu công sức khi tạo phản hồi, hãy dùng `output_config.effort`:

```python theme={null}
message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=4096,
    messages=[
        {"role": "user", "content": "Summarize this briefly."}
    ],
    output_config={"effort": "low"},  # "low", "medium", "high", "xhigh", or "max"
)
```

***

## Sử dụng công cụ phía máy chủ

Claude hỗ trợ các công cụ phía máy chủ chạy trên hạ tầng của Anthropic:

<Tabs>
  <Tab title="Web Fetch">
    Truy xuất và phân tích nội dung từ URL:

    ```python theme={null}
    message = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "Analyze the content at https://arxiv.org/abs/1512.03385"}
        ],
        tools=[
            {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}
        ],
    )
    ```
  </Tab>

  <Tab title="Web Search">
    Tìm kiếm trên web để lấy thông tin theo thời gian thực:

    ```python theme={null}
    message = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "What are the latest developments in AI?"}
        ],
        tools=[
            {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}
        ],
    )
    ```
  </Tab>
</Tabs>

***

## Ví dụ phản hồi

Một phản hồi điển hình từ endpoint Anthropic của CometAPI:

```json theme={null}
{
  "id": "msg_bdrk_01UjHdmSztrL7QYYm7CKBDFB",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello!"
    }
  ],
  "model": "claude-sonnet-5",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 19,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0,
    "cache_creation": {
      "ephemeral_5m_input_tokens": 0,
      "ephemeral_1h_input_tokens": 0
    },
    "output_tokens": 4
  }
}
```

***

## So sánh với endpoint tương thích OpenAI

| Tính năng          | Anthropic Messages (`/v1/messages`)                         | Tương thích OpenAI (`/v1/chat/completions`)    |
| ------------------ | ----------------------------------------------------------- | ---------------------------------------------- |
| Adaptive thinking  | `thinking` với `type: "adaptive"` và `output_config.effort` | Không khả dụng                                 |
| Prompt caching     | `cache_control` trên các khối content                       | Không khả dụng                                 |
| Điều khiển effort  | `output_config.effort`                                      | Không khả dụng                                 |
| Web fetch/search   | Công cụ phía server (`web_fetch`, `web_search`)             | Không khả dụng                                 |
| Header xác thực    | `x-api-key` hoặc `Bearer`                                   | Chỉ `Bearer`                                   |
| Định dạng phản hồi | Định dạng Anthropic (`content` blocks)                      | Định dạng OpenAI (`choices`, `message`)        |
| Models             | Chỉ Claude                                                  | Nhiều nhà cung cấp (GPT, Claude, Gemini, v.v.) |


## OpenAPI

````yaml api/openapi/text/post-anthropic-messages.openapi.json POST /v1/messages
openapi: 3.1.0
info:
  title: Anthropic Messages API
  version: 1.0.0
servers:
  - url: https://api.cometapi.com
security:
  - apiKeyAuth: []
paths:
  /v1/messages:
    post:
      summary: Anthropic Messages
      description: >-
        Send structured messages to Claude models using the Anthropic native API
        format. Supports text and multimodal inputs, multi-turn conversations,
        adaptive thinking, tool use, prompt caching, streaming, and web search.
        Use this endpoint when you need Claude-specific features like adaptive
        thinking or prompt caching that are not available through the
        OpenAI-compatible endpoint.
      operationId: anthropic_messages
      parameters:
        - name: anthropic-version
          in: header
          required: false
          description: The Anthropic API version to use. Defaults to `2023-06-01`.
          schema:
            type: string
            default: '2023-06-01'
            example: '2023-06-01'
        - name: anthropic-beta
          in: header
          required: false
          description: >-
            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`.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - messages
                - max_tokens
              properties:
                model:
                  type: string
                  description: >-
                    The Claude model to use. See the [Models
                    page](/overview/models) for available Claude model IDs.
                  example: claude-sonnet-5
                messages:
                  type: array
                  description: >-
                    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.
                  items:
                    type: object
                    required:
                      - role
                      - content
                    properties:
                      role:
                        type: string
                        description: The role of the message author.
                        enum:
                          - user
                          - assistant
                      content:
                        description: >-
                          The message content. Either a plain string or an array
                          of content blocks for multimodal input.
                        oneOf:
                          - type: string
                          - type: array
                            items:
                              type: object
                              properties:
                                type:
                                  type: string
                                  description: The content block type.
                                  enum:
                                    - text
                                    - image
                                    - document
                                    - tool_use
                                    - tool_result
                                text:
                                  type: string
                                  description: Text content (for `text` type blocks).
                                source:
                                  type: object
                                  description: >-
                                    Source data for `image` or `document`
                                    blocks.
                                  properties:
                                    type:
                                      type: string
                                      enum:
                                        - base64
                                        - url
                                      description: >-
                                        Image source type: `url` for a public
                                        image URL, or `base64` for inline data.
                                    media_type:
                                      type: string
                                      description: >-
                                        Image MIME type for base64 sources, such
                                        as `image/jpeg` or `image/png`.
                                    data:
                                      type: string
                                      description: >-
                                        Base64-encoded image bytes when `type`
                                        is `base64`.
                                    url:
                                      type: string
                                      description: >-
                                        Public HTTPS image URL when `type` is
                                        `url`. The provider must be able to
                                        download it.
                                cache_control:
                                  type: object
                                  description: >-
                                    Cache control for prompt caching. Set
                                    `{"type": "ephemeral"}` to cache this
                                    content block.
                                  properties:
                                    type:
                                      type: string
                                      enum:
                                        - ephemeral
                                      description: Cache control type. Use `ephemeral`.
                                    ttl:
                                      type: string
                                      description: >-
                                        Cache TTL. Options: `ephemeral_5m` (5
                                        min), `ephemeral_1h` (1 hour).
                max_tokens:
                  type: integer
                  description: >-
                    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.
                  minimum: 1
                  example: 1024
                system:
                  description: >-
                    System prompt providing context and instructions to Claude.
                    Can be a plain string or an array of content blocks (useful
                    for prompt caching).
                  oneOf:
                    - type: string
                    - type: array
                      items:
                        type: object
                        properties:
                          type:
                            type: string
                            enum:
                              - text
                            description: Content block type, `text`.
                          text:
                            type: string
                            description: System prompt text for this block.
                          cache_control:
                            type: object
                            properties:
                              type:
                                type: string
                                enum:
                                  - ephemeral
                                description: Cache control type. Use `ephemeral`.
                            description: >-
                              Marks this system block as a prompt-cache
                              breakpoint.
                temperature:
                  type: number
                  description: >-
                    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.
                  minimum: 0
                  maximum: 1
                  default: 1
                  example: 1
                top_p:
                  type: number
                  description: >-
                    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.
                  minimum: 0
                  maximum: 1
                  example: 1
                top_k:
                  type: integer
                  description: >-
                    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.
                  minimum: 0
                  example: 0
                stream:
                  type: boolean
                  description: >-
                    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`.
                  default: false
                stop_sequences:
                  type: array
                  description: >-
                    Custom strings that cause the model to stop generating when
                    encountered. The stop sequence is not included in the
                    response.
                  items:
                    type: string
                thinking:
                  type: object
                  description: >-
                    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.
                  properties:
                    type:
                      type: string
                      description: >-
                        Thinking mode. `adaptive` lets the model decide when and
                        how much to think. `disabled` turns thinking off only on
                        models that support disabling it. `enabled` is the
                        legacy manual-budget mode and is rejected by newer
                        Claude models.
                      enum:
                        - adaptive
                        - disabled
                        - enabled
                    budget_tokens:
                      type: integer
                      description: >-
                        Legacy manual-thinking token budget. Minimum: 1,024 when
                        accepted. These tokens count toward `max_tokens`. Do not
                        send this field to newer adaptive-thinking models that
                        reject manual thinking budgets.
                      minimum: 1024
                    display:
                      type: string
                      description: >-
                        Controls visible thinking blocks on models that support
                        display selection. `summarized` returns a readable
                        thinking summary; `omitted` returns an empty thinking
                        field with continuity metadata where applicable.
                      enum:
                        - summarized
                        - omitted
                tools:
                  type: array
                  description: >-
                    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.
                  items:
                    type: object
                    properties:
                      name:
                        type: string
                        description: >-
                          Tool name. The model repeats it in `tool_use` blocks
                          when it calls the tool.
                      description:
                        type: string
                        description: A description of what the tool does.
                      input_schema:
                        type: object
                        description: JSON Schema defining the tool's input parameters.
                      type:
                        type: string
                        description: >-
                          The tool type. Required for server tools (e.g.,
                          `web_search_20250305`, `web_fetch_20250910`,
                          `code_execution_20250522`).
                      max_uses:
                        type: integer
                        description: >-
                          Maximum number of times this tool can be used in a
                          single request.
                tool_choice:
                  type: object
                  description: Controls how the model uses tools.
                  properties:
                    type:
                      type: string
                      description: >-
                        The tool choice mode: `auto` (model decides), `any`
                        (must use a tool), `tool` (must use a specific tool), or
                        `none` (no tools).
                      enum:
                        - auto
                        - any
                        - tool
                        - none
                    name:
                      type: string
                      description: >-
                        The specific tool name to use. Required when `type` is
                        `tool`.
                    disable_parallel_tool_use:
                      type: boolean
                      description: >-
                        If `true`, prevent the model from calling multiple tools
                        in parallel.
                metadata:
                  type: object
                  description: Request metadata for tracking and analytics.
                  properties:
                    user_id:
                      type: string
                      description: >-
                        An external identifier for the user making the request.
                        Used for abuse detection.
                output_config:
                  type: object
                  description: >-
                    Configuration for response effort and output format. Field
                    support depends on the selected Claude model.
                  properties:
                    effort:
                      type: string
                      description: >-
                        Controls how much effort Claude applies to the response.
                        `high` is the default for newer effort-capable models.
                        Use `low` or `medium` for lower latency and cost,
                        `xhigh` for advanced coding or agentic work when
                        supported, and `max` only for the hardest tasks with a
                        large `max_tokens` value.
                      enum:
                        - low
                        - medium
                        - high
                        - xhigh
                        - max
                      example: medium
                    format:
                      type: object
                      description: >-
                        Structured output configuration. Use
                        `{"type":"json","schema":{...}}` to ask for JSON that
                        matches your schema when the selected model supports
                        structured output.
                service_tier:
                  type: string
                  description: >-
                    The service tier to use. `auto` tries priority capacity
                    first, `standard_only` uses only standard capacity.
                  enum:
                    - auto
                    - standard_only
            examples:
              Default:
                summary: Basic message
                value:
                  model: claude-sonnet-5
                  max_tokens: 1024
                  system: You are a helpful assistant.
                  messages:
                    - role: user
                      content: Hello, world
              Image Input:
                summary: Image Input
                value:
                  model: claude-sonnet-5
                  max_tokens: 1024
                  messages:
                    - role: user
                      content:
                        - type: image
                          source:
                            type: url
                            url: https://picsum.photos/seed/comet/800/600.jpg
                        - type: text
                          text: Describe this image in one sentence.
              Prompt Cache:
                summary: With prompt caching
                value:
                  model: claude-sonnet-5
                  max_tokens: 1024
                  system:
                    - type: text
                      text: >-
                        You are an expert code reviewer. Analyze code for
                        correctness, performance, security, and maintainability.
                        Follow SOLID principles and provide actionable
                        suggestions. [Long system prompt content that exceeds
                        1024 tokens to enable caching...]
                      cache_control:
                        type: ephemeral
                  messages:
                    - role: user
                      content: |-
                        Please review this Python code:

                        def calculate_order_total(items):
                            total = 0
                            for item in items:
                                total += item['price'] * item['quantity']
                            return total
              Streaming:
                summary: Streaming response
                value:
                  model: claude-sonnet-5
                  max_tokens: 256
                  stream: true
                  messages:
                    - role: user
                      content: Hello
              Web Fetch:
                summary: With web fetch tool
                value:
                  model: claude-sonnet-5
                  max_tokens: 1024
                  messages:
                    - role: user
                      content: >-
                        Please analyze the content at
                        https://arxiv.org/abs/1512.03385
                  tools:
                    - type: web_fetch_20250910
                      name: web_fetch
                      max_uses: 5
              Adaptive Thinking:
                summary: With adaptive thinking and effort
                value:
                  model: claude-sonnet-5
                  max_tokens: 4096
                  thinking:
                    type: adaptive
                  output_config:
                    effort: xhigh
                  messages:
                    - role: user
                      content: >-
                        Analyze the trade-offs between a monolithic architecture
                        and microservices for a small engineering team.
      responses:
        '200':
          description: >-
            Successful response. When `stream` is `true`, the response is a
            stream of SSE events.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: >-
                      Unique identifier for this message (e.g.,
                      `msg_01XFDUDYJgAACzvnptvVoYEL`).
                  type:
                    type: string
                    description: Always `message`.
                    enum:
                      - message
                  role:
                    type: string
                    description: Always `assistant`.
                    enum:
                      - assistant
                  content:
                    type: array
                    description: >-
                      The response content blocks. May include `text`,
                      `thinking`, `tool_use`, and other block types.
                    items:
                      type: object
                      properties:
                        type:
                          type: string
                          description: The content block type.
                          enum:
                            - text
                            - thinking
                            - tool_use
                        text:
                          type: string
                          description: The generated text (for `text` blocks).
                        thinking:
                          type: string
                          description: >-
                            Thinking text or summary for `thinking` blocks when
                            the selected model returns visible thinking content.
                        signature:
                          type: string
                          description: Cryptographic signature for the thinking block.
                        id:
                          type: string
                          description: Tool use ID (for `tool_use` blocks).
                        name:
                          type: string
                          description: Tool name (for `tool_use` blocks).
                        input:
                          type: object
                          description: Tool input arguments (for `tool_use` blocks).
                  model:
                    type: string
                    description: >-
                      The specific model version that generated this response,
                      such as `claude-sonnet-5`.
                  stop_reason:
                    type: string
                    description: >-
                      Why the model stopped generating. `refusal` can be
                      returned as a successful HTTP response when the model
                      declines a request.
                    enum:
                      - end_turn
                      - max_tokens
                      - stop_sequence
                      - tool_use
                      - pause_turn
                      - refusal
                  stop_sequence:
                    type:
                      - string
                      - 'null'
                    description: >-
                      The stop sequence that caused the model to stop, if
                      applicable.
                  usage:
                    type: object
                    description: Token usage statistics.
                    properties:
                      input_tokens:
                        type: integer
                        description: >-
                          Number of input tokens (prompt + conversation
                          history).
                      output_tokens:
                        type: integer
                        description: Number of output tokens generated.
                      cache_creation_input_tokens:
                        type: integer
                        description: >-
                          Number of input tokens used to create the prompt
                          cache.
                      cache_read_input_tokens:
                        type: integer
                        description: Number of input tokens read from the prompt cache.
                      cache_creation:
                        type: object
                        description: Detailed cache creation token breakdown by TTL tier.
                        properties:
                          ephemeral_5m_input_tokens:
                            type: integer
                            description: Tokens written to 5-minute ephemeral cache.
                          ephemeral_1h_input_tokens:
                            type: integer
                            description: Tokens written to 1-hour ephemeral cache.
                      output_tokens_details:
                        type: object
                        description: >-
                          Detailed output token breakdown when returned by the
                          selected model.
                        properties:
                          thinking_tokens:
                            type: integer
                            description: >-
                              Number of output tokens used for model thinking
                              when reported.
      x-codeSamples:
        - lang: Python
          label: Basic
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=1024,
                system="You are a helpful assistant.",
                messages=[
                    {"role": "user", "content": "Hello, world"}
                ],
            )

            print(message.content[0].text)
        - lang: Python
          label: Prompt Cache
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=1024,
                system=[
                    {
                        "type": "text",
                        "text": "You are an expert code reviewer. Analyze code, identify issues, "
                                "and suggest improvements following SOLID principles...",
                        "cache_control": {"type": "ephemeral"},
                    }
                ],
                messages=[
                    {
                        "role": "user",
                        "content": "Please review this Python code:\n\n"
                                   "def calculate_order_total(items):\n"
                                   "    total = 0\n"
                                   "    for item in items:\n"
                                   "        total += item['price'] * item['quantity']\n"
                                   "    return total",
                    }
                ],
            )

            print(message.content[0].text)
        - lang: Python
          label: Adaptive thinking
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=4096,
                thinking={"type": "adaptive"},
                output_config={"effort": "xhigh"},
                messages=[
                    {
                        "role": "user",
                        "content": "Analyze the trade-offs between a monolithic architecture and microservices for a small engineering team.",
                    }
                ],
            )

            for block in message.content:
                if block.type == "text":
                    print(block.text)
        - lang: Python
          label: Effort control
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=2048,
                messages=[
                    {
                        "role": "user",
                        "content": "Summarize the key risks in moving a billing service to microservices.",
                    }
                ],
                output_config={"effort": "low"},
            )

            print(message.content[0].text)
        - lang: Python
          label: Streaming
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            with client.messages.stream(
                model="claude-sonnet-5",
                max_tokens=256,
                messages=[
                    {"role": "user", "content": "Hello"}
                ],
            ) as stream:
                for text in stream.text_stream:
                    print(text, end="")
        - lang: Python
          label: Web Fetch
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=1024,
                messages=[
                    {
                        "role": "user",
                        "content": "Please analyze the content at https://arxiv.org/abs/1512.03385",
                    }
                ],
                tools=[
                    {
                        "type": "web_fetch_20250910",
                        "name": "web_fetch",
                        "max_uses": 5,
                    }
                ],
            )

            print(message.content)
        - lang: Python
          label: Image Input
          source: |
            import os
            import anthropic

            client = anthropic.Anthropic(
                base_url="https://api.cometapi.com",
                api_key=os.environ["COMETAPI_KEY"],
            )

            message = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=1024,
                messages=[
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "image",
                                "source": {
                                    "type": "url",
                                    "url": "https://picsum.photos/seed/comet/800/600.jpg",
                                },
                            },
                            {"type": "text", "text": "Describe this image in one sentence."},
                        ],
                    }
                ],
            )

            print(message.content[0].text)
        - lang: JavaScript
          label: Basic
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 1024,
                system: "You are a helpful assistant.",
                messages: [
                    { role: "user", content: "Hello, world" },
                ],
            });

            console.log(message.content[0].text);
        - lang: JavaScript
          label: Adaptive thinking
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 4096,
                thinking: { type: "adaptive" },
                output_config: { effort: "xhigh" },
                messages: [
                    {
                        role: "user",
                        content: "Analyze the trade-offs between a monolithic architecture and microservices for a small engineering team.",
                    },
                ],
            });

            for (const block of message.content) {
                if (block.type === "text") {
                    console.log(block.text);
                }
            }
        - lang: JavaScript
          label: Effort control
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 2048,
                messages: [
                    {
                        role: "user",
                        content: "Summarize the key risks in moving a billing service to microservices.",
                    },
                ],
                output_config: { effort: "low" },
            });

            console.log(message.content[0].text);
        - lang: JavaScript
          label: Streaming
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const stream = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 256,
                messages: [
                    { role: "user", content: "Hello" },
                ],
                stream: true,
            });

            for await (const event of stream) {
                if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
                    process.stdout.write(event.delta.text);
                }
            }
        - lang: JavaScript
          label: Web Fetch
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 1024,
                messages: [
                    {
                        role: "user",
                        content: "Please analyze the content at https://arxiv.org/abs/1512.03385",
                    },
                ],
                tools: [
                    {
                        type: "web_fetch_20250910",
                        name: "web_fetch",
                        max_uses: 5,
                    },
                ],
            });

            console.log(message.content);
        - lang: JavaScript
          label: Image Input
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 1024,
                messages: [
                    {
                        role: "user",
                        content: [
                            {
                                type: "image",
                                source: { type: "url", url: "https://picsum.photos/seed/comet/800/600.jpg" },
                            },
                            { type: "text", text: "Describe this image in one sentence." },
                        ],
                    },
                ],
            });

            console.log(message.content[0].text);
        - lang: JavaScript
          label: Prompt Cache
          source: |
            import Anthropic from "@anthropic-ai/sdk";

            const client = new Anthropic({
                apiKey: process.env.COMETAPI_KEY,
                baseURL: "https://api.cometapi.com",
            });

            const message = await client.messages.create({
                model: "claude-sonnet-5",
                max_tokens: 1024,
                system: [
                    {
                        type: "text",
                        text: "You are an expert code reviewer. Analyze code, identify issues, and suggest improvements following SOLID principles...",
                        cache_control: { type: "ephemeral" },
                    },
                ],
                messages: [
                    {
                        role: "user",
                        content: "Please review this Python code:\n\ndef calculate_order_total(items):\n    total = 0\n    for item in items:\n        total += item['price'] * item['quantity']\n    return total",
                    },
                ],
            });

            console.log(message.content[0].text);
        - lang: Shell
          label: Basic
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "system": "You are a helpful assistant.",
                "messages": [
                  {"role": "user", "content": "Hello, world"}
                ]
              }'
        - lang: Shell
          label: Adaptive thinking
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 4096,
                "thinking": {"type": "adaptive"},
                "output_config": {"effort": "xhigh"},
                "messages": [
                  {"role": "user", "content": "Analyze the trade-offs between a monolithic architecture and microservices for a small engineering team."}
                ]
              }'
        - lang: Shell
          label: Effort control
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 2048,
                "messages": [
                  {"role": "user", "content": "Summarize the key risks in moving a billing service to microservices."}
                ],
                "output_config": {"effort": "low"}
              }'
        - lang: Shell
          label: Streaming
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 256,
                "stream": true,
                "messages": [
                  {"role": "user", "content": "Hello"}
                ]
              }'
        - lang: Shell
          label: Prompt Cache
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "system": [
                  {
                    "type": "text",
                    "text": "You are an expert code reviewer...",
                    "cache_control": {"type": "ephemeral"}
                  }
                ],
                "messages": [
                  {"role": "user", "content": "Please review this code..."}
                ]
              }'
        - lang: Shell
          label: Web Fetch
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "messages": [
                  {"role": "user", "content": "Please analyze the content at https://arxiv.org/abs/1512.03385"}
                ],
                "tools": [
                  {"type": "web_fetch_20250910", "name": "web_fetch", "max_uses": 5}
                ]
              }'
        - lang: Shell
          label: Image Input
          source: |
            curl https://api.cometapi.com/v1/messages \
              -H "Content-Type: application/json" \
              -H "x-api-key: $COMETAPI_KEY" \
              -H "anthropic-version: 2023-06-01" \
              -d '{
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "messages": [
                  {
                    "role": "user",
                    "content": [
                      {"type": "image", "source": {"type": "url", "url": "https://picsum.photos/seed/comet/800/600.jpg"}},
                      {"type": "text", "text": "Describe this image in one sentence."}
                    ]
                  }
                ]
              }'
components:
  securitySchemes:
    apiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        Your CometAPI key passed via the `x-api-key` header. `Authorization:
        Bearer $COMETAPI_KEY` is also supported.

````