Claude 延伸思考
本頁說明如何開啟 Claude 的延伸思考並讀取思考內容。模型 ID 與介面位址請見 Claude 系列概覽。
重點原生介面傳入 thinking,OpenAI 相容介面傳入 reasoning 物件。開啟思考時請勿設定 temperature。
延伸思考讓模型在回答前先進行推理,適合數學、程式碼與多步驟分析。實測以下模型在預設供應商下可穩定回傳思考內容:Opus 5.5、Opus 5、Opus 4.8、Opus 4.6、Sonnet 4.6、Haiku 5.5、Haiku 4.5、Fable 5。
Anthropic 原生介面
兩種模式:
Python
claude_thinking.py
import os
import anthropic
client = anthropic.Anthropic(base_url="https://api.ofox.io/anthropic", api_key=os.environ["OFOX_API_KEY"])
message = client.messages.create(
model="anthropic/claude-opus-5.5",
max_tokens=4000,
thinking={"type": "enabled", "budget_tokens": 2000},
messages=[{"role": "user", "content": "球拍和球共 1.10 美元,球拍比球貴 1 美元,球多少錢?"}],
)
for block in message.content:
if block.type == "thinking":
print("[思考]", block.thinking)
elif block.type == "text":
print("[回答]", block.text)- 回應的
content中會先出現thinking區塊,再出現text區塊。thinking區塊帶有signature,在多輪工具呼叫中需原樣傳回。 - 串流輸出時,思考內容透過
thinking_delta事件回傳,接著是一個signature_delta事件,然後才開始text_delta。 - 開啟思考時請勿設定
temperature(或設為 1),也不要設定top_k。 - 思考消耗的 token 計入
output_tokens,依輸出單價計費。
OpenAI 相容介面
透過 reasoning 物件開啟,max_tokens 為思考預算:
claude_thinking_openai.py
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ofox.io/v1", api_key=os.environ["OFOX_API_KEY"])
resp = client.chat.completions.create(
model="anthropic/claude-sonnet-4.6",
max_tokens=4000,
extra_body={"reasoning": {"max_tokens": 2000}},
messages=[{"role": "user", "content": "球拍和球共 1.10 美元,球拍比球貴 1 美元,球多少錢?"}],
)
msg = resp.choices[0].message
details = getattr(msg, "reasoning_details", None) or []
print("[思考]", "".join(d.get("text", "") for d in details))
print("[回答]", msg.content)- 非串流回應中,思考內容位於
message.reasoning_details,請將各項的text依序串接。 - 串流回應中,思考內容位於
delta.reasoning_content。
其他錯誤請見常見錯誤。
最後更新於