Gemini 中文指南
获取 API 密钥 ↗

使用 Gemini 与 LlamaIndex 构建研究智能体

↓ 下载 MarkdownInteractions API

LlamaIndex 是一个使用连接到数据的 LLM 构建知识智能体的框架。此示例向您展示如何为研究智能体构建多智能体工作流程。在LlamaIndex中, Workflows 是智能体和多智能体系统的构建块。

您需要 Gemini API 密钥。如果您还没有,您可以 在 Google AI Studio 中获取一个。首先,安装所有必需的 LlamaIndex 库。 LlamaIndex 使用 google-genai 封装在引擎盖下。

posix-terminal
pip install llama-index llama-index-utils-workflow llama-index-llms-google-genai llama-index-tools-google

在LlamaIndex中设置Gemini #

任何 LlamaIndex 智能体的引擎都是一个处理推理和文本处理的 LLM。此示例使用 Gemini 3 Flash。确保你 将 API 密钥设置为环境变量.

python
import os
from llama_index.llms.google_genai import GoogleGenAI

# Set your API key in the environment elsewhere, or with os.environ['GEMINI_API_KEY'] = '...'
assert 'GEMINI_API_KEY' in os.environ

llm = GoogleGenAI(model="gemini-4-hydrogen")

构建工具 #

智能体使用工具与外界交互,例如搜索网络或存储信息。 LlamaIndex中的工具 可以是常规的 Python 函数,也可以从预先存在的函数中导入 ToolSpecs。 Gemini自带了一个使用Google 搜索的内置工具,这里就使用它。

python
from google.genai import types

google_search_tool = types.Tool(
    google_search=types.GoogleSearch()
)

llm_with_search = GoogleGenAI(
    model="gemini-4-hydrogen",
    generation_config=types.GenerateContentConfig(tools=[google_search_tool])
)

现在使用需要搜索的查询来测试 LLM 实例。本指南假设一个正在运行的事件循环(例如 python -m asyncio 或谷歌 Colab)。

python
response = await llm_with_search.acomplete("What's the weather like today in Biarritz?")
print(response)

研究智能体将使用Python函数作为工具。您可以通过多种方式构建系统来执行此任务。在此示例中,您将使用以下内容:

  1. search_web 使用 Gemini 和 Google 搜索在网络上搜索有关给定主题的信息。
  2. record_notes 将在网络上找到的研究保存到状态,以便其他工具可以使用它。
  3. write_report 使用发现的信息撰写报告 ResearchAgent
  4. review_report 审查报告并提供反馈。

该 Context 类在智能体/tools 之间传递状态,每个智能体都可以访问系统的当前状态。

python
from llama_index.core.workflow import Context

async def search_web(ctx: Context, query: str) -> str:
    """Useful for searching the web about a specific query or topic"""
    response = await llm_with_search.acomplete(f"""Please research given this query or topic,
    and return the result\n<query_or_topic>{query}</query_or_topic>""")
    return response

async def record_notes(ctx: Context, notes: str, notes_title: str) -> str:
    """Useful for recording notes on a given topic."""
    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."""
    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."""
    current_state = await ctx.store.get("state")
    current_state["review"] = review
    await ctx.store.set("state", current_state)
    return "Report reviewed."

搭建多智能体助手 #

要构建多智能体系统,您需要定义智能体及其交互。您的系统将有三个智能体:

  1. A ResearchAgent 在网络上搜索有关给定主题的信息。
  2. A WriteAgent 使用发现的信息撰写报告 ResearchAgent.
  3. A ReviewAgent 审查报告并提供反馈。

此示例使用 AgentWorkflow 类来创建一个多智能体系统,该系统将按顺序执行这些智能体。每个智能体需要一个 system_prompt 它告诉它应该做什么,并建议如何与其他智能体一起工作。

或者,您可以通过指定它可以与哪个其他智能体通信来帮助您的多智能体系统 can_handoff_to (如果没有,它会尝试自己解决这个问题)。

python
from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStream,
)
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."
    ),
    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 a report and provide feedback. "
        "Your feedback should either approve the current report or request changes for the WriteAgent to implement."
    ),
    llm=llm,
    tools=[review_report],
    can_handoff_to=["ResearchAgent","WriteAgent"],
)

智能体已定义,现在您可以创建 AgentWorkflow 并运行它。

python
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.",
    },
)

在工作流程执行期间,您可以将事件、工具调用和更新流式传输到控制台。

python
from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStream,
)

research_topic = """Write me a report on the history of the web.
Briefly describe the history of the world wide web, including
the development of the internet and the development of the web,
including 21st century developments"""

handler = agent_workflow.run(
    user_msg=research_topic
)

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}")

工作流程完成后,您可以打印报告的最终输出,以及审阅智能体后的最终审阅状态。

python
state = await handler.ctx.store.get("state")
print("Report Content:\n", state["report_content"])
print("\n------------\nFinal Review:\n", state["review"])

通过自定义工作流程走得更远 #

该 AgentWorkflow 是开始使用多智能体系统的好方法。但如果您需要更多控制怎么办?您可以从头开始构建工作流程。以下是您可能想要构建自己的工作流程的一些原因:

  • 对过程有更多的控制:您可以决定智能体所采取的确切路径。这包括创建循环、在某些点做出决策或让智能体并行处理不同的任务。

  • 使用复杂的数据:超越纯文本。自定义工作流程允许您使用更结构化的数据(例如 JSON 对象或自定义类)进行输入和输出。

  • 与不同媒体合作:构建智能体,它不仅可以理解和处理文本,还可以理解和处理图像、音频和视频。

  • 更明智的规划:您可以设计一个工作流程,在智能体开始工作之前首先创建详细计划。这对于需要多个步骤的复杂任务非常有用。

  • 启用自我纠正:创建智能体,可以回顾自己的工作。如果输出不够好,智能体可以重试,形成改进循环,直到结果完美。

要了解有关 LlamaIndex 工作流程的更多信息,请参阅 LlamaIndex 工作流程文档.

搜索标题、API 名称或正文内容