Agente A2A

A2AAgent consente all'applicazione di connettersi agli agenti remoti esposti tramite il protocollo da agente a agente (A2A). Esegue il wrapping di qualsiasi endpoint conforme a A2A come standard AIAgent, in modo da poter usare metodi familiari come RunAsync e RunStreamingAsync per interagire con gli agenti remoti indipendentemente dal framework o dalla tecnologia con cui sono stati creati.

Getting Started

Aggiungere il pacchetto NuGet necessario al progetto:

dotnet add package Microsoft.Agents.AI.A2A --prerelease

Individuazione agenti

Prima di comunicare con un agente A2A remoto, è necessario individuarlo e creare un'istanza AIAgent di . Il protocollo A2A definisce tre strategie di individuazione, ognuna supportata da Agent Framework.

URI Well-Known

Gli agenti A2A possono rendere individuabile la scheda agente in un percorso standardizzato: https://{domain}/.well-known/agent-card.json. A2ACardResolver Usare per recuperare la scheda e creare un agente in una singola chiamata:

using A2A;
using Microsoft.Agents.AI;

// Initialize a resolver pointing at the remote agent's host.
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));

// Resolve the agent card and create an AIAgent in one step.
AIAgent agent = await resolver.GetAIAgentAsync();

// Use the agent.
Console.WriteLine(await agent.RunAsync("Hello!"));

Suggerimento

GetAIAgentAsync accetta anche un parametro facoltativo A2AClientOptions per la selezione del protocollo.

individuazione Catalog-Based

Negli ambienti aziendali o nei marketplace pubblici, le schede agente vengono spesso gestite da un registro centrale. Se è già AgentCard stato ottenuto da un registro di questo tipo, convertirlo direttamente in :AIAgent

using A2A;
using Microsoft.Agents.AI;

// Assume agentCard was retrieved from a registry or catalog.
AgentCard agentCard = await GetAgentCardFromRegistryAsync("travel-planner");

AIAgent agent = agentCard.AsAIAgent();

Console.WriteLine(await agent.RunAsync("Plan a trip to Paris."));

Configurazione diretta

Per gli scenari di sviluppo o sistemi strettamente associati in cui l'endpoint agente è noto in anticipo, creare un oggetto A2AClient direttamente e convertirlo in :AIAgent

using A2A;
using Microsoft.Agents.AI;

// Create a client pointing at the known agent endpoint.
A2AClient a2aClient = new(new Uri("https://a2a-agent.example.com"));

AIAgent agent = a2aClient.AsAIAgent(name: "my-agent", description: "A helpful assistant.");

Console.WriteLine(await agent.RunAsync("What can you help me with?"));

Selezione protocollo

Gli agenti A2A possono esporre più associazioni di protocollo, ad esempio HTTP+JSON e JSON-RPC. Per impostazione predefinita, HTTP+JSON è preferibile rispetto a JSON-RPC. Usare A2AClientOptions.PreferredBindings per controllare in modo esplicito quale associazione di protocollo viene usata:

Note

L'agente A2A remoto deve essere disponibile in un endpoint che supporta l'associazione di protocollo selezionata.

using A2A;
using Microsoft.Agents.AI;

A2ACardResolver agentCardResolver = new(new Uri("https://a2a-agent.example.com"));

AgentCard agentCard = await agentCardResolver.GetAgentCardAsync();

// Prefer HTTP+JSON protocol binding. For JSON-RPC, set PreferredBindings = [ProtocolBindingNames.JsonRpc]
A2AClientOptions options = new()
{
    PreferredBindings = [ProtocolBindingNames.HttpJson]
};

AIAgent agent = agentCard.AsAIAgent(options: options);

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

Streaming

A2A supporta lo streaming delle risposte tramite eventi di Server-Sent. Usare RunStreamingAsync per ricevere gli aggiornamenti in tempo reale quando l'agente remoto elabora la richiesta:

using A2A;
using Microsoft.Agents.AI;

A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();

await foreach (var update in agent.RunStreamingAsync("Write a short story about a robot."))
{
    if (!string.IsNullOrEmpty(update.Text))
    {
        Console.Write(update.Text);
    }
}

Risposte in background

Gli agenti A2A supportano le risposte in background per la gestione delle operazioni a esecuzione prolungata. Quando un agente A2A remoto restituisce un'attività anziché un messaggio immediato, Agent Framework fornisce un token di continuazione che è possibile usare per eseguire il polling dei risultati o riconnettersi a flussi interrotti.

Polling per il completamento attività

Per gli scenari non di streaming, usare AllowBackgroundResponses per ricevere un token di continuazione ed eseguire il polling fino al completamento dell'attività:

using A2A;
using Microsoft.Agents.AI;

A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();

AgentSession session = await agent.CreateSessionAsync();

// AllowBackgroundResponses must be true so the server returns immediately with a continuation token
// instead of blocking until the task is complete.
AgentRunOptions options = new() { AllowBackgroundResponses = true };

// Start the initial run with a long-running task.
AgentResponse response = await agent.RunAsync(
    "Conduct a comprehensive analysis of quantum computing applications in cryptography.",
    session,
    options: options);

// Poll until the response is complete.
while (response.ContinuationToken is { } token)
{
    // Wait before polling again.
    await Task.Delay(TimeSpan.FromSeconds(2));

    // Continue with the token.
    response = await agent.RunAsync(session, options: new AgentRunOptions { ContinuationToken = token });
}

Console.WriteLine(response);

Riconnessione di flusso

Negli scenari di streaming, ogni aggiornamento può includere un token di continuazione. Se il flusso viene interrotto, usare il token per riconnettersi e ottenere il flusso di risposta dall'inizio:

using A2A;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync();

AgentSession session = await agent.CreateSessionAsync();

ResponseContinuationToken? continuationToken = null;

await foreach (var update in agent.RunStreamingAsync(
    "Conduct a comprehensive analysis of quantum computing applications in cryptography.",
    session))
{
    // Save the continuation token to reconnect later if the stream is interrupted.
    // Continuation tokens are only returned for long-running tasks. If the A2A agent
    // returns a message instead of a task, the continuation token will not be initialized.
    if (update.ContinuationToken is { } token)
    {
        continuationToken = token;
    }
}

// If the stream was interrupted and a continuation token was captured,
// reconnect to the response stream using the saved continuation token.
if (continuationToken is not null)
{
    await foreach (var update in agent.RunStreamingAsync(
        session,
        options: new() { ContinuationToken = continuationToken }))
    {
        if (!string.IsNullOrEmpty(update.Text))
        {
            Console.WriteLine(update.Text);
        }
    }
}

Note

Gli agenti A2A supportano la riconnessione del flusso (ottenendo lo stesso flusso di risposta dall'inizio), non la ripresa del flusso da un punto specifico nel flusso.

Note

La documentazione per gli agenti Python A2A sarà presto disponibile.

Passaggi successivi