菜鸟AI - 让提示词生成更简单! 全站导航 全站导航
AI工具安装 新手教程 进阶教程 辅助资源 AI提示词 热点资讯 技术资讯 产业资讯 内容生成 模型技术 AI信息库

已有账号?

首页 > AI教程 > LangGraph踩坑全解析:避坑指南与实战经验
进阶教程 避坑

LangGraph踩坑全解析:避坑指南与实战经验

2026-06-03
阅读 0
热度 0
作者 菜鸟AI编辑部
摘要

摘要

在整合LangGraph与Qwen(通义千问)模型时,有几个隐蔽的坑几乎每次都会让新手翻车。下面

在整合LangGraph与Qwen(通义千问)模型时,有几个隐蔽的坑几乎每次都会让新手翻车。下面拆解两个最典型的问题,并附上可直接套用的修复方案,省去反复调试的麻烦。

1. 当响应格式要求为 json_object 时

你当前的 System Prompt 是:

Langgraph踩坑记录

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"!""")

来源:互联网

免责声明

本网站新闻资讯均来自公开渠道,力求准确但不保证绝对无误,内容观点仅代表作者本人,与本站无关。若涉及侵权,请联系我们处理。本站保留对声明的修改权,最终解释权归本站所有。

同类文章推荐

相关文章推荐

更多