Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Il protocollo da agente a agente (A2A) consente la comunicazione standardizzata tra gli agenti creati con framework e tecnologie diversi. Questa pagina illustra l'esposizione degli agenti di Agent Framework come server A2A.
Per individuare e richiamare un agente A2A remoto, vedere il servizio agente A2A.
Che cos'è A2A?
A2A è un protocollo standardizzato che supporta:
- Individuazione agente tramite schede agente
- Comunicazione basata su messaggi tra agenti
- Processi agentici a lunga durata tramite attività
- Interoperabilità multipiattaforma tra diversi framework agente
Per altre informazioni, vedere la specifica del protocollo A2A.
La libreria Microsoft.Agents.AI.Hosting.A2A.AspNetCore fornisce l'integrazione di ASP.NET Core per esporre gli agenti tramite il protocollo A2A.
Pacchetti NuGet:
Example
Questo esempio minimo illustra come esporre un agente tramite A2A. L'esempio include dipendenze OpenAPI e Swagger per semplificare il test.
1. Creare un progetto API Web di base ASP.NET
Creare un nuovo progetto api Web core ASP.NET o usarne uno esistente.
2. Installare le dipendenze necessarie
Installare i pacchetti seguenti:
Eseguire i comandi seguenti nella directory del progetto per installare i pacchetti NuGet necessari:
# Hosting.A2A.AspNetCore for A2A protocol integration
dotnet add package Microsoft.Agents.AI.Hosting.A2A.AspNetCore --prerelease
# Libraries to connect to Microsoft Foundry
dotnet add package Azure.AI.Projects --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.Foundry --prerelease
# Swagger to test app
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Swashbuckle.AspNetCore
3. Configurare la connessione Microsoft Foundry
L'applicazione richiede una connessione al progetto Microsoft Foundry. Configurare l'endpoint e il nome della distribuzione usando dotnet user-secrets o le variabili di ambiente.
È anche possibile modificare semplicemente , appsettings.jsonma non è consigliabile per le app distribuite nell'ambiente di produzione perché alcuni dei dati possono essere considerati segreti.
dotnet user-secrets set "AZURE_OPENAI_ENDPOINT" "https://<your-openai-resource>.openai.azure.com/"
dotnet user-secrets set "AZURE_OPENAI_DEPLOYMENT_NAME" "gpt-4o-mini"
4. Aggiungere il codice a Program.cs
Sostituire il contenuto di Program.cs con il codice seguente ed eseguire l'applicazione:
using A2A.AspNetCore;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Extensions.AI;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddSwaggerGen();
string endpoint = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = builder.Configuration["AZURE_OPENAI_DEPLOYMENT_NAME"]
?? throw new InvalidOperationException("AZURE_OPENAI_DEPLOYMENT_NAME is not set.");
// Register the chat client
IChatClient chatClient = new AIProjectClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetProjectOpenAIClient()
.GetProjectResponsesClient()
.AsIChatClient(deploymentName);
builder.Services.AddSingleton(chatClient);
// Register an agent
var pirateAgent = builder.AddAIAgent("pirate", instructions: "You are a pirate. Speak like a pirate.");
var app = builder.Build();
app.MapOpenApi();
app.UseSwagger();
app.UseSwaggerUI();
// Expose the agent via A2A protocol. You can also customize the agentCard
app.MapA2A(pirateAgent, path: "/a2a/pirate", agentCard: new()
{
Name = "Pirate Agent",
Description = "An agent that speaks like a pirate.",
Version = "1.0"
});
app.Run();
Avvertimento
DefaultAzureCredential è utile per lo sviluppo, ma richiede un'attenta considerazione nell'ambiente di produzione. Nell'ambiente di produzione prendere in considerazione l'uso di credenziali specifiche ,ad esempio ManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.
Test dell'agente
Dopo aver eseguito l'applicazione, è possibile testare l'agente A2A usando il file seguente .http o tramite l'interfaccia utente di Swagger.
Il formato di input è conforme alla specifica A2A. È possibile specificare i valori per:
-
messageId- Identificatore univoco per questo messaggio specifico. È possibile creare il proprio ID (ad esempio, un GUID) o impostarlo sunullper consentire all'agente di generarne uno automaticamente. -
contextId- Identificatore della conversazione. Specificare il proprio ID per avviare una nuova conversazione o continuare una esistente riutilizzando un oggetto precedentecontextId. L'agente manterrà la cronologia delle conversazioni per lo stessocontextId. Agent genererà anche uno per l'utente, se non ne viene fornito alcuno.
# Send A2A request to the pirate agent
POST {{baseAddress}}/a2a/pirate/v1/message:stream
Content-Type: application/json
{
"message": {
"kind": "message",
"role": "user",
"parts": [
{
"kind": "text",
"text": "Hey pirate! Tell me where have you been",
"metadata": {}
}
],
"messageId": null,
"contextId": "foo"
}
}
Nota: sostituire {{baseAddress}} con l'endpoint server.
Questa richiesta restituisce la risposta JSON seguente:
{
"kind": "message",
"role": "agent",
"parts": [
{
"kind": "text",
"text": "Arrr, ye scallywag! Ye’ll have to tell me what yer after, or be I walkin’ the plank? 🏴☠️"
}
],
"messageId": "chatcmpl-CXtJbisgIJCg36Z44U16etngjAKRk",
"contextId": "foo"
}
La risposta include ( contextId identificatore della conversazione), messageId (identificatore del messaggio) e il contenuto effettivo dell'agente pirata.
Configurazione di AgentCard
AgentCard fornisce metadati sull'agente per l'individuazione e l'integrazione:
app.MapA2A(agent, "/a2a/my-agent", agentCard: new()
{
Name = "My Agent",
Description = "A helpful agent that assists with tasks.",
Version = "1.0",
});
È possibile accedere alla scheda agente inviando questa richiesta:
# Send A2A request to the pirate agent
GET {{baseAddress}}/a2a/pirate/v1/card
Nota: sostituire {{baseAddress}} con l'endpoint server.
Proprietà AgentCard
- Nome: nome visualizzato dell'agente
- Descrizione: breve descrizione dell'agente
- Versione: stringa di versione per l'agente
- URL: URL endpoint (assegnato automaticamente se non specificato)
- Funzionalità: metadati facoltativi relativi a streaming, notifiche push e altre funzionalità
Esposizione di più agenti
È possibile esporre più agenti in una singola applicazione, purché gli endpoint non si sovrappongano. Ecco un esempio:
var mathAgent = builder.AddAIAgent("math", instructions: "You are a math expert.");
var scienceAgent = builder.AddAIAgent("science", instructions: "You are a science expert.");
app.MapA2A(mathAgent, "/a2a/math");
app.MapA2A(scienceAgent, "/a2a/science");
Il agent-framework-a2a pacchetto espone un agente di Agent Framework tramite il protocollo A2A.
pip install agent-framework-a2a --pre
Testare un endpoint protetto
Usare un oggetto AuthInterceptor in un client di test per verificare un endpoint A2A protetto:
from a2a.client.auth.interceptor import AuthInterceptor
class BearerAuth(AuthInterceptor):
def __init__(self, token: str):
self.token = token
async def intercept(self, request):
request.headers["Authorization"] = f"Bearer {self.token}"
return request
async with A2AAgent(
name="secure-agent",
url="https://secure-a2a-agent.example.com",
auth_interceptor=BearerAuth("your-token"),
) as agent:
response = await agent.run("Hello!")
Esposizione di un agente di Agent Framework su A2A
Il pacchetto agent-framework-a2a fornisce un'implementazione A2AExecutor predefinita che adatta qualsiasi agente del framework Agent Framework al protocollo A2A lato server. Avvia l'agente, mappa i contenuti di output supportati agli eventi e agli artefatti A2A e gestisce gli aggiornamenti dello stato delle attività tramite il a2a-sdk ufficiale.
L'applicazione riunisce gli elementi che circondano il server SDK A2A: la scheda dell'agente, DefaultRequestHandler, l'archivio delle attività, le route o il generatore di applicazioni, l'autenticazione e la distribuzione. Per un confronto con gli adattatori gestiti dall'app e gli helper di conversione autonomi in agent-framework-hosting-a2a, consulta Ospitare autonomamente agenti A2A.
import uvicorn
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from a2a.types import AgentCapabilities, AgentCard, AgentInterface, AgentSkill
from agent_framework import Agent
from agent_framework.a2a import A2AExecutor
from agent_framework.openai import OpenAIChatClient
from starlette.applications import Starlette
flight_skill = AgentSkill(
id="Flight_Booking",
name="Flight Booking",
description="Search and book flights across Europe.",
tags=["flights", "travel", "europe"],
examples=[],
)
public_agent_card = AgentCard(
name="Europe Travel Agent",
description="Helps users search and book flights and hotels across Europe.",
version="1.0.0",
default_input_modes=["text"],
default_output_modes=["text"],
capabilities=AgentCapabilities(streaming=True),
supported_interfaces=[
AgentInterface(url="http://localhost:9999/", protocol_binding="JSONRPC"),
],
skills=[flight_skill],
)
agent = Agent(
client=OpenAIChatClient(),
name="Europe Travel Agent",
instructions="You are a helpful Europe Travel Agent.",
)
request_handler = DefaultRequestHandler(
agent_executor=A2AExecutor(agent, stream=True),
task_store=InMemoryTaskStore(),
agent_card=public_agent_card,
)
server = Starlette(
routes=[
*create_agent_card_routes(public_agent_card),
*create_jsonrpc_routes(request_handler, "/"),
]
)
uvicorn.run(server, host="0.0.0.0", port=9999)
A2AExecutor trasmette in streaming gli aggiornamenti dell'agente sotto forma di artefatti A2A quando l'agente sottostante supporta lo streaming e propaga l'context_id A2A come session_id della sessione dell'agente. È possibile sottoclassare A2AExecutor ed eseguire l'override del handle_events metodo per implementare trasformazioni personalizzate dal formato di output dell'agente agli eventi del protocollo A2A.
Protocollo A2A
Go Agent Framework supporta l'hosting degli agenti di Agent Framework tramite il protocollo da agente a agente (A2A) con il provider/a2aprovider pacchetto e i gestori del server A2A Go ufficiali.
Installare i pacchetti Agent Framework e A2A nel modulo Go:
go get github.com/microsoft/agent-framework-go
go get github.com/a2aproject/a2a-go/v2
Ospitare un agente tramite A2A
Creare o riutilizzare un agente di Agent Framework, descriverlo con una scheda agente A2A ed esporlo tramite una delle associazioni di trasporto A2A. In questo esempio, hostAgent è qualsiasi framework *agent.Agentagente. Il server ospita un endpoint JSON-RPC in / e serve la scheda dell'agente nel percorso A2A noto.
import (
"fmt"
"net/http"
"github.com/a2aproject/a2a-go/v2/a2a"
"github.com/a2aproject/a2a-go/v2/a2asrv"
"github.com/microsoft/agent-framework-go/provider/a2aprovider"
)
url := "http://localhost:5000"
card := &a2a.AgentCard{
Name: "InvoiceAgent",
Description: "Handles requests relating to invoices.",
Version: "1.0.0",
DefaultInputModes: []string{"text"},
DefaultOutputModes: []string{"text"},
Capabilities: a2a.AgentCapabilities{
Streaming: false,
},
SupportedInterfaces: []*a2a.AgentInterface{
a2a.NewAgentInterface(url, a2a.TransportProtocolJSONRPC),
},
}
mux := http.NewServeMux()
requestHandler := a2asrv.NewHandler(
a2aprovider.NewExecutor(hostAgent, a2aprovider.ExecutorConfig{}),
a2asrv.WithExtendedAgentCard(card),
)
mux.Handle("/", a2asrv.NewJSONRPCHandler(requestHandler))
mux.Handle(a2asrv.WellKnownAgentCardPath, a2asrv.NewStaticAgentCardHandler(card))
if err := http.ListenAndServe(":5000", mux); err != nil {
panic(fmt.Errorf("A2A server failed: %w", err))
}
Avvolgi lo stesso handler di richiesta con a2asrv.NewRESTHandler quando vuoi esporre il binding di trasporto HTTP+JSON. Impostare ExecutorConfig.AllowBackgroundResponses su true se l'agente ospitato deve essere autorizzato a restituire attività A2A per operazioni di lunga durata.
Vedere anche
- Panoramica delle integrazioni
- Servizio agente A2A
- Integrazione OpenAI
- Specifica del protocollo A2A
- Scoperta degli agenti