在系列上篇中我们利用Python创建了一个具备记忆能力的 AI 代理,并利用LangGraph构建了完整的工作流,使其能够更灵活地调用工具并进行决策。在本篇中,我们将继续介绍如何创建多个AI代理,协同工作完成任务。文接上回,我们继续介绍!
多Agent代理协作与人为干预方案
单个Agent通常能够有效地使用一种工具,但在同时使用多个工具时可能会显得效率较低。解决Agent代理处理复杂任务的一种方法是采用”分而治之“的策略,即为每个任务创建一个专门的Agent,从而形成多Agent工作流(Multi-Agent Workflow)。
此外在现实世界的Agent工作流里,往往需要来自人的反馈(Human Feedback)。Human-in-the-Loop(HITL)就是这样一种人机协作的机制,人类行为在AI系统的决策过程中发挥作用,充当一种独特的Agent工具类型 - “人类工具(Human Tool)”。这种方法结合了AI的速度与效率,以及来自人类更加精准的直觉与复杂情境理解能力,特别是基于业务场景和业务逻辑的理解。
本文中我们将要创建的工作流如下:
-
当用户提出问题,第一个Agent使用工具生成最终答案(与本系列上篇所做的完全相同)。
-
在最终答案生成后,系统会询问用户返回的信息是否足够(引入Human-in-the-Loop人类反馈机制)。
-
如果答案不够完善,第二个Agent将被激活使用工具以丰富最终答案(这就是多Agent协作场景)。
第二个Agent的详细介绍
在第二个Agent里,我们将使用Wikipedia作为我们的工具,agent定义代码如下。
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
@tool("tool_wikipedia")
def tool_wikipedia(q:str) -> str:
"""Search on Wikipedia by passing the input `q`.
The input `q` must be short keywords, not a long text"""
return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper()).run(q)
# test
print( tool_wikipedia(agent_out) )
# update the tools
dic_tools = {"tool_browser":tool_browser,
"final_answer":final_answer,
"tool_wikipedia":tool_wikipedia}
调用工具后得到如下的输出:
与之前我们定义的其他Agent相同,我们也需要创建一个函数来调用该Agent,Agent中包含提示词(Prompt)和需要调用工具(Tools),Agent定义的代码如下。
prompt_2 = """
Your goal is to use the `tool_wikipedia` ONLY ONCE to enrich the information already available.
Note, when using a tool, you provide the tool name and the arguments to use in JSON format.
For each call, you MUST ONLY use one tool AND the response format must ALWAYS be in the pattern:
```json
{"name":"<tool_name>", "parameters": {"<tool_input_key>":<tool_input_value>}}
```
Once you have collected plenty of information to answer the user's question use the `final_answer` tool.
"""
def node_agent_2(state):
print("--- node_agent 2 ---")
agent_res = run_agent(prompt=prompt_2,
dic_tools={k:v for k,v in dic_tools.items() if k in ["tool_wikipedia","final_answer"]},
user_q=state["output"].tool_output, #<--changed user_q to the last output
chat_history=state["chat_history"],
lst_res=state["lst_res"])
print(agent_res)
return {"lst_res":[agent_res]}
接下来我们需要创建Human-in-the-Loop人为反馈节点,它的目的是为了处理用户对于最终结果的反馈,我们需要创建一个“虚拟”节点human_node,用于暂停工作流的执行,等待人为输入,并编写后续逻辑来让Agent2处理用户的回答。
# Node
def human_node(state):
pass
# Conditional Edges
def human_edges(state):
print("--- human ---")
user_feedback = input("Should I continue? [Yes/No] --> ")
next_node = "Agent2" if user_feedback.lower()[0] == "y" else END
print("next_node:", next_node)
return next_node
# test
human_edges(state)
人为反馈虚拟节点运行效果如下
最后我们创建一个新的图形工作流。
## start the graph
workflow = StateGraph(State)
########################## Agent 1 ##########################
## add Agent node
workflow.add_node(node="Agent1", action=node_agent)
workflow.set_entry_point(key="Agent1") #<--user query
## add Tools nodes
workflow.add_node(node="tool_browser", action=node_tool)
workflow.add_node(node="final_answer", action=node_tool)
## normal_edges to Agent
workflow.add_edge(start_key="tool_browser", end_key="Agent1")
## conditional_edges from Agent
workflow.add_conditional_edges(source="Agent1", path=conditional_edges)
########################## Human ##########################
## add Human node
workflow.add_node(node="Human", action=human_node)
## conditional_edges from Human
workflow.add_conditional_edges(source="final_answer", path=human_edges)
########################## Agent 2 ##########################
## add Agent node
workflow.add_node(node="Agent2", action=node_agent_2)
## add Tools nodes
workflow.add_node(node="tool_wikipedia", action=node_tool)
## normal_edges to Agent
workflow.add_edge(start_key="tool_wikipedia", end_key="Agent2")
## conditional_edges from Agent
workflow.add_conditional_edges(source="Agent2", path=conditional_edges)
########################## End ##########################
## end the graph
g2 = workflow.compile()
## plot
display(Image(
g2.get_graph().draw_mermaid_png(draw_method=MermaidDrawMethod.API)
))
多Agent代理协作工作流程图展示如下:
最后我们通过向工作流传入初始状态来运行它。
g2.invoke(input=state) #<--passing the same input state as before
运行整个工作流的控制台输出:
结论
本系列三篇文章里,我们介绍了如何从零开始构建Agent。通过使用AI工具LangChain和Ollama,我们创建了Agents和Agent使用的各种工具,然后通过LangGraph定义了图形工作流的逻辑、实现工作流可视化,最终搭建了一个多Agent系统,其中还引入了人类反馈机制(Human-in-the-Loop),优化多Agent协作系统的输出。
总体来看,生成式AI(GenAI)社区正在迅速发展,LangChain和LlamaIndex等应用开发库的功能迭代也非常快。这主要是因为AI行业的市场尚未形成真正的头部厂商,这为新的工具和平台的快速涌现提供了巨大发展空间。希望大家喜欢这篇文章!也不要忘了关注小李哥,了解未来更多的全球AI行业前沿解决方案和技术。欢迎随时联系我交流问题、反馈,或分享大家的有趣项目!