Nessun risultato. Prova con un altro termine.
Guide
Notizie
Software
Tutorial

Costruire l'architettura di agenti

Impariamo a creare agenti AI che collaborino tra loro usando altri agenti o servizi MCP (Model Context Protocol) come dei tool
Impariamo a creare agenti AI che collaborino tra loro usando altri agenti o servizi MCP (Model Context Protocol) come dei tool
Link copiato negli appunti

A questo punto abbiamo imparato a costruire tutti i tasselli fondamentali:

  • creare server MCP che sono in grado di offrire servizi tematici. Nel nostro caso, uno offre informazioni su hotel ed uno sui voli. Essenzialmente, abbiamo costruito dei servizi che accedono a database aziendali o ad altri servizi preesistenti e li offrono ad agenti AI. E' il modo con cui mettiamo know-how aziendale a disposizione di LLM;
  • definire agenti di Intelligenza Artificiale che coniugano la potenza di un LLM con dei tool ovvero strumenti che ne estendono le facoltà.

Quello che ci resta da fare è creare agenti che collaborino tra loro usando altri agenti o servizi MCP come dei tool.

La gerarchia di agenti

Continuiamo la nostra struttura piramidale creando:

  • due agenti specializzati, rispettivamente, uno nel dialogo con l'HotelService ed uno con il FlightService;
  • un TravelAgent che risolve problematiche di viaggio nel complesso interrogando i due agenti.

Come possiamo vedere quindi le richieste dell'utente arriveranno sino al nostro database con le informazioni ma passando da agenti a server MCP, il tutto coordinato da un LLM che nel nostro caso sarà un modello OpenAI.

Vediamo il codice nel dettaglio.

La gerarchia di agenti

Per prima cosa, creiamo degli oggetti MCPServerStreamableHttp che rappresentano un la connessione con i servizi MCP. Specifichiamo gli indirizzi locali su cui noi, coerentemente con quanto spiegato nella guida, abbiamo lanciato sulle porte 8001 e 8002 TCP:

import asyncio
from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp
hotel_mcp = MCPServerStreamableHttp(
    name="hotelservice",
    params={
        "url": "http://localhost:8002/mcp",
    },
)
flights_mcp = MCPServerStreamableHttp(
    name="flightsservice",
    params={
        "url": "http://localhost:8001/mcp",
    },
)

Fatto ciò, ci servono due agenti basati sull'OpenAI Agents SDK che useranno i due servizi MCP come tool:

hotel_agent = Agent(
    name="Hotel Agent",
    instructions="""
# Role
You are a hotel search specialist.
# Goal
Find hotels that match the user's requirements.
# Tools
Use the tools provided by the hotelservice MCP server to:
- search for hotels
- retrieve prices
- check availability
# Rules
- Use the MCP tools whenever hotel information is required.
- Do not invent hotels, prices, availability, or other facts.
- If the MCP service does not provide the requested information,
  clearly state that the information could not be found.
# Output
Return concise and factual results that can be used by the Travel Agent.
""",
    mcp_servers=[hotel_mcp],
)
flight_agent = Agent(
    name="Flight Agent",
    instructions="""
# Role
You are a flight search specialist.
# Goal
Find flights that match the user's requirements.
# Tools
Use the tools provided by the flightsservice MCP server to:
- search for flights
- retrieve prices
- check availability
# Rules
- Use the MCP tools whenever flight information is required.
- Do not invent flights, prices, availability, or other facts.
- If the MCP service does not provide the requested information,
  clearly state that the information could not be found.
# Output
Return concise and factual results that can be used by the Travel Agent.
""",
    mcp_servers=[flights_mcp],
)

Notiamo che il campo mcp_servers indica la variabile di tipo MCPServerStreamableHttp, definita sopra, che vuole usare come servizio di riferimento per il suo lavoro. Inoltre, nel campo instructions immettiamo dei prompt che ci siamo fatti definire da una AI in quanto, come accennato in precedenza, istruzioni in inglese, ben formattate e generate da AI avranno sempre più possibilità di essereben comprensibili per dei modelli LLM.

Infine, il nostro punto di riferimento, l'agente che coordina tutti gli agenti, il Travel Agent:

travel_agent = Agent(
    name="Travel Agent",
    instructions="""
# Role
You are a travel planning coordinator.
# Goal
Help the user plan a trip by coordinating specialized agents.
# Available specialists
## Hotel Agent
Use `cerca_hotel` for hotel-related requests.
## Flight Agent
Use `cerca_voli` for flight-related requests.
# Workflow
1. Understand the user's travel requirements.
2. Identify which specialists are needed.
3. Call the appropriate specialist agents.
4. Combine their results into a coherent answer.
5. Present the final answer to the user.
# Rules
- Use the specialist agents whenever their domain is relevant.
- You may call one or both specialists.
- Do not invent travel information.
- Do not assume that a missing result means that no option exists.
- Base your answer on information returned by the specialist agents.
# Output
Provide a concise and useful answer.
When appropriate, organize flight and hotel options separately.
""",
    tools=[
        hotel_agent.as_tool(
            tool_name="search_hotels",
            tool_description="""
Use this tool when the user needs hotel information,
including hotel search, prices, or availability.
The request is delegated to the Hotel Agent,
which has access to the hotelservice MCP server.
""",
        ),
        flight_agent.as_tool(
            tool_name="search_flights",
            tool_description="""
Use this tool when the user needs flight information,
including flight search, prices, or availability.
The request is delegated to the Flight Agent,
which has access to the flightsservice MCP server.
""",
        ),
    ],
)

nel quale, al di là delle istruzioni copiose e LLM-generated come già detto, notiamo la sezione tools in fondo in cui abbiamo definito gli altri due agenti as_tool in modo che l'agente principale sappia che deve usarli per trovare informazioni specifiche.

Il test finale

E' il momento di provare il tutto. Definiamo un prompt per la richiesta utente (che potremo dettagliare molto meglio di questo):

USER_PROMPT = """
Voglio organizzare un viaggio da Roma a Parigi.
Cerca opzioni disponibili nel database per il volo da Roma a Parigi e per un hotel a Parigi.
"""

e lanciamo, in modalità asincrona, il programma dal nostro main:

async def main():
    #connesioni con i server MCP
    async with hotel_mcp, flights_mcp:
        # invio richiesta all'agente
        result = await Runner.run(
            travel_agent,
            USER_PROMPT,
        )
        # Stampa dei risultati
        print(result.final_output)
if __name__ == "__main__":
    asyncio.run(main())

All'esecuzione, otterremo una descrizione delle possibilità di viaggio che, ovviamente, avrà trovato in quanto calzanti con i dati di prova inseriti nel database.

Cosa fare ora?

A questo punto possiamo dire di avere una bella base di architettura per le mani: non dobbiamo fare altro che estenderla.

Immaginiamo, ad esempio, di prendere una qualche fonte di informazione o funzionalità che abbiamo a disposizione in azienda e vogliamo che un nostro software sia in grado di sfruttarla con la forza di un LLM: ci basterà creare servizi MCP che la integrino e degli agenti che sappiano interagire con questi, magari non con un main di questo tipo ma un servizio di API raggiungibile da interfacce web o mobile.

Avremo posto le basi per la versione basata sull'Intelligenza Artificiale di un nostro servizio aziendale.

Se vuoi aggiornamenti su Costruire l'architettura di agenti inserisci la tua email nel box qui sotto:

Compilando il presente form acconsento a ricevere le informazioni relative ai servizi di cui alla presente pagina ai sensi dell'informativa sulla privacy.

Ti consigliamo anche