我们针对 Claude 系列模型对 OpenAI 兼容接口进行了更深入的优化。现在你可以更精确、更便捷地控制思考和缓存。多轮对话中的交错思考也更加易用,无需额外参数即可无缝集成。同时,还支持启用 Anthropic 提供的 beta 功能。
1. 模型思考(Extended Thinking)
1.1 交错思考的优势
未启用交错思考时,模型只会在助手回合开始时进行一次思考;收到工具结果后,后续回复会直接生成,不会产生新的思考块:
User → [Thinking] → Tool Call → Tool Result → Response
启用交错思考后,模型每次收到工具结果时都会插入一个新的思考块,形成推理链:
User → [Thinking] → Tool Call → Tool Result → [Thinking] → Response
↑ Interleaved Thinking
这使模型能够:
- 基于工具结果进行二次推理,而不是简单拼接输出。
- 在多次工具调用之间进行链式推理,每个决策都基于上一步的分析。
参考:Anthropic 交错思考
1.2 启用思考
你可以通过以下四种方式之一启用思考,任选其一即可:
| 方式 | 示例 | 说明 |
|---|---|---|
reasoning_effort |
"reasoning_effort": "low" |
OpenAI 标准参数,置于请求体顶层 |
reasoning.effort |
"reasoning": {"effort": "low"} |
与前一种方式等效,置于 reasoning 对象内 |
reasoning.max_tokens |
"reasoning": {"max_tokens": 1024} |
精确控制思考的最大 token 数 |
模型名称加上 -think |
"model": "claude-sonnet-4-5-think" |
最简单的方式,无需额外参数 |
优先级(同时使用多种方式时):reasoning_effort>reasoning.max_tokens>reasoning.effort>-think后缀
effort 可选值: minimal / low / medium / high / xhigh
1.3 思考内容返回
响应消息将包含两个新字段:
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 原样放入下一轮的助手消息中:
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 完整示例
以下两个示例展示了完整的多轮工具调用 + 交错思考流程:用户提问 → 模型思考并调用工具 → 注入工具结果(保留 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+ 使用自适应思考(effort=medium);其他模型设置 budget_tokens = min(10240, max_tokens - 1),默认 max_tokens 为 4096。
2. 提示词缓存(Prompt Caching)
通过 Chat 接口请求 Claude 模型时,你可以使用提示词缓存。通过在消息中设置 cache_control 断点,可以缓存大段文本(如角色设定、RAG 数据、书籍章节等)以便重复使用,后续请求即可直接命中缓存,从而显著降低成本。
Claude 官方文档:Prompt Caching
2.1 缓存费用
| 操作 | 价格倍率(相对于原始输入价格) |
|---|---|
| 缓存写入(5 分钟 TTL) | 1.25x |
| 缓存写入(1 小时 TTL) | 2x |
| 缓存读取 | 0.1x |
2.2 支持的模型与最小缓存长度
| 模型 | 最小缓存 token 数 |
|---|---|
| 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 |
断点数量上限: 每个请求最多 4 个 cache_control 断点。2.3 缓存 TTL
| TTL | 语法 | 适用场景 |
|---|---|---|
| 5 分钟(默认) | "cache_control": {"type": "ephemeral"} |
短会话、常规请求 |
| 1 小时 | "cache_control": {"type": "ephemeral", "ttl": "1h"} |
长会话,避免重复写入缓存 |
1 小时 TTL 的写入费用更高,但在较长的会话中可以减少重复写入,从而节省总体开销。Claude 4.5 及之后的所有模型在各提供商(包括 Anthropic、Amazon Bedrock、Google Vertex AI)中均支持 1 小时 TTL。
2.4 用法
你可以在 system、user(包括图片)和 tools 中使用 cache_control 字段设置缓存断点。以下示例仅展示关键结构,省略了大段文本。
System 消息缓存(默认 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"}]
}
]
}
User 消息缓存(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 |
本次请求写入缓存的 token 数 |
cache_read_input_tokens |
本次请求从缓存读取的 token 数 |
cache_write_5_minutes_input_tokens |
写入 5 分钟 TTL 缓存的 token 数 |
cache_write_1_hour_input_tokens |
写入 1 小时 TTL 缓存的 token 数 |
prompt_tokens_details.cached_tokens |
缓存命中时的缓存 token 数,与 OpenAI 格式兼容 |
3. anthropic-beta 请求头
你可以通过 HTTP 请求头 anthropic-beta 启用 Claude 模型的 beta 功能,AIHubMix 会将其透传给 Anthropic API。
用法
在请求头中添加 anthropic-beta,值为对应 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"}]}
]
}'
具体可用的 beta 标识符,请参阅 Anthropic API 文档。
最后更新:2026-06-01



