LangGraph踩坑全解析:避坑指南与实战经验
在整合LangGraph与Qwen(通义千问)模型时,有几个隐蔽的坑几乎每次都会让新手翻车。下面拆解两个最典型的问题,并附上可直接套用的修复方案,省去反复调试的麻烦。
1. 当响应格式要求为 json_object 时
你当前的 System Prompt 是:
SystemMessage(content="Generate a plan for the report.")
里面完全没有 json → 于是报错!
如何修复?
只需在 SystemMessage 中显式加入 json 字样即可!
修复后的代码(仅改一行)
report_sections = planner.invoke([
# ✅ 添加 "JSON" 关键词,报错立刻消失
SystemMessage(content="Generate a plan for the report in valid JSON."),
HumanMessage(content=f"Here is the report topic: {state['topic']}"),
])
或者中文版本:
SystemMessage(content="生成报告计划,**必须输出 JSON 格式**。")
只要提示词中出现 json/JSON,错误瞬间消失!
为何 LangGraph 官方示例不报错?
官方示例使用 OpenAI,没有这个额外的校验规则。
Qwen / 阿里通义自带的限制:
- 开启
json_object→ 提示词中必须包含 json - 否则直接拒绝调用
你现在可以安全运行的完整代码
def orchestrator(state: State):
"""Orchestrator that generates a plan for the report"""
report_sections = planner.invoke([
# ✅ 修复:强制要求 JSON 格式输出
SystemMessage(content="Generate a plan for the report. Output response in JSON format."),
HumanMessage(content=f"Here is the report topic: {state['topic']}"),
])
return {"sections": report_sections.sections}
2. pydantic 字段类型校验失败
sections.0.nameField required
含义:你的 Sections 模型规定每个章节必须有 name 字段,但 Qwen 实际输出的是 title / section_number,缺少 name!
1. 先检查你的 Schema(根源所在)
class Section(BaseModel):
name: str # 你强制要求 name 字段
section_number: int
class Sections(BaseModel):
sections: list[Section]
而 Qwen 实际输出的是:
{
"section_number": 1,
"title": "Introduction" # 它输出 title,不是 name!
}
→ 字段不匹配 → 触发 ValidationError
2. 一键修复(二选一,立竿见影)
方案 A:将 Schema 改为 title(推荐,最稳妥)
class Section(BaseModel):
title: str # 改为 title
section_number: int
class Sections(BaseModel):
sections: list[Section]
方案 B:通过 Prompt 强制模型输出 name
SystemMessage(content="""Generate a plan for the report. Output response in JSON format.
Each section MUST have a field called "name", not "title"!""")
