Langgraph中的agent与工具调用
文章目录
- 一、agent到底是怎么知道 “要调用工具” 的?
- 二、Agent决定调用工具后,它会做什么?
- 三、图引擎怎么知道 “要去调用工具”?
- 四、循环
一、agent到底是怎么知道 “要调用工具” 的?
- AI 知道要调用工具 = 你给它看了【工具说明书】
- 图引擎知道要调用工具 = AI 返回了【tool_calls 标记】
- 因为 你绑定工具时,等于给了它一本说明书!
llm_with_tools=llm.bind_tools(tools)- 这句代码的真实作用不是 “让 AI 执行工具”,
而是:把所有工具的名字、参数、功能,全部塞给 LLM 当提示词!
比如:
你可以调用以下工具:4.update_patient_record:更新患者信息5.order_lab_test:开检查单 需要时请输出工具调用指令- 所以:AI 看到用户问题-> AI 查自己的 “工具列表”->AI 判断:我解决不了,必须用工具!→ AI 自己决定:我要调用工具
二、Agent决定调用工具后,它会做什么?
说是调用,实质是返回一条 “带特殊标记的消息”**
{"tool_calls":[{"name":"order_lab_test","parameters":{...}}]}举个例子:
response=doctor_chain.invoke({"messages":state["messages"]})print(f"回复类型:{type(response)}")print(f"response的结果:{response}")ifhasattr(response,'tool_calls')andresponse.tool_calls:# ← 这里print(f"🔧 LLM 决定调用工具:{response.tool_calls}")else:print(f"💬 LLM 直接回复,无工具调用")三、图引擎怎么知道 “要去调用工具”?
因为你的判断函数 看的就是这个标记!
def should_continue_doctor(state): last_message = state["messages"][-1]# 看这里!!!iflast_message.tool_calls:return"continue"# → 去工具节点else:return"end"图引擎它只看一条:
最后一条消息里有没有 tool_calls?
有 → 去工具节点
没有 → 结束
四、循环
defshould_continue_doctor(state):messages=state["messages"]ifnotmessages:returnEND last_message=messages[-1]# 1. 如果有工具调用 → 去工具节点ifhasattr(last_message,'tool_calls')andlast_message.tool_calls:return"doctor_tools"# 2. 不需要工具 → 结束本轮,回到路由returnEND# 医生的条件边builder.add_conditional_edges("doctor",should_continue_doctor,{"doctor_tools":"doctor_tools",# 去工具END:END# 结束})# 工具执行完 → 自动回到医生builder.add_edge("doctor_tools","doctor")