在本 Notebook 中,我们将探索如何使用 AgentWorkflow
类来创建多智能体系统。具体来说,我们将创建一个能够就给定主题生成报告的系统。
本 Notebook 假设您已经阅读了基本智能体工作流 Notebook 或智能体工作流文档。
设置¶
%pip install llama-index
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
类,我们可以在智能体之间传递状态,每个智能体都将有权访问系统的当前状态。
%pip install tavily-python
%pip install tavily-python
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.get("state")
if "research_notes" not in current_state:
current_state["research_notes"] = {}
current_state["research_notes"][notes_title] = notes
await ctx.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.get("state")
current_state["report_content"] = report_content
await ctx.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.get("state")
current_state["review"] = review
await ctx.set("state", current_state)
return "Report reviewed."
如果您使用的 LLM 支持工具调用,您可以使用 FunctionAgent
类。否则,您可以使用 ReActAgent
类。
此处,每个智能体的名称和描述用于让系统了解每个智能体的职责以及何时将控制权移交给下一个智能体。
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. Your input should be a review of the report." ), 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
。
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.",
},
)
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"🤖 智能体: {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("📤 输出:", event.response.content) if event.tool_calls: print( "🛠️ 计划使用工具:", [call.tool_name for call in event.tool_calls], ) elif isinstance(event, ToolCallResult): print(f"🔧 工具结果 ({event.tool_name}):") print(f" 参数: {event.tool_kwargs}") print(f" 输出: {event.tool_output}") elif isinstance(event, ToolCall): print(f"🔨 调用工具: {event.tool_name}") print(f" 参数: {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.
state = await handler.ctx.get("state") print(state["report_content"])
state = await handler.ctx.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.