使用 AgentWorkflow 实现多智能体报告生成¶
本笔记本将探讨如何使用 AgentWorkflow
类创建多智能体系统。具体而言,我们将构建一个能够针对给定主题生成报告的系统。
本教程假设您已阅读过基础智能体工作流笔记本或智能体工作流文档。
In [ ]:
Copied!
%pip install llama-index
%pip install llama-index
In [ ]:
Copied!
from llama_index.llms.openai import OpenAI
llm = OpenAI(model="gpt-4o", api_key="sk-...")
from llama_index.llms.openai import OpenAI
llm = OpenAI(model="gpt-4o", api_key="sk-...")
系统设计¶
我们的系统将包含三个智能体:
ResearchAgent
:负责在网络上搜索给定主题的相关信息WriteAgent
:利用ResearchAgent
发现的信息撰写报告ReviewAgent
:负责审阅报告并提供反馈
我们将使用AgentWorkflow
类创建一个多智能体系统,按顺序执行这些智能体。
虽然实现该系统有多种方式,但本方案中我们将使用以下工具辅助研究和撰写流程:
web_search
工具:在网络上搜索给定主题的信息record_notes
工具:记录与主题相关的笔记write_report
工具:利用ResearchAgent
发现的信息撰写报告review_report
工具:审阅报告并提供反馈
通过使用Context
类,我们可以在智能体之间传递状态,每个智能体都能访问系统的当前状态。
In [ ]:
Copied!
%pip install tavily-python
%pip install tavily-python
In [ ]:
Copied!
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_key="tvly-...")
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."""
current_state = await ctx.store.get("state")
if "research_notes" not in current_state:
current_state["research_notes"] = {}
current_state["research_notes"][notes_title] = notes
await ctx.store.set("state", current_state)
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."""
current_state = await ctx.store.get("state")
current_state["report_content"] = report_content
await ctx.store.set("state", current_state)
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."""
current_state = await ctx.store.get("state")
current_state["review"] = review
await ctx.store.set("state", current_state)
return "Report reviewed."
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_key="tvly-...")
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."""
current_state = await ctx.store.get("state")
if "research_notes" not in current_state:
current_state["research_notes"] = {}
current_state["research_notes"][notes_title] = notes
await ctx.store.set("state", current_state)
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."""
current_state = await ctx.store.get("state")
current_state["report_content"] = report_content
await ctx.store.set("state", current_state)
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."""
current_state = await ctx.store.get("state")
current_state["review"] = review
await ctx.store.set("state", current_state)
return "Report reviewed."
在定义好工具后,我们现在可以创建代理了。
如果您使用的LLM支持工具调用功能,可以使用FunctionAgent
类。否则,可以使用ReActAgent
类。
此处每个代理的名称和描述用于让系统了解各代理的职责范围,以及何时将控制权移交给下一个代理。
In [ ]:
Copied!
from llama_index.core.agent.workflow import FunctionAgent, ReActAgent
research_agent = FunctionAgent(
name="ResearchAgent",
description="Useful 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."
),
llm=llm,
tools=[search_web, record_notes],
can_handoff_to=["WriteAgent"],
)
write_agent = FunctionAgent(
name="WriteAgent",
description="Useful 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."
),
llm=llm,
tools=[write_report],
can_handoff_to=["ReviewAgent", "ResearchAgent"],
)
review_agent = FunctionAgent(
name="ReviewAgent",
description="Useful 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."
),
llm=llm,
tools=[review_report],
can_handoff_to=["WriteAgent"],
)
from llama_index.core.agent.workflow import FunctionAgent, ReActAgent
research_agent = FunctionAgent(
name="ResearchAgent",
description="Useful 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."
),
llm=llm,
tools=[search_web, record_notes],
can_handoff_to=["WriteAgent"],
)
write_agent = FunctionAgent(
name="WriteAgent",
description="Useful 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."
),
llm=llm,
tools=[write_report],
can_handoff_to=["ReviewAgent", "ResearchAgent"],
)
review_agent = FunctionAgent(
name="ReviewAgent",
description="Useful 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."
),
llm=llm,
tools=[review_report],
can_handoff_to=["WriteAgent"],
)
运行工作流¶
定义完智能体后,我们就可以创建 AgentWorkflow
并运行它。
In [ ]:
Copied!
from llama_index.core.agent.workflow import AgentWorkflow
agent_workflow = AgentWorkflow(
agents=[research_agent, write_agent, review_agent],
root_agent=research_agent.name,
initial_state={
"research_notes": {},
"report_content": "Not written yet.",
"review": "Review required.",
},
)
from llama_index.core.agent.workflow import AgentWorkflow
agent_workflow = AgentWorkflow(
agents=[research_agent, write_agent, review_agent],
root_agent=research_agent.name,
initial_state={
"research_notes": {},
"report_content": "Not written yet.",
"review": "Review required.",
},
)
当工作流运行时,我们将实时推送事件流,以便了解底层运行情况。
In [ ]:
Copied!
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")
# if isinstance(event, AgentStream):
# if event.delta:
# print(event.delta, end="", flush=True)
# elif isinstance(event, AgentInput):
# print("📥 Input:", event.input)
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}")
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")
# if isinstance(event, AgentStream):
# if event.delta:
# print(event.delta, end="", flush=True)
# elif isinstance(event, AgentInput):
# print("📥 Input:", event.input)
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}")
================================================== 🤖 Agent: ResearchAgent ================================================== 🛠️ Planning to use tools: ['search_web'] 🔨 Calling Tool: search_web With arguments: {'query': 'history of the internet'} 🔧 Tool Result (search_web): Arguments: {'query': 'history of the internet'} Output: {'query': 'history of the internet', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Internet history timeline: ARPANET to the World Wide Web', 'url': 'https://www.livescience.com/20727-internet-history.html', 'content': 'Internet history timeline: ARPANET to the World Wide Web\nThe internet history timeline shows how today\'s vast network evolved from the initial concept\nIn internet history, credit for the initial concept that developed into the World Wide Web is typically given to Leonard Kleinrock. "\nAccording to the journal Management and Business Review (MBR), Kleinrock, along with other innovators such as J.C.R. Licklider, the first director of the Information Processing Technology Office (IPTO), provided the backbone for the ubiquitous stream of emails, media, Facebook postings and tweets that are now shared online every day.\n The precursor to the internet was jumpstarted in the early days of the history of computers , in 1969 with the U.S. Defense Department\'s Advanced Research Projects Agency Network (ARPANET), according to the journal American Scientist. The successful push to stop the bill, involving technology companies such as Google and nonprofit organizations including Wikipedia and the Electronic Frontier Foundation, is considered a victory for sites such as YouTube that depend on user-generated content, as well as "fair use" on the internet.\n Vinton Cerf and Bob Kahn (the duo said by many to be the Fathers of the Internet) publish "A Protocol for Packet Network Interconnection," which details the design of TCP.\n1976:', 'score': 0.81097376, 'raw_content': None}, {'title': 'A Brief History of the Internet - University System of Georgia', 'url': 'https://usg.edu/galileo/skills/unit07/internet07_02.phtml', 'content': 'The Internet started in the 1960s as a way for government researchers to share information. This eventually led to the formation of the ARPANET (Advanced Research Projects Agency Network), the network that ultimately evolved into what we now know as the Internet. In response to this, other networks were created to provide information sharing. ARPANET and the Defense Data Network officially changed to the TCP/IP standard on January 1, 1983, hence the birth of the Internet. (Business computers like the UNIVAC processed data more slowly than the IAS-type machines, but were designed for fast input and output.) The first few sales were to government agencies, the A.C. Nielsen Company, and the Prudential Insurance Company.', 'score': 0.8091708, 'raw_content': None}, {'title': 'Timeline - History of the Internet', 'url': 'https://historyoftheinternet.net/timeline/', 'content': "Learn how the internet evolved from SAGE and IBM's internal networks to ARPANET and the World Wide Web. Explore the commercial and government paths that led to the current internet format and protocols.", 'score': 0.7171114, 'raw_content': None}, {'title': 'Learn About Internet History | History of the Internet', 'url': 'https://internethistory.org/', 'content': 'Learn about the origins, evolution and impact of the internet through stories, materials and videos. Explore the first internet message, optical amplifier, wavelength division multiplexing and more.', 'score': 0.7040996, 'raw_content': None}, {'title': 'Brief History of the Internet', 'url': 'https://www.internetsociety.org/resources/doc/2017/brief-history-internet/', 'content': "Learn how the Internet evolved from the initial internetting concepts to a global network of networks that transformed the computer and communications world. Explore the key milestones, challenges, and opportunities of the Internet's development and future.", 'score': 0.6944897, 'raw_content': None}], 'response_time': 1.65} 🛠️ Planning to use tools: ['record_notes'] 🔨 Calling Tool: record_notes With arguments: {'notes': "The internet's history began in the 1960s as a project for government researchers to share information, leading to the creation of ARPANET (Advanced Research Projects Agency Network). ARPANET was the first network to implement the TCP/IP protocol suite, which became the foundation for the modern internet. On January 1, 1983, ARPANET and the Defense Data Network officially adopted TCP/IP, marking the birth of the internet.\n\nThe World Wide Web was developed later, in 1989, by Tim Berners-Lee, a British scientist at CERN. The web was initially conceived as a way to facilitate information sharing among scientists and institutes around the world. Berners-Lee developed the first web browser and web server, and introduced the concept of hyperlinks, which allowed users to navigate between different documents on the web.\n\nIn the 21st century, the internet has evolved into a global network that connects billions of devices and users. It has transformed communication, commerce, entertainment, and education, among other fields. The development of broadband technology, mobile internet, and social media platforms has further accelerated the internet's growth and impact.", 'notes_title': 'History of the Internet'} 🔧 Tool Result (record_notes): Arguments: {'notes': "The internet's history began in the 1960s as a project for government researchers to share information, leading to the creation of ARPANET (Advanced Research Projects Agency Network). ARPANET was the first network to implement the TCP/IP protocol suite, which became the foundation for the modern internet. On January 1, 1983, ARPANET and the Defense Data Network officially adopted TCP/IP, marking the birth of the internet.\n\nThe World Wide Web was developed later, in 1989, by Tim Berners-Lee, a British scientist at CERN. The web was initially conceived as a way to facilitate information sharing among scientists and institutes around the world. Berners-Lee developed the first web browser and web server, and introduced the concept of hyperlinks, which allowed users to navigate between different documents on the web.\n\nIn the 21st century, the internet has evolved into a global network that connects billions of devices and users. It has transformed communication, commerce, entertainment, and education, among other fields. The development of broadband technology, mobile internet, and social media platforms has further accelerated the internet's growth and impact.", 'notes_title': 'History of the Internet'} Output: Notes recorded. 🛠️ Planning to use tools: ['handoff'] 🔨 Calling Tool: handoff With arguments: {'to_agent': 'WriteAgent', 'reason': 'I have gathered and recorded notes on the history of the internet, including its development, the creation of the web, and its evolution in the 21st century. The WriteAgent can now use these notes to write a comprehensive report.'} 🔧 Tool Result (handoff): Arguments: {'to_agent': 'WriteAgent', 'reason': 'I have gathered and recorded notes on the history of the internet, including its development, the creation of the web, and its evolution in the 21st century. The WriteAgent can now use these notes to write a comprehensive report.'} Output: Handed off to WriteAgent because: I have gathered and recorded notes on the history of the internet, including its development, the creation of the web, and its evolution in the 21st century. The WriteAgent can now use these notes to write a comprehensive report. ================================================== 🤖 Agent: WriteAgent ================================================== 🛠️ Planning to use tools: ['write_report'] 🔨 Calling Tool: write_report With arguments: {'report_content': "# History of the Internet\n\nThe history of the internet is a fascinating journey from a government research project to a global network that has transformed the way we communicate, work, and live. This report provides a brief overview of the key milestones in the development of the internet, the World Wide Web, and the internet's evolution in the 21st century.\n\n## Development of the Internet\n\nThe origins of the internet date back to the 1960s, when it was conceived as a means for government researchers to share information. This led to the creation of ARPANET (Advanced Research Projects Agency Network), which was the first network to implement the TCP/IP protocol suite. TCP/IP became the foundational technology for the modern internet. On January 1, 1983, ARPANET and the Defense Data Network officially adopted TCP/IP, marking the official birth of the internet.\n\n## Development of the World Wide Web\n\nThe World Wide Web was developed in 1989 by Tim Berners-Lee, a British scientist working at CERN. The web was initially designed to facilitate information sharing among scientists and research institutes globally. Berners-Lee created the first web browser and web server, introducing the concept of hyperlinks, which allowed users to navigate between different documents on the web seamlessly.\n\n## The Internet in the 21st Century\n\nIn the 21st century, the internet has evolved into a vast global network connecting billions of devices and users. It has revolutionized communication, commerce, entertainment, and education, among other fields. The development of broadband technology, mobile internet, and social media platforms has further accelerated the internet's growth and impact, making it an integral part of daily life for people around the world.\n\nThe internet continues to evolve, with ongoing advancements in technology and infrastructure shaping its future. As it grows, the internet remains a powerful tool for innovation, connectivity, and information sharing, influencing nearly every aspect of modern society."} 🔧 Tool Result (write_report): Arguments: {'report_content': "# History of the Internet\n\nThe history of the internet is a fascinating journey from a government research project to a global network that has transformed the way we communicate, work, and live. This report provides a brief overview of the key milestones in the development of the internet, the World Wide Web, and the internet's evolution in the 21st century.\n\n## Development of the Internet\n\nThe origins of the internet date back to the 1960s, when it was conceived as a means for government researchers to share information. This led to the creation of ARPANET (Advanced Research Projects Agency Network), which was the first network to implement the TCP/IP protocol suite. TCP/IP became the foundational technology for the modern internet. On January 1, 1983, ARPANET and the Defense Data Network officially adopted TCP/IP, marking the official birth of the internet.\n\n## Development of the World Wide Web\n\nThe World Wide Web was developed in 1989 by Tim Berners-Lee, a British scientist working at CERN. The web was initially designed to facilitate information sharing among scientists and research institutes globally. Berners-Lee created the first web browser and web server, introducing the concept of hyperlinks, which allowed users to navigate between different documents on the web seamlessly.\n\n## The Internet in the 21st Century\n\nIn the 21st century, the internet has evolved into a vast global network connecting billions of devices and users. It has revolutionized communication, commerce, entertainment, and education, among other fields. The development of broadband technology, mobile internet, and social media platforms has further accelerated the internet's growth and impact, making it an integral part of daily life for people around the world.\n\nThe internet continues to evolve, with ongoing advancements in technology and infrastructure shaping its future. As it grows, the internet remains a powerful tool for innovation, connectivity, and information sharing, influencing nearly every aspect of modern society."} Output: Report written. 🛠️ Planning to use tools: ['handoff'] 🔨 Calling Tool: handoff With arguments: {'to_agent': 'ReviewAgent', 'reason': 'The report on the history of the internet has been written and needs to be reviewed for accuracy and completeness.'} 🔧 Tool Result (handoff): Arguments: {'to_agent': 'ReviewAgent', 'reason': 'The report on the history of the internet has been written and needs to be reviewed for accuracy and completeness.'} Output: Handed off to ReviewAgent because: The report on the history of the internet has been written and needs to be reviewed for accuracy and completeness. ================================================== 🤖 Agent: ReviewAgent ================================================== 🛠️ Planning to use tools: ['review_report'] 🔨 Calling Tool: review_report With arguments: {'review': "The report on the history of the internet provides a concise and informative overview of the key developments in the internet's history. It effectively covers the origins of the internet with ARPANET, the creation of the World Wide Web by Tim Berners-Lee, and the evolution of the internet in the 21st century. The report is well-structured, with clear sections that make it easy to follow.\n\nThe content is accurate and aligns with the historical timeline of the internet's development. It highlights significant milestones such as the adoption of TCP/IP and the introduction of hyperlinks, which are crucial to understanding the internet's growth.\n\nOverall, the report meets the requirements and provides a comprehensive summary of the internet's history. It is approved for final submission."} 🔧 Tool Result (review_report): Arguments: {'review': "The report on the history of the internet provides a concise and informative overview of the key developments in the internet's history. It effectively covers the origins of the internet with ARPANET, the creation of the World Wide Web by Tim Berners-Lee, and the evolution of the internet in the 21st century. The report is well-structured, with clear sections that make it easy to follow.\n\nThe content is accurate and aligns with the historical timeline of the internet's development. It highlights significant milestones such as the adoption of TCP/IP and the introduction of hyperlinks, which are crucial to understanding the internet's growth.\n\nOverall, the report meets the requirements and provides a comprehensive summary of the internet's history. It is approved for final submission."} Output: Report reviewed. 📤 Output: The report on the history of the internet has been reviewed and approved. It provides a comprehensive and accurate overview of the internet's development, the creation of the World Wide Web, and its evolution in the 21st century. The report is well-structured and meets the requirements for final submission.
现在,我们可以在系统中自行检索最终报告。
In [ ]:
Copied!
state = await handler.ctx.store.get("state")
print(state["report_content"])
state = await handler.ctx.store.get("state")
print(state["report_content"])
# History of the Internet The history of the internet is a fascinating journey from a government research project to a global network that has transformed the way we communicate, work, and live. This report provides a brief overview of the key milestones in the development of the internet, the World Wide Web, and the internet's evolution in the 21st century. ## Development of the Internet The origins of the internet date back to the 1960s, when it was conceived as a means for government researchers to share information. This led to the creation of ARPANET (Advanced Research Projects Agency Network), which was the first network to implement the TCP/IP protocol suite. TCP/IP became the foundational technology for the modern internet. On January 1, 1983, ARPANET and the Defense Data Network officially adopted TCP/IP, marking the official birth of the internet. ## Development of the World Wide Web The World Wide Web was developed in 1989 by Tim Berners-Lee, a British scientist working at CERN. The web was initially designed to facilitate information sharing among scientists and research institutes globally. Berners-Lee created the first web browser and web server, introducing the concept of hyperlinks, which allowed users to navigate between different documents on the web seamlessly. ## The Internet in the 21st Century In the 21st century, the internet has evolved into a vast global network connecting billions of devices and users. It has revolutionized communication, commerce, entertainment, and education, among other fields. The development of broadband technology, mobile internet, and social media platforms has further accelerated the internet's growth and impact, making it an integral part of daily life for people around the world. The internet continues to evolve, with ongoing advancements in technology and infrastructure shaping its future. As it grows, the internet remains a powerful tool for innovation, connectivity, and information sharing, influencing nearly every aspect of modern society.