LangChain中如何启用和使用大模型的“推理/思维链”功能

对于支持思考/推理模式的模型,在ChatOllama可以通过在构造函数或 invoke/stream 方法中将 reasoning 参数设置为 True 来启用推理模式。这将允许模型通过思考来解决问题,并将推理过程作为单独的内容返回在响应消息的 additional_kwargs 中,具体键名为 reasoning_content

model_1 = ChatOllama(
            model="qwen3:4b",
            reasoning=True,
        )
result_1 = model.invoke("0 1 4 9 16 这几个数字有什么规律")
print(result_1)

model_2 = ChatOllama(
            model="qwen3:4b",
        )
result_2 = model_2.invoke("0 1 4 9 16 这几个数字有什么规律", reasoning=True)
print(result_2)

  如果 reasoning 被设置为 None,模型将使用其默认的推理行为,此时任何推理内容不会被收录在 reasoning_content 键下

       reasoning 还可以设置为str类型,例如 'low'、'medium'、'high',这仅支持具有自定义强度级别的推理 gpt-oss

在ChatOpenAI中也是通过配置reasoning来实现思考链,effort: 推理深度(low/medium/high)、summary: 摘要粒度(detailed/auto/None)

from langchain_openai import ChatOpenAI

# 配置推理参数
reasoning = {
    "effort": "medium",  # 推理深度
    "summary": "auto",   # 摘要自动模式
}

# 初始化模型(必须指定 output_version)
model = ChatOpenAI(
    model="gpt-4o",  # 需替换为支持推理的实际模型
    reasoning=reasoning,
    output_version="responses/v1"  # 关键:启用推理输出
)

# 调用模型
response = model.invoke("What is 3^3?")

# 打印最终回答
print(f"Output: {response.text}")  # Output: 3³ = 27

# 提取推理摘要
for block in response.content:
    if block["type"] == "reasoning":  # 识别推理块
        for summary in block["summary"]:
            print(f"Reasoning: {summary['text']}")

  

  

posted @ 2026-01-14 23:35  干瘪咸鱼  阅读(89)  评论(0)    收藏  举报