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

# メッセージを作成

> Anthropic Messages API 形式を使用してメッセージを作成します

## 概要

このエンドポイントは、Anthropic Messages API とのネイティブ互換性を提供します。extended thinking などの機能を備えた Claude モデルにはこれを使用してください。

このエンドポイントは Anthropic のネイティブ契約を維持します。`messages` は `user` / `assistant` メッセージの配列である必要があり、`system` はトップレベルの `system` フィールドに置き、`max_tokens` は必須です。`messages` 内で OpenAI の `system`、`developer`、`tool` などの role を使う payload は `/v1/chat/completions` に送ってください。

<Note>
  Anthropic SDK の Base URL: `https://api.tokenlab.sh`（`/v1` サフィックスなし）
</Note>

## リクエストヘッダー

<ParamField header="x-api-key" type="string" required>
  あなたの TokenLab API key です。Bearer token の代替として使用できます。
</ParamField>

<ParamField header="anthropic-version" type="string" required>
  Anthropic API version。`2023-06-01` を使用してください。
</ParamField>

## リクエストボディ

<ParamField body="model" type="string" required>
  Claude モデル ID（例: `claude-sonnet-4-6` または `claude-opus-4-6`）。
</ParamField>

<ParamField body="messages" type="array" required>
  `role` と `content` を持つ message object の配列。
</ParamField>

<ParamField body="max_tokens" type="integer" required>
  生成する最大 token 数。
</ParamField>

<ParamField body="system" type="string">
  System prompt（messages 配列とは別）。
</ParamField>

<ParamField body="temperature" type="number" default="1">
  Sampling temperature（0-1）。
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  ストリーミングレスポンスを有効にします。
</ParamField>

<ParamField body="thinking" type="object">
  Extended thinking の設定（Claude Opus 4.5）。

  * `type` (string): 有効化するには `"enabled"`
  * `budget_tokens` (integer): thinking 用の token 予算
</ParamField>

<ParamField body="tools" type="array">
  モデルで利用可能なツール。
</ParamField>

<ParamField body="tool_choice" type="object">
  モデルがツールをどのように使用すべきか。オプション: `auto`、`any`、`tool`（特定のツール）。
</ParamField>

<ParamField body="top_p" type="number">
  Nucleus sampling パラメータ。temperature または top\_p のいずれか一方のみを使用し、両方は使用しないでください。
</ParamField>

<ParamField body="top_k" type="integer">
  各 token について上位 K 個の選択肢からのみサンプリングします。
</ParamField>

<ParamField body="stop_sequences" type="array">
  モデルの生成を停止させるカスタム stop sequence。
</ParamField>

<ParamField body="metadata" type="object">
  トラッキング目的でリクエストに付加する metadata。
</ParamField>

## レスポンス

<ResponseField name="id" type="string">
  一意のメッセージ識別子。
</ResponseField>

<ResponseField name="type" type="string">
  常に `message`。
</ResponseField>

<ResponseField name="role" type="string">
  常に `assistant`。
</ResponseField>

<ResponseField name="content" type="array">
  content block（text、thinking、tool\_use）の配列。
</ResponseField>

<ResponseField name="model" type="string">
  使用されたモデル。
</ResponseField>

<ResponseField name="stop_reason" type="string">
  生成が停止した理由（`end_turn`、`max_tokens`、`tool_use`）。
</ResponseField>

<ResponseField name="usage" type="object">
  `input_tokens` と `output_tokens` を含む token 使用量。
</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>

## ビジョン入力の例

画像対応の Claude モデルでは、画像を `messages[].content` 内に構造化された画像ブロックとして配置してください。

```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..."
          }
        }
      ]
    }
  ]
}
```

## 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}")
```

## Anthropic メッセージバッチ

TokenLab では `/v1/messages` に加えて、Anthropic Message Batches のネイティブフローも提供しています。

利用できるルート：

* `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`

運用メモ：

* 同じ TokenLab API key と Anthropic ネイティブヘッダーを使用してください。
* batch item が `file_id` を参照する場合は、`anthropic-beta: files-api-2025-04-14` も付けてください。
* Batch job は Anthropic ネイティブのリクエスト/レスポンス形式を維持しつつ、TokenLab 側で内部の精算ライフサイクルを追跡します。
