OpenAI互換インターフェースのアップグレード:Claudeへの深いサポート

AIHubMixは、Claude向けのOpenAI互換APIをアップグレードしました。追加パラメータなしのインターリーブド・シンキング、プロンプトキャッシュ、Anthropicのベータ機能サポートに対応しています。

AIHubMix約 8 分で読めます
OpenAI互換インターフェースのアップグレード:Claudeへの深いサポート

OpenAI互換インターフェースを、Claudeシリーズのモデルに特化して深く最適化しました。これにより、思考(thinking)とキャッシュをより正確かつ簡単に制御できるようになりました。マルチターン会話におけるインターリーブド・シンキングも使いやすくなり、追加パラメータなしでシームレスに統合できます。また、Anthropicが提供するベータ機能の有効化にも対応しています。

1. モデルの思考(Extended Thinking)

1.1 インターリーブド・シンキングの利点

インターリーブド・シンキングが無効の場合、モデルはアシスタントのターンの最初に一度だけ思考を行います。その後の応答はツール結果を受け取った後に直接生成され、新たな思考ブロックは生成されません。

User → [Thinking] → Tool Call → Tool Result → Response

インターリーブド・シンキングが有効の場合、モデルはツール結果を受け取るたびに新しい思考ブロックを挿入し、推論の連鎖を形成します。

User → [Thinking] → Tool Call → Tool Result → [Thinking] → Response
                                                ↑ Interleaved Thinking

これにより、モデルは次のことができます。

  • ツール結果に基づく二次的な推論を行う。単に出力を連結するのではありません。
  • 複数のツール呼び出しの間で推論を連鎖させる。各判断は前のステップの分析に基づきます。
参考:Anthropic Interleaved Thinking

1.2 思考の有効化

思考は次の4つの方法のいずれかで有効にできます。

方法 例 説明
reasoning_effort "reasoning_effort": "low" OpenAI標準パラメータ。リクエストボディのトップレベルに配置します
reasoning.effort "reasoning": {"effort": "low"} 前の方法と同等。reasoningオブジェクト内に配置します
reasoning.max_tokens "reasoning": {"max_tokens": 1024} 思考に使用するトークンの最大数を正確に制御します
モデル名に-thinkを付与 "model": "claude-sonnet-4-5-think" 最も簡単な方法で、追加パラメータは不要です
優先順位(複数の方法を使用する場合):reasoning_effort > reasoning.max_tokens > reasoning.effort > -thinkサフィックス

effortの指定可能な値: minimal / low / medium / high / xhigh

1.3 思考の返却

レスポンスのメッセージには、2つの新しいフィールドが含まれます。

  • reasoning_content:思考の内容(文字列)。表示に便利です。
  • reasoning_details:思考に関する完全な構造化情報。マルチターン会話では、そのまま返却する必要があります。内部構造はプロバイダーによって異なる場合があります。

非ストリーミングの例(無関係なフィールドは省略):

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you today?",
      "reasoning_content": "The user is just saying hello...",
      "reasoning_details": {
        "type": "thinking",
        "thinking": "The user is just saying hello...",
        "signature": "Er8CCkYI..."
      }
    }
  }]
}

ストリーミングレスポンスでは、思考の内容はdelta.reasoning_contentとdelta.reasoning_detailsを通じて分割して送信されます。ストリーミングの完全な連結ロジックについては、以下の完全な例を参照してください。

1.4 マルチターン会話での思考の保持 (インターリーブド・シンキングは組み込み済みで、追加パラメータは不要です)

マルチターン会話でモデルが推論能力を維持できるように、以前に返されたreasoning_detailsをそのまま次のラウンドのassistantメッセージに含めるだけです。

messages = [
    {"role": "user", "content": "What's the weather like in Boston?"},
    {
        "role": "assistant",
        "content": response.choices[0].message.content,
        "tool_calls": response.choices[0].message.tool_calls,
        "reasoning_details": response.choices[0].message.reasoning_details,
    },
    {
        "role": "tool",
        "tool_call_id": "toolu_xxx",
        "content": '{"temperature": 45, "condition": "rainy"}',
    }
]

リクエスト内に過去の思考情報が含まれていることを検出すると、AIHubMixはインターリーブド・シンキングを自動的に有効にします。これにより、追加パラメータなしで、ツール呼び出しの結果を受け取った後もモデルは深い推論を続けられます。

1.5 完全な例

以下の2つの例は、マルチターンのツール呼び出し+インターリーブド・シンキングの完全な流れを示しています。ユーザーの問い合わせ → モデルが思考してツールを呼び出す → ツール結果を注入(reasoning_detailsを保持)→ モデルがインターリーブド・シンキングを経て最終的な応答を返す。

非ストリーミング・インターリーブド・シンキング

import os
import json
from openai import OpenAI

client = OpenAI(
    base_url="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)

# ── Tool definition ───────────────────────────────────────────
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "City name"}},
            "required": ["location"]
        }
    }
}]

# ── Mock tool execution ───────────────────────────────────────
WEATHER_DB = {
    "boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
    "tokyo":  {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}

def execute_tool(name: str, args: dict) -> str:
    if name == "get_weather":
        key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
        return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
    return "{}"

# ── Multi-turn conversation loop ─────────────────────────────
messages = [
    {"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]

turn = 0
while True:
    turn += 1
    print(f"\n── Turn {turn} ──")

    response = client.chat.completions.create(
        model="claude-sonnet-4-5",
        messages=messages,
        tools=tools,
        extra_body={"reasoning": {"max_tokens": 2000}},
    )
    msg = response.choices[0].message

    # Print thinking process
    if msg.reasoning_content:
        label = "Interleaved Thinking" if turn > 1 else "Thinking"
        print(f"[{label}] {msg.reasoning_content}")

    # Print response content
    if msg.content:
        print(f"[Response] {msg.content}")

    # Print tool calls
    if msg.tool_calls:
        for tc in msg.tool_calls:
            print(f"[Tool Call: {tc.function.name}] {tc.function.arguments}")

    # Build assistant message, preserve reasoning_details (critical!)
    assistant_msg = {"role": "assistant", "content": msg.content}
    if msg.tool_calls:
        assistant_msg["tool_calls"] = msg.tool_calls
    if msg.reasoning_details:
        assistant_msg["reasoning_details"] = msg.reasoning_details  # pass back unmodified
    messages.append(assistant_msg)

    # No tool_calls means conversation is done
    if not msg.tool_calls:
        break

    # Execute tools and append results to messages
    for tc in msg.tool_calls:
        args = json.loads(tc.function.arguments)
        result = execute_tool(tc.function.name, args)
        print(f"[Tool Result: {tc.function.name}] {result}")
        messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})

ストリーミング・インターリーブド・シンキング

import os
import sys
import json
from openai import OpenAI

client = OpenAI(
    base_url="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)

# ── Tool definition & mock execution ─────────────────────────
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "City name"}},
            "required": ["location"]
        }
    }
}]

WEATHER_DB = {
    "boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
    "tokyo":  {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}

def execute_tool(name: str, args: dict) -> str:
    if name == "get_weather":
        key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
        return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
    return "{}"

# ── Stream response collector ────────────────────────────────
def stream_and_collect(turn: int, **kwargs):
    """Stream response, print thinking/content in real-time, accumulate reasoning_details/tool_calls."""
    rd = {}            # accumulated reasoning_details
    content = ""       # accumulated response text
    tc_map = {}        # accumulated tool_calls (by index)
    cur = "none"       # current output section: none / thinking / content

    stream = client.chat.completions.create(stream=True, **kwargs)
    for chunk in stream:
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta

        # ── Handle thinking ──
        rd_delta = getattr(delta, "reasoning_details", None)
        if rd_delta and isinstance(rd_delta, dict):
            for k, v in rd_delta.items():
                if k == "type":
                    rd[k] = v
                elif isinstance(v, str):
                    rd[k] = rd.get(k, "") + v
                elif v is not None:
                    rd[k] = v
            # Print thinking chunks in real-time
            thinking_chunk = rd_delta.get("thinking", "")
            if thinking_chunk:
                if cur != "thinking":
                    cur = "thinking"
                    label = "Interleaved Thinking" if turn > 1 else "Thinking"
                    sys.stdout.write(f"\n[{label}] ")
                sys.stdout.write(thinking_chunk)
                sys.stdout.flush()

        # ── Handle content ──
        if delta.content:
            if cur != "content":
                if cur == "thinking":
                    sys.stdout.write("\n")
                cur = "content"
                sys.stdout.write("\n[Response] ")
            sys.stdout.write(delta.content)
            sys.stdout.flush()
            content += delta.content

        # ── Handle tool_calls ──
        for tc in delta.tool_calls or []:
            i = tc.index
            if i not in tc_map:
                tc_map[i] = {"id": "", "type": "function",
                             "function": {"name": "", "arguments": ""}}
            if tc.id:
                tc_map[i]["id"] = tc.id
            if tc.function:
                tc_map[i]["function"]["name"] += tc.function.name or ""
                tc_map[i]["function"]["arguments"] += tc.function.arguments or ""

    # End current output section
    if cur in ("thinking", "content"):
        sys.stdout.write("\n")

    tool_calls = [tc_map[i] for i in sorted(tc_map)] if tc_map else None
    return {
        "content": content or None,
        "reasoning_details": rd or None,
        "tool_calls": tool_calls,
    }

# ── Multi-turn conversation loop ─────────────────────────────
messages = [
    {"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]

turn = 0
while True:
    turn += 1
    print(f"\n── Turn {turn} ──")

    result = stream_and_collect(
        turn,
        model="claude-sonnet-4-5",
        messages=messages,
        tools=tools,
        extra_body={"reasoning": {"max_tokens": 2000}},
    )

    # Print tool calls
    if result["tool_calls"]:
        for tc in result["tool_calls"]:
            print(f"[Tool Call: {tc['function']['name']}] {tc['function']['arguments']}")

    # Build assistant message, preserve reasoning_details (critical!)
    assistant_msg = {"role": "assistant", "content": result["content"]}
    if result["tool_calls"]:
        assistant_msg["tool_calls"] = result["tool_calls"]
    if result["reasoning_details"]:
        assistant_msg["reasoning_details"] = result["reasoning_details"]  # pass back unmodified
    messages.append(assistant_msg)

    # No tool_calls means conversation is done
    if not result["tool_calls"]:
        break

    # Execute tools and append results to messages
    for tc in result["tool_calls"]:
        args = json.loads(tc["function"]["arguments"])
        tool_result = execute_tool(tc["function"]["name"], args)
        print(f"[Tool Result: {tc['function']['name']}] {tool_result}")
        messages.append({"role": "tool", "tool_call_id": tc["id"], "content": tool_result})

1.6 思考の強度マッピングルール

Effortモード:

  • Opus 4.6 / Sonnet 4.6以降:AnthropicネイティブのAdaptive Thinkingのeffortレベルにマッピングされます。
  • その他のモデル:budget_tokensの計算式を使用して算出されます:
budget_tokens = max(min(max_tokens × effort_ratio, 128000), 1024)
effort effort_ratio
xhigh 0.95
high 0.80
medium 0.50
low 0.20
minimal 0.10

Adaptive Thinkingのeffortマッピング:

受信したEffort Opus 4.6 Sonnet 4.6
xhigh max high
high high high
medium medium medium
low low low
minimal low low

max_tokensモード: Anthropicのbudget_tokensとして直接割り当てられます。

-think サフィックス: Opus/Sonnet 4.6以降はadaptive thinking(effort=medium)を使用します。その他のモデルはbudget_tokens = min(10240, max_tokens - 1)に設定され、max_tokensのデフォルトは4096です。


2. プロンプトキャッシュ

Chatインターフェース経由でClaudeモデルにリクエストを送信する際、プロンプトキャッシュを使用できます。messages内にcache_controlのブレークポイントを設定することで、大きなテキストブロック(ロールカード、RAGデータ、書籍の章など)をキャッシュして再利用できます。これにより、後続のリクエストはキャッシュに直接ヒットし、コストを大幅に削減できます。

Claude公式ドキュメント:Prompt Caching

2.1 キャッシュのコスト

操作 価格倍率(元の入力価格に対する比率)
キャッシュ書き込み(5分TTL) 1.25x
キャッシュ書き込み(1時間TTL) 2x
キャッシュ読み取り 0.1x

2.2 対応モデルと最小キャッシュ長

モデル 最小キャッシュトークン数
Claude Opus 4.8 1024
Claude Opus 4.7 2048
Claude Opus 4.6 / Opus 4.5 4096
Claude Sonnet 4.6 / Sonnet 4.5 / Opus 4.1 / Opus 4 / Sonnet 4 / Sonnet 3.7(非推奨) 1024
Claude Haiku 4.5 4096
Claude Haiku 3.5(非推奨)/ Haiku 3 2048
ブレークポイント数の上限: 1リクエストあたり最大4個のcache_controlブレークポイント。

2.3 キャッシュTTL

TTL 構文 適用シナリオ
5分(デフォルト) "cache_control": {"type": "ephemeral"} 短いセッション、通常のリクエスト
1時間 "cache_control": {"type": "ephemeral", "ttl": "1h"} 長いセッション、繰り返しのキャッシュ書き込みを避けたい場合

1時間TTLの書き込みコストは高くなりますが、長いセッションで繰り返し書き込みを減らすことで、総費用を節約できる場合があります。すべてのプロバイダー(Anthropic、Amazon Bedrock、Google Vertex AIを含む)のClaude 4.5以降のモデルは、1時間TTLに対応しています。

2.4 使い方

system、user(画像を含む)、tools内のcache_controlフィールドを使用してキャッシュブレークポイントを設定できます。以下の例では、キー構造のみを示し、大きなテキストブロックは省略しています。

システムメッセージのキャッシュ(デフォルトは5分TTL):

{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [
        {"type": "text", "text": "You are an AI assistant"},
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {
      "role": "user",
      "content": [{"type": "text", "text": "Hello"}]
    }
  ]
}

ユーザーメッセージのキャッシュ(1時間TTL):

{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [{"type": "text", "text": "You are an AI assistant"}]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral", "ttl": "1h"}
        },
        {"type": "text", "text": "Hello"}
      ]
    }
  ]
}

画像メッセージのキャッシュ:

{
  "role": "user",
  "content": [
    {
      "type": "image_url",
      "image_url": {"detail": "auto", "url": "data:image/jpeg;base64,/9j/4AAQ..."},
      "cache_control": {"type": "ephemeral"}
    },
    {"type": "text", "text": "What's this?"}
  ]
}

ツール定義のキャッシュ:

cache_controlは、ツールオブジェクトのトップレベルに配置します(typeおよびfunctionと同じ階層):

{
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "parameters": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    },
    "cache_control": {"type": "ephemeral", "ttl": "1h"}
  }]
}

2.5 キャッシュ状態の確認

レスポンスのusageには、詳細なキャッシュ情報を記録したclaude_cache_tokens_detailsが含まれます。

初回リクエスト(キャッシュの作成):

{
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 890,
    "total_tokens": 912,
    "claude_cache_tokens_details": {
      "cache_creation_input_tokens": 6266,
      "cache_read_input_tokens": 0,
      "cache_write_5_minutes_input_tokens": 6266,
      "cache_write_1_hour_input_tokens": 0
    }
  }
}

後続のリクエスト(キャッシュヒット):

{
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 810,
    "total_tokens": 832,
    "prompt_tokens_details": {
      "cached_tokens": 6266
    },
    "claude_cache_tokens_details": {
      "cache_creation_input_tokens": 0,
      "cache_read_input_tokens": 6266,
      "cache_write_5_minutes_input_tokens": 0,
      "cache_write_1_hour_input_tokens": 0
    }
  }
}
フィールド 意味
cache_creation_input_tokens このリクエストでキャッシュに書き込まれたトークン数
cache_read_input_tokens このリクエストでキャッシュから読み取られたトークン数
cache_write_5_minutes_input_tokens 5分TTLのキャッシュに書き込まれたトークン数
cache_write_1_hour_input_tokens 1時間TTLのキャッシュに書き込まれたトークン数
prompt_tokens_details.cached_tokens キャッシュヒット時のキャッシュ済みトークン数。OpenAI形式と互換性があります

3. anthropic-betaのリクエストヘッダー

HTTPヘッダーanthropic-betaを使用して、Claudeモデルのベータ機能を有効にできます。AIHubMixはこの値をAnthropic APIにそのまま渡します。

使い方

リクエストヘッダーにanthropic-betaを追加し、値に対応するベータ機能の識別子を指定します。

curl "https://aihubmix.com/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AIHUBMIX_API_KEY" \
  -H "anthropic-beta: context-1m-2025-08-07" \
  -d '{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [
        {"type": "text", "text": "You are an AI assistant"},
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {"role": "user", "content": [{"type": "text", "text": "hello"}]}
  ]
}'
利用可能なベータ識別子の詳細は、Anthropic APIドキュメントを参照してください。

最終更新日:2026-06-01

ひとつのゲートウェイで複数のAIプロバイダーへ。 本番運用のために設計。

AIHubMix公式サイトへ