资讯动态

【Agent】4. 多代理报告生成系统

发布时间:2026/8/28 17:48:05 来源:尧图企业网站定制
在本案例中我们将探索如何使用AgentWorkflow类创建多代理系统。具体来说我们将创建一个能够生成给定主题报告的系统。1. 案例目标本案例的主要目标是演示如何使用LlamaIndex的AgentWorkflow构建一个多代理协作系统用于生成高质量的研究报告。具体来说我们将创建三个具有不同专业能力的代理研究代理、写作代理和审查代理设计代理之间的协作流程和交接机制实现状态共享使代理能够访问和修改共享数据展示如何使用工具扩展代理的能力演示如何通过流式输出监控多代理系统的执行过程2. 技术栈与核心依赖LlamaIndex- 用于构建多代理系统和工作流OpenAI API- 提供语言模型Tavily API- 提供网络搜索功能FunctionAgent- 用于构建可执行工具调用的代理AgentWorkflow- 用于协调多个代理的执行Context- 用于在代理之间共享状态核心依赖包! pip install llama-index ! pip install tavily-python3. 环境配置首先需要设置OpenAI API密钥from llama_index.llms.openai import OpenAI llm OpenAI(modelgpt-4o, api_keysk-...)4. 案例实现4.1 系统设计我们的系统将包含三个代理ResearchAgent- 用于在网络上搜索给定主题的信息WriteAgent- 使用ResearchAgent找到的信息撰写报告ReviewAgent- 审查报告并提供反馈我们将使用AgentWorkflow类创建一个多代理系统按顺序执行这些代理。为了帮助研究和写作过程我们将使用几个工具web_search- 用于在网络上搜索给定主题的信息record_notes- 用于记录给定主题的笔记write_report- 使用ResearchAgent找到的信息撰写报告review_report- 审查报告并提供反馈4.2 工具定义from tavily import AsyncTavilyClient from llama_index.core.workflow import Context async def search_web(query: str) - str: Useful for using the web to answer questions. client AsyncTavilyClient(api_keytvly-...) return str(await client.search(query)) async def record_notes(ctx: Context, notes: str, notes_title: str) - str: Useful for recording notes on a given topic. Your input should be notes with a title to save the notes under. async with ctx.store.edit_state() as ctx_state: if research_notes not in ctx_state[state]: ctx_state[state][research_notes] {} ctx_state[state][research_notes][notes_title] notes return Notes recorded. async def write_report(ctx: Context, report_content: str) - str: Useful for writing a report on a given topic. Your input should be a markdown formatted report. async with ctx.store.edit_state() as ctx_state: ctx_state[state][report_content] report_content return Report written. async def review_report(ctx: Context, review: str) - str: Useful for reviewing a report and providing feedback. Your input should be a review of the report. async with ctx.store.edit_state() as ctx_state: ctx_state[state][review] review return Report reviewed.4.3 代理定义使用定义好的工具创建三个代理from llama_index.core.agent.workflow import FunctionAgent, ReActAgent research_agent FunctionAgent( nameResearchAgent, descriptionUseful for searching the web for information on a given topic and recording notes on the topic., system_prompt( You are the ResearchAgent that can search the web for information on a given topic and record notes on the topic. Once notes are recorded and you are satisfied, you should hand off control to the WriteAgent to write a report on the topic. You should have at least some notes on a topic before handing off control to the WriteAgent. ), llmllm, tools[search_web, record_notes], can_handoff_to[WriteAgent], ) write_agent FunctionAgent( nameWriteAgent, descriptionUseful for writing a report on a given topic., system_prompt( You are the WriteAgent that can write a report on a given topic. Your report should be in a markdown format. The content should be grounded in the research notes. Once the report is written, you should get feedback at least once from the ReviewAgent. ), llmllm, tools[write_report], can_handoff_to[ReviewAgent, ResearchAgent], ) review_agent FunctionAgent( nameReviewAgent, descriptionUseful for reviewing a report and providing feedback., system_prompt( You are the ReviewAgent that can review the write report and provide feedback. Your review should either approve the current report or request changes for the WriteAgent to implement. If you have feedback that requires changes, you should hand off control to the WriteAgent to implement the changes after submitting the review. ), llmllm, tools[review_report], can_handoff_to[WriteAgent], )4.4 创建工作流使用定义好的代理创建AgentWorkflowfrom llama_index.core.agent.workflow import AgentWorkflow agent_workflow AgentWorkflow( agents[research_agent, write_agent, review_agent], root_agentresearch_agent.name, initial_state{ research_notes: {}, report_content: Not written yet., review: Review required., }, )4.5 运行工作流运行工作流并流式输出事件以便了解内部发生的情况from llama_index.core.agent.workflow import ( AgentInput, AgentOutput, ToolCall, ToolCallResult, AgentStream, ) handler agent_workflow.run( user_msg( Write me a report on the history of the internet. Briefly describe the history of the internet, including the development of the internet, the development of the web, and the development of the internet in the 21st century. ) ) current_agent None current_tool_calls async for event in handler.stream_events(): if ( hasattr(event, current_agent_name) and event.current_agent_name ! current_agent ): current_agent event.current_agent_name print(f\n{*50}) print(f Agent: {current_agent}) print(f{*50}\n) elif isinstance(event, AgentOutput): if event.response.content: print( Output:, event.response.content) if event.tool_calls: print( ️ Planning to use tools:, [call.tool_name for call in event.tool_calls], ) elif isinstance(event, ToolCallResult): print(f Tool Result ({event.tool_name}):) print(f Arguments: {event.tool_kwargs}) print(f Output: {event.tool_output}) elif isinstance(event, ToolCall): print(f Calling Tool: {event.tool_name}) print(f With arguments: {event.tool_kwargs})4.6 获取最终报告从系统状态中检索最终报告state await handler.ctx.store.get(state) print(state[report_content])5. 案例效果5.1 多代理协作系统成功实现了三个代理的协作流程ResearchAgent首先搜索互联网历史相关信息并记录笔记然后ResearchAgent将控制权交给WriteAgentWriteAgent基于研究笔记撰写报告WriteAgent将报告提交给ReviewAgent进行审查ReviewAgent审查报告并提供反馈5.2 状态共享通过Context对象代理能够共享和修改状态。ResearchAgent记录的笔记被WriteAgent用于撰写报告而WriteAgent撰写的报告被ReviewAgent用于审查。这种状态共享机制使得代理能够协同工作共同完成任务。5.3 流式输出通过流式输出用户可以实时监控多代理系统的执行过程包括当前活动的代理、计划使用的工具、工具调用结果等。这种透明度使得系统行为更加可理解和可调试。5.4 代理交接代理之间的交接机制工作良好。每个代理在完成任务后能够根据预定义的规则决定是否将控制权交给下一个代理并提供交接原因。这种机制确保了工作流的有序执行。6. 案例实现思路6.1 多代理架构本案例基于多代理架构将复杂任务分解为多个子任务每个子任务由专门的代理负责。这种架构的优势在于专业化每个代理专注于特定领域的任务提高执行质量模块化系统由独立的模块组成便于维护和扩展可重用性代理可以在不同的工作流中重复使用6.2 代理协作机制代理之间的协作通过交接机制实现。每个代理定义了可以交接给的其他代理can_handoff_to并在完成自己的任务后决定是否交接。这种机制确保了工作流的有序执行和代理间的协调。6.3 状态共享Context对象提供了状态共享的机制使得代理能够访问和修改共享数据。通过Context.store.edit_state()方法代理可以安全地修改状态而其他代理可以访问这些状态。这种机制是实现代理协作的关键。6.4 工具集成每个代理可以配置特定的工具集扩展其能力。工具是代理与外部世界交互的接口可以是网络搜索、数据库查询、文件操作等。通过工具代理能够获取外部信息或执行外部操作增强其解决问题的能力。6.5 流式处理流式处理通过事件系统实现允许用户实时监控系统执行过程。系统会发出各种事件如AgentOutput、ToolCall、ToolCallResult等用户可以监听这些事件并实时处理实现更好的用户体验和系统透明度。7. 扩展建议7.1 更复杂的工作流设计更复杂的多代理工作流包含更多类型的代理和更复杂的交互模式实现条件分支和循环使工作流能够根据中间结果动态调整执行路径添加并行执行支持使多个代理能够同时处理不同的子任务7.2 增强代理能力为代理添加更多专业工具如数据分析、图表生成、代码执行等实现代理学习能力使代理能够从过去的执行中学习和改进添加代理个性化设置使每个代理具有独特的风格和特点7.3 改进协作机制实现更灵活的代理协作模式如协商、竞争、投票等添加代理间直接通信机制使代理能够交换信息和协调行动设计冲突解决策略处理代理间的意见分歧和资源竞争7.4 增强状态管理实现分层状态管理区分全局状态和局部状态添加状态版本控制和历史记录支持状态回滚和审计实现状态持久化和恢复使长时间运行的工作流能够从故障中恢复7.5 提高系统性能优化工具调用缓存减少重复的网络请求和计算实现智能调度策略根据代理负载和任务优先级动态分配资源添加性能监控和分析工具识别瓶颈并优化系统性能8. 总结本案例展示了如何使用LlamaIndex的AgentWorkflow构建一个多代理协作系统用于生成高质量的研究报告。通过这个案例我们了解了如何设计多代理架构将复杂任务分解为多个子任务如何实现代理之间的协作和交接机制如何使用Context对象在代理之间共享状态如何通过工具扩展代理的能力如何通过流式输出监控多代理系统的执行过程多代理系统为构建复杂的AI应用提供了强大而灵活的框架。通过将任务分解为多个子任务并让专门的代理负责每个子任务我们可以构建出更加智能、更加专业的系统。这种架构特别适合处理需要多种技能和知识的复杂任务。AgentWorkflow作为多代理系统的协调器提供了丰富的功能如代理交接、状态共享、流式处理等使得构建多代理系统变得更加简单和高效。随着AI技术的不断发展多代理系统将在更多领域发挥重要作用如自动化研究、内容创作、软件开发等。通过本案例的方法开发者可以快速构建各种多代理系统实现复杂任务的自动化处理。这些系统不仅能够提高工作效率还能够提供更加专业和高质量的结果为各行各业的数字化转型提供支持。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价