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

# メッセージの作成（Claude）

> Claude CodeなどのAnthropicクライアント向けのClaudeネイティブメッセージインターフェース

## はじめに

Messages APIは、MixRouteを通じてAnthropic Claudeのネイティブインターフェースとの互換性を提供し、AnthropicのSDKやClaude Codeなどのツールを直接利用できるようにします。このインターフェースはAnthropicのAPI仕様に準拠し、拡張思考、ツール呼び出し、その他の高度な機能を含むClaudeモデルの全機能を提供します。

OpenAI互換クライアント（OpenAI SDKなど）を使用している場合は、代わりに`/v1/chat/completions`エンドポイントを使用することをおすすめします。

<Info>
  Claude Sonnet 5.5にはモデル固有の要件があります。適応型思考はデフォルトで有効です。最初の思考を無効にするには、effortをhigh以下にしてthinking.type=between\_toolsを使用してください。tool\_choice.typeにはany/toolではなくautoを使用し、ツールループでは思考ブロックと署名を完全な状態で保持してください。以前の例を再利用する前に、[Sonnet 5.5](/ja/model-api/anthropic/claude-sonnet-5-5)を確認してください。
</Info>

## 認証

Bearerトークン。例: `Bearer sk-xxxxxxxxxx`

## リクエストパラメーター

<ParamField body="model" type="string" required>
  Claudeのモデル識別子。例: `claude-opus-4-8`
</ParamField>

<ParamField body="messages" type="array" required>
  会話メッセージのリスト。各メッセージには`role`（user/assistant）と`content`が含まれます
</ParamField>

<ParamField body="max_tokens" type="integer" required>
  生成するトークンの最大数。0より大きい必要があります
</ParamField>

<ParamField body="system" type="string | array">
  システムプロンプト。文字列形式または配列形式（プロンプトキャッシュ用）をサポートします。
</ParamField>

<ParamField body="stream" type="boolean">
  ストリーミング出力を有効にする
</ParamField>

<ParamField body="temperature" type="number">
  サンプリング温度。範囲は0～1
</ParamField>

<ParamField body="top_p" type="number">
  Nucleusサンプリングのパラメーター。範囲は0～1
</ParamField>

<ParamField body="top_k" type="integer">
  Top-kサンプリングパラメータ
</ParamField>

<ParamField body="stop_sequences" type="array">
  カスタム停止シーケンス
</ParamField>

<ParamField body="thinking" type="object">
  拡張思考の設定。`type`と`budget_tokens`を含みます
</ParamField>

<ParamField body="tools" type="array">
  ツール定義の一覧
</ParamField>

## 基本的な例

<Tabs>
  <Tab title="非ストリーミングリクエスト">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "messages": [
          {"role": "user", "content": "Briefly explain artificial intelligence"}
        ]
      }'
    ```
  </Tab>

  <Tab title="ストリーミングリクエスト（SSE）">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "stream": true,
        "messages": [
          {"role": "user", "content": "Briefly explain artificial intelligence"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Pythonの例">
    ```python theme={null}
    from anthropic import Anthropic

    client = Anthropic(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.mixroute.ai"
    )

    # Non-streaming
    message = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "Briefly explain artificial intelligence"}
        ]
    )
    print(message.content[0].text)

    # Streaming
    with client.messages.stream(
        model="claude-opus-4-8",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "Briefly explain artificial intelligence"}
        ]
    ) as stream:
        for text_block in stream.text_stream:
            print(text_block, end="")
    ```
  </Tab>
</Tabs>

## 高度な機能

### システムプロンプト

<Tabs>
  <Tab title="文字列形式">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "system": "You are a professional programming assistant skilled at explaining complex technical concepts.",
        "messages": [
          {"role": "user", "content": "What is recursion?"}
        ]
      }'
    ```
  </Tab>

  <Tab title="配列形式">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "system": [
          {
            "type": "text",
            "text": "You are a professional programming assistant skilled at explaining complex technical concepts."
          }
        ],
        "messages": [
          {"role": "user", "content": "What is recursion?"}
        ]
      }'
    ```
  </Tab>
</Tabs>

### 拡張思考

<Tabs>
  <Tab title="基本的な使い方">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 16000,
        "thinking": {
          "type": "enabled",
          "budget_tokens": 10000
        },
        "messages": [
          {"role": "user", "content": "Provide a medium difficulty geometry problem and solve it step by step"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Pythonの例">
    ```python theme={null}
    from anthropic import Anthropic

    client = Anthropic(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.mixroute.ai"
    )

    with client.messages.stream(
        model="claude-opus-4-8",
        max_tokens=16000,
        thinking={
            "type": "enabled",
            "budget_tokens": 10000
        },
        messages=[
            {"role": "user", "content": "Provide a medium difficulty geometry problem and solve it step by step"}
        ]
    ) as stream:
        for event in stream:
            if event.type == "content_block_delta":
                if hasattr(event.delta, "thinking"):
                    print(f"[Thinking] {event.delta.thinking}", end="")
                elif hasattr(event.delta, "text"):
                    print(event.delta.text, end="")
    ```
  </Tab>
</Tabs>

### ツール

<Tabs>
  <Tab title="関数ツール">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "tools": [
          {
            "name": "get_weather",
            "description": "Get weather information for a city",
            "input_schema": {
              "type": "object",
              "properties": {
                "city": {
                  "type": "string",
                  "description": "City name"
                }
              },
              "required": ["city"]
            }
          }
        ],
        "messages": [
          {"role": "user", "content": "What is the weather like in Tokyo?"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Claude公式ウェブ検索ツール">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 4096,
        "tools": [
          {
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 5
          }
        ],
        "messages": [
          {"role": "user", "content": "What are the latest news about artificial intelligence?"}
        ]
      }'
    ```
  </Tab>
</Tabs>

### マルチモーダル入力（画像）

```bash theme={null}
curl -X POST "https://api.mixroute.ai/v1/messages" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-opus-4-8",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "image",
            "source": {
              "type": "base64",
              "media_type": "image/jpeg",
              "data": "base64_encoded_image_data"
            }
          },
          {
            "type": "text",
            "text": "Please describe this image"
          }
        ]
      }
    ]
  }'
```

### プロンプトキャッシュ

よく使用するコンテキストの内容をキャッシュすると、コストを大幅に削減し、応答速度を向上できます。キャッシュする内容には、最低1024トークンが必要です。

<Tabs>
  <Tab title="システムキャッシュ">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "system": [
          {
            "type": "text",
            "text": "You are a professional document analysis assistant. Here is the document content to analyze: [long text content, at least 1024 tokens]",
            "cache_control": {"type": "ephemeral"}
          }
        ],
        "messages": [
          {"role": "user", "content": "Please summarize the main points of the document"}
        ]
      }'
    ```
  </Tab>

  <Tab title="メッセージのキャッシュ">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/messages" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -H "anthropic-version: 2023-06-01" \
      -d '{
        "model": "claude-opus-4-8",
        "max_tokens": 1024,
        "messages": [
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": "Here is the codebase to analyze: [large code content, at least 1024 tokens]",
                "cache_control": {"type": "ephemeral"}
              },
              {
                "type": "text",
                "text": "Please identify potential issues in the code"
              }
            ]
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="Python SDKの例">
    ```python theme={null}
    from anthropic import Anthropic

    client = Anthropic(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.mixroute.ai"
    )

    # System cache
    message = client.messages.create(
        model="claude-opus-4-8",
        max_tokens=1024,
        system=[
            {
                "type": "text",
                "text": "You are a professional document analysis assistant. Here is the document content to analyze: [long text content]",
                "cache_control": {"type": "ephemeral"}
            }
        ],
        messages=[
            {"role": "user", "content": "Please summarize the main points of the document"}
        ]
    )

    # Check cache usage
    print(f"Cache creation tokens: {message.usage.cache_creation_input_tokens}")
    print(f"Cache read tokens: {message.usage.cache_read_input_tokens}")
    ```
  </Tab>
</Tabs>

## レスポンス形式

<Tabs>
  <Tab title="非ストリーミングレスポンス">
    ```json theme={null}
    {
      "id": "msg_xxx",
      "type": "message",
      "role": "assistant",
      "content": [
        {
          "type": "text",
          "text": "Response content..."
        }
      ],
      "model": "claude-opus-4-8",
      "stop_reason": "end_turn",
      "usage": {
        "input_tokens": 25,
        "output_tokens": 100,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0
      }
    }
    ```
  </Tab>

  <Tab title="ストリーミングレスポンス">
    ```text theme={null}
    event: message_start
    data: {"type":"message_start","message":{"id":"msg_xxx","type":"message","role":"assistant","content":[],"model":"claude-opus-4-8"}}

    event: content_block_start
    data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Response"}}

    event: content_block_delta
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" content"}}

    event: content_block_stop
    data: {"type":"content_block_stop","index":0}

    event: message_delta
    data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":100}}

    event: message_stop
    data: {"type":"message_stop"}
    ```
  </Tab>
</Tabs>

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.mixroute.ai/v1/messages \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --header 'anthropic-version: 2023-06-01' \
    --data '{
      "model": "claude-opus-4-8",
      "max_tokens": 1024,
      "messages": [
        {"role": "user", "content": "Briefly explain artificial intelligence"}
      ]
    }'
  ```

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

  client = Anthropic(
      api_key="sk-xxxxxxxxxx",
      base_url="https://api.mixroute.ai"
  )

  message = client.messages.create(
      model="claude-opus-4-8",
      max_tokens=1024,
      messages=[
          {"role": "user", "content": "Briefly explain artificial intelligence"}
      ]
  )
  print(message.content[0].text)
  ```

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

  const client = new Anthropic({
    apiKey: 'sk-xxxxxxxxxx',
    baseURL: 'https://api.mixroute.ai'
  });

  const message = await client.messages.create({
    model: 'claude-opus-4-8',
    max_tokens: 1024,
    messages: [
      { role: 'user', content: 'Briefly explain artificial intelligence' }
    ]
  });
  console.log(message.content[0].text);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1/messages', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
          'anthropic-version' => '2023-06-01',
      ],
      'json' => [
          'model' => 'claude-opus-4-8',
          'max_tokens' => 1024,
          'messages' => [
              ['role' => 'user', 'content' => 'Briefly explain artificial intelligence']
          ]
      ]
  ]);
  echo $response->getBody();
  ```

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

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

  func main() {
      payload := map[string]interface{}{
          "model": "claude-opus-4-8",
          "max_tokens": 1024,
          "messages": []map[string]string{
              {"role": "user", "content": "Briefly explain artificial intelligence"},
          },
      }
      body, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", "https://api.mixroute.ai/v1/messages", bytes.NewBuffer(body))
      req.Header.Set("Authorization", "Bearer sk-xxxxxxxxxx")
      req.Header.Set("Content-Type", "application/json")
      req.Header.Set("anthropic-version", "2023-06-01")
      http.DefaultClient.Do(req)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  String json = """
      {
          "model": "claude-opus-4-8",
          "max_tokens": 1024,
          "messages": [{"role": "user", "content": "Briefly explain artificial intelligence"}]
      }
      """;
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1/messages"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .header("Content-Type", "application/json")
      .header("anthropic-version", "2023-06-01")
      .POST(HttpRequest.BodyPublishers.ofString(json))
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1/messages')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'
  request['Content-Type'] = 'application/json'
  request['anthropic-version'] = '2023-06-01'
  request.body = {
    model: 'claude-opus-4-8',
    max_tokens: 1024,
    messages: [{ role: 'user', content: 'Briefly explain artificial intelligence' }]
  }.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "msg_xxx",
    "type": "message",
    "role": "assistant",
    "content": [
      {
        "type": "text",
        "text": "Artificial intelligence is a new technical science that researches and develops theories, methods, technologies, and application systems for simulating, extending, and expanding human intelligence..."
      }
    ],
    "model": "claude-opus-4-8",
    "stop_reason": "end_turn",
    "stop_sequence": null,
    "usage": {
      "input_tokens": 25,
      "output_tokens": 100
    }
  }
  ```
</ResponseExample>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.