Agente A2A

A2AAgent permite a la aplicación conectarse a agentes remotos que se exponen a través del protocolo Agent-to-Agent (A2A). Encapsula cualquier punto de conexión compatible con A2A como estándar AIAgent, por lo que puede usar métodos conocidos como RunAsync e RunStreamingAsync interactuar con agentes remotos independientemente del marco o la tecnología con los que se crearon.

Introducción

Agregue el paquete NuGet necesario al proyecto:

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

Detección de agentes

Antes de comunicarse con un agente A2A remoto, debe detectarlo y crear una AIAgent instancia. El protocolo A2A define tres estrategias de detección, cada una compatible con Agent Framework.

URI de Well-Known

Los agentes de A2A pueden hacer que su tarjeta de agente se pueda detectar en una ruta de acceso estandarizada: https://{domain}/.well-known/agent-card.json. A2ACardResolver Use para capturar la tarjeta y crear un agente en una sola llamada:

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!"));

Sugerencia

GetAIAgentAsync también acepta un parámetro opcional A2AClientOptions para la selección de protocolo.

detección de Catalog-Based

En entornos empresariales o marketplaces públicos, las tarjetas de agente suelen administrarse mediante un registro central. Si ya tiene un AgentCard obtenido de este registro, conviértelo directamente en un 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."));

Configuración directa

Para sistemas estrechamente acoplados o escenarios de desarrollo en los que el punto de conexión del agente se conoce con antelación, cree un directamente A2AClient y conviértelo en :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?"));

Selección de protocolo

Los agentes de A2A pueden exponer varios enlaces de protocolo, como HTTP+JSON y JSON-RPC. De forma predeterminada, se prefiere HTTP+JSON sobre JSON-RPC. Use A2AClientOptions.PreferredBindings para controlar explícitamente qué enlace de protocolo se usa:

Nota:

El agente A2A remoto debe estar disponible en un punto de conexión que admita el enlace de protocolo seleccionado.

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 admite respuestas de streaming a través de eventos de Server-Sent. Use RunStreamingAsync para recibir actualizaciones en tiempo real a medida que el agente remoto procesa la solicitud:

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

Respuestas en segundo plano

Los agentes de A2A admiten respuestas en segundo plano para controlar las operaciones de larga duración. Cuando un agente A2A remoto devuelve una tarea en lugar de un mensaje inmediato, Agent Framework proporciona un token de continuación que puede usar para sondear los resultados o volver a conectarse a secuencias interrumpidas.

Sondeo de finalización de tareas

Para escenarios que no son de streaming, use AllowBackgroundResponses para recibir un token de continuación y sondear hasta que se complete la tarea:

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);

Reconexión de secuencias

En escenarios de streaming, cada actualización puede incluir un token de continuación. Si se interrumpe la secuencia, use el token para volver a conectarse y obtener el flujo de respuesta desde el principio:

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

Nota:

Los agentes de A2A admiten la reconexión de flujos (obteniendo la misma secuencia de respuesta desde el principio), no la reanudación de la secuencia desde un punto específico de la secuencia.

Nota:

La documentación de los agentes de Python A2A estará disponible próximamente.

Pasos siguientes