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

张开发
2026/4/16 1:11:11 15 分钟阅读

分享文章

16.修正 LangGraph Agent 的路由层,让 Router 真正只负责选工具
目 录1. 今天做了什么2. 核心变化3. 一个关键问题4. 当前系统能力1. 今天做了什么昨天的测试日志有暴露出问题路由在选择工具和提取用户问题的时候回在半路就将用户的问题给回答了所以今天要做的是给路由增加约束条件避免中途回答用户问题。2. 核心变化首先是在node.py中增加两个小工具这两个小工具一个负责给出更规范的json字典另一个负责给工具选择结果加强约束如果是rag、llm、time这三类默认都把原始 query 继续传下去。defclean_json_text(text:str)-str:texttext.strip()iftext.startswith(json):texttext.removeprefix(json).strip()eliftext.startswith():texttext.removeprefix().strip()iftext.endswith():texttext.removesuffix().strip()returntextdefnormalize_decision(decision:dict,query:str,valid_tool_names:set[str])-dict:ifnotisinstance(decision,dict):return{tool:llm,input:query}toolstr(decision.get(tool,)).strip().lower()tool_inputstr(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 允许保留模型抽出来的表达式iftoolcalculator: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:querystate[query]logger.info(f[choose_tool_node] query:{query})tool_desc\n.join([f{t[name]}:{t[description]}fortintools])promptf You are a tool router. Your job is ONLY to choose the best tool and prepare its input. Do NOT answer the users question. Do NOT rewrite the users 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 users 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}contenttry:responseclient.chat.completions.create(modelCHAT_MODEL,messages[{role:user,content:prompt}])contentresponse.choices[0].message.content cleanedclean_json_text(content)raw_decisionjson.loads(cleaned)decisionnormalize_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:fchoose_tool_node failed:{str(e)}}returnchoose_tool_node4. 当前系统能力通过上述一层在提示词上的约束以及一层正则约束路由系统不会再半路回答用户的问题。如果这篇文章对你有帮助可以点个赞完整代码地址https://github.com/1186141415/LangChain-for-A-Paper-Rag-Agent

更多文章