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

# Tạo Tin nhắn

> Tạo một tin nhắn باستخدام định dạng Anthropic Messages API

## Tổng quan

Endpoint này cung cấp khả năng tương thích gốc với Anthropic Messages API. Hãy sử dụng endpoint này cho các model Claude với các tính năng như extended thinking.

Endpoint này giữ nguyên hợp đồng native của Anthropic. `messages` phải là mảng tin nhắn `user` / `assistant`, `system` nằm ở field cấp cao nhất `system`, và `max_tokens` là bắt buộc. Nếu payload dùng role kiểu OpenAI như `system`, `developer`, hoặc `tool` bên trong `messages`, hãy gửi sang `/v1/chat/completions`.

<Note>
  Base URL cho Anthropic SDK: `https://api.tokenlab.sh` (không có hậu tố `/v1`)
</Note>

## Header của Request

<ParamField header="x-api-key" type="string" required>
  API key TokenLab của bạn. Phương án thay thế cho Bearer token.
</ParamField>

<ParamField header="anthropic-version" type="string" required>
  Phiên bản Anthropic API. Sử dụng `2023-06-01`.
</ParamField>

## Body của Request

<ParamField body="model" type="string" required>
  ID model Claude (ví dụ: `claude-sonnet-4-6` hoặc `claude-opus-4-6`).
</ParamField>

<ParamField body="messages" type="array" required>
  Mảng các object tin nhắn với `role` và `content`.
</ParamField>

<ParamField body="max_tokens" type="integer" required>
  Số lượng token tối đa để tạo.
</ParamField>

<ParamField body="system" type="string">
  System prompt (tách biệt với mảng messages).
</ParamField>

<ParamField body="temperature" type="number" default="1">
  Nhiệt độ lấy mẫu (0-1).
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  Bật phản hồi dạng streaming.
</ParamField>

<ParamField body="thinking" type="object">
  Cấu hình extended thinking (Claude Opus 4.5).

  * `type` (string): `"enabled"` để bật
  * `budget_tokens` (integer): Ngân sách token cho thinking
</ParamField>

<ParamField body="tools" type="array">
  Các công cụ khả dụng cho model.
</ParamField>

<ParamField body="tool_choice" type="object">
  Cách model nên sử dụng công cụ. Các tùy chọn: `auto`, `any`, `tool` (công cụ cụ thể).
</ParamField>

<ParamField body="top_p" type="number">
  Tham số nucleus sampling. Chỉ dùng temperature hoặc top\_p, không dùng cả hai.
</ParamField>

<ParamField body="top_k" type="integer">
  Chỉ lấy mẫu từ K lựa chọn hàng đầu cho mỗi token.
</ParamField>

<ParamField body="stop_sequences" type="array">
  Các chuỗi dừng tùy chỉnh sẽ khiến model ngừng tạo.
</ParamField>

<ParamField body="metadata" type="object">
  Metadata được đính kèm vào request nhằm mục đích theo dõi.
</ParamField>

## Phản hồi

<ResponseField name="id" type="string">
  Định danh duy nhất của tin nhắn.
</ResponseField>

<ResponseField name="type" type="string">
  Luôn là `message`.
</ResponseField>

<ResponseField name="role" type="string">
  Luôn là `assistant`.
</ResponseField>

<ResponseField name="content" type="array">
  Mảng các khối nội dung (text, thinking, tool\_use).
</ResponseField>

<ResponseField name="model" type="string">
  Model được sử dụng.
</ResponseField>

<ResponseField name="stop_reason" type="string">
  Lý do việc tạo nội dung dừng lại (`end_turn`, `max_tokens`, `tool_use`).
</ResponseField>

<ResponseField name="usage" type="object">
  Mức sử dụng token với `input_tokens` và `output_tokens`.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1/messages" \
    -H "x-api-key: sk-your-api-key" \
    -H "anthropic-version: 2023-06-01" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "claude-sonnet-4-6",
      "max_tokens": 1024,
      "system": "You are a helpful assistant.",
      "messages": [
        {"role": "user", "content": "Hello, Claude!"}
      ]
    }'
  ```

  ```python Python theme={null}
  from anthropic import Anthropic

  client = Anthropic(
      api_key="sk-your-api-key",
      base_url="https://api.tokenlab.sh"
  )

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

  print(message.content[0].text)
  ```

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

  const client = new Anthropic({
    apiKey: 'sk-your-api-key',
    baseURL: 'https://api.tokenlab.sh'
  });

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

  console.log(message.content[0].text);
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "model":      "claude-sonnet-4-6",
          "max_tokens": 1024,
          "system":     "You are a helpful assistant.",
          "messages": []map[string]string{
              {"role": "user", "content": "Hello, Claude!"},
          },
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", "https://api.tokenlab.sh/v1/messages", bytes.NewBuffer(jsonData))
      req.Header.Set("x-api-key", "sk-your-api-key")
      req.Header.Set("anthropic-version", "2023-06-01")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      body, _ := io.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```php PHP theme={null}
  <?php
  $payload = [
      'model' => 'claude-sonnet-4-6',
      'max_tokens' => 1024,
      'system' => 'You are a helpful assistant.',
      'messages' => [
          ['role' => 'user', 'content' => 'Hello, Claude!']
      ]
  ];

  $ch = curl_init('https://api.tokenlab.sh/v1/messages');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          'x-api-key: sk-your-api-key',
          'anthropic-version: 2023-06-01',
          'Content-Type: application/json'
      ],
      CURLOPT_POSTFIELDS => json_encode($payload)
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);
  echo $data['content'][0]['text'];
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "msg_abc123",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "Hello! How can I help you today?"
      }
    ],
    "model": "claude-sonnet-4-6",
    "stop_reason": "end_turn",
    "usage": {
      "input_tokens": 15,
      "output_tokens": 10
    }
  }
  ```
</ResponseExample>

## Ví dụ đầu vào thị giác

Với các mô hình Claude có hỗ trợ thị giác, hãy đặt hình ảnh bên trong `messages[].content` dưới dạng các khối ảnh có cấu trúc.

```json theme={null}
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Please describe this image."
        },
        {
          "type": "image",
          "source": {
            "type": "url",
            "url": "https://example.com/demo.jpg"
          }
        }
      ]
    }
  ]
}
```

```json theme={null}
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Please describe this image."
        },
        {
          "type": "image",
          "source": {
            "type": "base64",
            "media_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}
```

## Ví dụ về Extended Thinking

````python theme={null}
message = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000
    },
    messages=[{"role": "user", "content": "Solve this math problem..."}]
)

for block in message.content:
    if block.type == "thinking":
        print(f"Thinking: {block.thinking}")
    elif block.type == "text":
        print(f"Response: {block.text}")
```}
## Các lô tin nhắn Anthropic

TokenLab hiện cũng cung cấp luồng Anthropic Message Batches gốc bên cạnh `/v1/messages`.

Các route khả dụng:

- `POST /v1/messages/batches`
- `GET /v1/messages/batches`
- `GET /v1/messages/batches/:message_batch_id`
- `GET /v1/messages/batches/:message_batch_id/results`
- `POST /v1/messages/batches/:message_batch_id/cancel`
- `DELETE /v1/messages/batches/:message_batch_id`

Ghi chú vận hành:

- Sử dụng cùng một TokenLab API key với các header Anthropic gốc.
- Nếu batch item tham chiếu `file_id`, hãy thêm cả `anthropic-beta: files-api-2025-04-14`.
- Batch job vẫn giữ nguyên hình dạng request/response gốc của Anthropic, trong khi TokenLab theo dõi vòng đời quyết toán nội bộ của chúng.
````
