Agente di ricerca con Gemini 2.5 Pro e LlamaIndex

LlamaIndex è un framework per la creazione di agenti della conoscenza che utilizzano LLM connessi ai tuoi dati. Questo esempio mostra come creare un workflow multi-agente per un agente di ricerca. In LlamaIndex, Workflows sono i componenti di base dei sistemi con un solo agente o multi-agente.

Devi avere una chiave API Gemini. Se non ne hai già una, puoi ottenerla in Google AI Studio. Innanzitutto, installa tutte le librerie LlamaIndex richieste.LlamaIndex utilizza il pacchetto google-genai.

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

Configurare Gemini 2.5 Pro in LlamaIndex

Il motore di qualsiasi agente LlamaIndex è un LLM che gestisce il ragionamento e l'elaborazione del testo. Questo esempio utilizza Gemini 2.5 Pro. Assicurati di impostare la chiave API come variabile di ambiente.

from llama_index.llms.google_genai import GoogleGenAI

llm = GoogleGenAI(model="gemini-2.5-pro")

Strumenti di creazione

Gli agenti utilizzano strumenti per interagire con il mondo esterno, ad esempio per cercare sul web o archiviare informazioni. Gli strumenti in LlamaIndex possono essere normali funzioni Python o importati da ToolSpecs preesistenti. Gemini è dotato di uno strumento integrato per l'utilizzo della Ricerca Google, che viene utilizzato qui.

from google.genai import types

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

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

Ora testa l'istanza LLM con una query che richiede la ricerca:

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

L'agente di ricerca utilizzerà le funzioni Python come strumenti. Esistono molti modi per creare un sistema che esegua questa attività. In questo esempio, utilizzerai quanto segue:

  1. search_web utilizza Gemini con la Ricerca Google per cercare informazioni sul web sull'argomento specificato.
  2. record_notes salva le ricerche trovate sul web nello stato in modo che gli altri strumenti possano utilizzarle.
  3. write_report scrive il report utilizzando le informazioni trovate da ResearchAgent
  4. review_report esamina la segnalazione e fornisce un feedback.

La classe Context passa lo stato tra agenti/strumenti e ogni agente avrà accesso allo stato attuale del sistema.

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."

Creare un assistente multi-agente

Per creare un sistema multi-agente, devi definire gli agenti e le loro interazioni. Il sistema avrà tre agenti:

  1. Un ResearchAgent cerca informazioni sul web sull'argomento specificato.
  2. Un WriteAgent scrive il report utilizzando le informazioni trovate dal ResearchAgent.
  3. Un ReviewAgent esamina la segnalazione e fornisce un feedback.

Questo esempio utilizza la classe AgentWorkflow per creare un sistema multi-agente che esegue questi agenti in ordine. Ogni agente riceve un system_prompt che gli indica cosa deve fare e suggerisce come collaborare con gli altri agenti.

Se vuoi, puoi aiutare il tuo sistema multi-agente specificando con quali altri agenti può comunicare utilizzando can_handoff_to (in caso contrario, cercherà di capirlo da solo).

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"],
)

Gli agenti sono definiti, ora puoi creare AgentWorkflow ed eseguirlo.

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

Durante l'esecuzione del flusso di lavoro, puoi trasmettere in streaming eventi, chiamate di strumenti e aggiornamenti alla console.

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

Al termine del flusso di lavoro, puoi stampare l'output finale del report, nonché lo stato finale della revisione dell'agente di revisione.

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

Andare oltre con i workflow personalizzati

AgentWorkflow è un ottimo modo per iniziare a utilizzare i sistemi multi-agente. Ma cosa succede se hai bisogno di un maggiore controllo? Puoi creare un flusso di lavoro da zero. Ecco alcuni motivi per cui potresti voler creare il tuo flusso di lavoro:

  • Maggiore controllo sulla procedura: puoi decidere il percorso esatto che seguono i tuoi agenti. Ciò include la creazione di loop, la presa di decisioni in determinati punti o la collaborazione degli agenti in parallelo su attività diverse.
  • Utilizza dati complessi: vai oltre il semplice testo. I workflow personalizzati ti consentono di utilizzare dati più strutturati, come oggetti JSON o classi personalizzate, per input e output.
  • Utilizzare diversi contenuti multimediali: crea agenti in grado di comprendere ed elaborare non solo testo, ma anche immagini, audio e video.
  • Pianificazione più intelligente: puoi progettare un flusso di lavoro che crei prima un piano dettagliato prima che gli agenti inizino a lavorare. Questo è utile per le attività complesse che richiedono più passaggi.
  • Attiva l'autocorrezione: crea agenti in grado di rivedere il proprio lavoro. Se l'output non è soddisfacente, l'agente può riprovare, creando un ciclo di miglioramento finché il risultato non è perfetto.

Per saperne di più su LlamaIndex Workflows, consulta la documentazione di LlamaIndex Workflows.