当前位置: 首页 > news >正文

16.修正 LangGraph Agent 的路由层,让 Router 真正只负责选工具

目 录

    • 1. 今天做了什么
    • 2. 核心变化
    • 3. 一个关键问题
    • 4. 当前系统能力

1. 今天做了什么

昨天的测试日志有暴露出问题:路由在选择工具和提取用户问题的时候回在半路就将用户的问题给回答了,所以今天要做的是给路由增加约束条件避免中途回答用户问题。

2. 核心变化

首先是在node.py中增加两个小工具,这两个小工具一个负责给出更规范的json字典,另一个负责给工具选择结果加强约束,如果是ragllmtime这三类,默认都把原始 query 继续传下去。

defclean_json_text(text:str)->str:text=text.strip()iftext.startswith("```json"):text=text.removeprefix("```json").strip()eliftext.startswith("```"):text=text.removeprefix("```").strip()iftext.endswith("```"):text=text.removesuffix("```").strip()returntextdefnormalize_decision(decision:dict,query:str,valid_tool_names:set[str])->dict:ifnotisinstance(decision,dict):return{"tool":"llm","input":query}tool=str(decision.get("tool","")).strip().lower()tool_input=str(decision.get("input","")).strip()iftoolnotinvalid_tool_names:return{"tool":"llm","input":query}# 关键规则:# 对 rag / llm / time 这三类,默认都把原始 query 继续传下去,# 不允许 router 自己现编一个答案塞进 input。iftoolin{"rag","llm","time"}:return{"tool":tool,"input":query}# calculator 允许保留模型抽出来的表达式iftool=="calculator":ifnottool_input:return{"tool":"calculator","input":query}return{"tool":"calculator","input":tool_input}return{"tool":"llm","input":query}

3. 一个关键问题

  • 问题是什么:路由会提前回答问题原因是由于工具选择node的约束不够强,所以导致大模型自己回答了问题。
  • 怎么解决的:做更强的提示词工程,增加一些约束条件,约束模型的返回结果。
defbuild_choose_tool_node(tools:list[dict[str,Any]]):valid_tool_names={t["name"]fortintools}defchoose_tool_node(state:AgentState)->AgentState:query=state["query"]logger.info(f"[choose_tool_node] query:{query}")tool_desc="\n".join([f"{t['name']}:{t['description']}"fortintools])prompt=f""" You are a tool router. Your job is ONLY to choose the best tool and prepare its input. Do NOT answer the user's question. Do NOT rewrite the user's question into an answer. Return JSON only. Available tools:{tool_desc}Rules: 1. You must return exactly one JSON object. 2. JSON format: {{"tool": "...", "input": "..."}} 3. tool must be one of: rag, calculator, time, llm 4. For rag, llm, and time: - input should stay the same as the user's original question - do not invent a new sentence 5. For calculator: - input should be the math expression only if you can extract it 6. Do not include markdown, explanations, or code fences. User question:{query}"""content=""try:response=client.chat.completions.create(model=CHAT_MODEL,messages=[{"role":"user","content":prompt}])content=response.choices[0].message.content cleaned=clean_json_text(content)raw_decision=json.loads(cleaned)decision=normalize_decision(raw_decision,query,valid_tool_names)logger.info(f"[choose_tool_node] raw decision:{raw_decision}")logger.info(f"[choose_tool_node] normalized decision:{decision}")return{"decision":decision}exceptExceptionase:logger.exception("choose_tool_node failed")return{"decision":{"tool":"llm","input":query},"error":f"choose_tool_node failed:{str(e)}"}returnchoose_tool_node

4. 当前系统能力

通过上述一层在提示词上的约束,以及一层正则约束,路由系统不会再半路回答用户的问题。

如果这篇文章对你有帮助,可以点个赞~
完整代码地址:https://github.com/1186141415/LangChain-for-A-Paper-Rag-Agent

http://www.jsqmd.com/news/647599/

相关文章:

  • 跨境电商商品采集skill来了,可部署openclaw,不用Python也能搞定爬虫
  • 为什么Redis的KEYS命令在生产环境是禁止使用的?
  • 运维工程师最后的护城河正在崩塌?:多模态大模型自动解析监控截图、语音工单、异常堆栈的3层可信推理机制
  • 网络运维Windows Server管理
  • 计算机毕业设计:Python全国降水数据采集与预警平台 Flask框架 数据分析 可视化 大数据 AI 大模型 爬虫 数据大屏(建议收藏)✅
  • 便携式综合气象观测仪
  • NLP学习笔记03:文本分类——从 TF-IDF 到 BERT
  • 嵌入式学习day3:数组与结构体
  • 【独家首发】央企信创云实战:基于Qwen-VL与InternVL的多模态运维Agent(已通过等保2.0三级认证)
  • CodeQ 项目数据库设计
  • 数学建模研究者可通过爱毕业(aibiye)快速实现论文复现与自动化排版
  • amcl_pose vs tf的位姿输出频率
  • SpringBoot入门核心要点
  • 零知识证明系统:zk-SNARK协议的工作原理与构造
  • 基于MPC模型预测控制的风电与储能调频策略:实时调整风电出力,仿真对比展现优越性
  • 【GitHub项目推荐--Plane:开源版 JIRA,让项目管理回归“有序”】⭐⭐⭐
  • 负载因子才0.5,unordered_map就有30%的桶在碰撞——读libstdc++源码看懂Google为什么要造absl::flat_hash_map
  • Web 品质可读性
  • Spring Data 2027 高级查询技巧:构建高效的数据访问层
  • 构建垂直领域专家级AI Agent的方法论
  • Windows系统iPhone USB网络共享驱动终极安装与优化指南
  • SMRT借助AI与数据分析技术预测轨道故障并提升维护效率
  • 从阻容复位到专用芯片:以MAX706为例,解析MCU看门狗复位电路的设计升级
  • C语言完美演绎8-3
  • Linux 安全加固:从攻击链反推,把每道门都锁上
  • Redis 慢查询优化与内存分配调优
  • 突发大洗牌!Claude强制“刷脸+护照”实名,GPT与Gemini全面封杀进入倒计时?
  • 金三银四上云季:阿里云服务器选购终极指南(附内部85折扣通道)
  • 【架构分享】多浏览器并发 RPA 中的状态同步与会话持久化:构建高可用电商运营流水线
  • VN1640A硬件实战:深入CANoe采样点(Sample Point)与位时序(BTL Cycles)配置原理