跳到主要内容

扩展思考(Extended Thinking)

扩展思考让模型在回答前深度推理,适合复杂数学、逻辑和分析任务。

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://www.cheapertoken.work")

response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "请证明根号2是无理数"}]
)

for block in response.content:
if block.type == "thinking":
print("思考过程:")
print(block.thinking)
elif block.type == "text":
print("回答:")
print(block.text)

流式扩展思考

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://www.cheapertoken.work")

with client.messages.stream(
model="claude-opus-4-7",
max_tokens=16000,
thinking={"type": "enabled", "budget_tokens": 8000},
messages=[{"role": "user", "content": "分析这个商业计划的优缺点:..."}]
) as stream:
for event in stream:
if hasattr(event, "type"):
if event.type == "content_block_start" and hasattr(event.content_block, "type"):
if event.content_block.type == "thinking":
print("\n[思考中...]")
elif event.type == "content_block_delta":
if hasattr(event.delta, "thinking"):
print(event.delta.thinking, end="", flush=True)
elif hasattr(event.delta, "text"):
print(event.delta.text, end="", flush=True)

budget_tokens 最小 1024,max_tokens 必须大于 budget_tokens