Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Permite A2AAgent que seu aplicativo se conecte a agentes remotos expostos por meio do protocolo Agente para Agente (A2A). Ele encapsula qualquer ponto de extremidade compatível com A2A como um padrão AIAgent, para que você possa usar métodos familiares como RunAsync e RunStreamingAsync interagir com agentes remotos, independentemente de qual estrutura ou tecnologia eles foram criados.
Introdução
Adicione o pacote NuGet necessário ao seu projeto:
dotnet add package Microsoft.Agents.AI.A2A --prerelease
Descoberta de agente
Antes de se comunicar com um agente A2A remoto, você precisa descobri-lo e criar uma AIAgent instância. O protocolo A2A define três estratégias de descoberta, cada uma com suporte do Agent Framework.
URI de Well-Known
Os agentes A2A podem tornar o Cartão do Agente detectável em um caminho padronizado: https://{domain}/.well-known/agent-card.json. Use o A2ACardResolver para buscar o cartão e criar um agente em uma única chamada:
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!"));
Dica
GetAIAgentAsync também aceita um parâmetro opcional A2AClientOptions para seleção de protocolo.
Descoberta de Catalog-Based
Em ambientes corporativos ou marketplaces públicos, os Cartões de Agente geralmente são gerenciados por um registro central. Se você já tiver obtido AgentCard um registro desse tipo, converta-o diretamente em um 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."));
Configuração Direta
Para sistemas fortemente acoplados ou cenários de desenvolvimento em que o ponto de extremidade do agente é conhecido antecipadamente, crie um A2AClient diretamente e converta-o em um 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?"));
Seleção de Protocolo
Os agentes A2A podem expor várias associações de protocolo, como HTTP+JSON e JSON-RPC. Por padrão, HTTP+JSON é preferencial em vez de JSON-RPC. Use A2AClientOptions.PreferredBindings para controlar explicitamente qual associação de protocolo é usada:
Note
O agente A2A remoto deve estar disponível em um ponto de extremidade que dê suporte à associação de protocolo selecionada.
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
O A2A dá suporte a respostas de streaming por meio de eventos Server-Sent. Use RunStreamingAsync para receber atualizações em tempo real à medida que o agente remoto processa a solicitação:
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);
}
}
Respostas em segundo plano
Os agentes A2A dão suporte a respostas em segundo plano para lidar com operações de execução longa. Quando um agente A2A remoto retorna uma tarefa em vez de uma mensagem imediata, o Agent Framework fornece um token de continuação que você pode usar para sondar resultados ou reconectar a fluxos interrompidos.
Sondagem para conclusão da tarefa
Para cenários que não são de streaming, use AllowBackgroundResponses para receber um token de continuação e sondar até que a tarefa seja concluída:
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);
Reconexão de fluxo
Em cenários de streaming, cada atualização pode incluir um token de continuação. Se o fluxo for interrompido, use o token para se reconectar e obter o fluxo de resposta desde o início:
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
Os agentes A2A dão suporte à reconexão de fluxo (obtendo o mesmo fluxo de resposta desde o início), não à retomada do fluxo de um ponto específico no fluxo.
Note
A documentação para agentes do Python A2A estará disponível em breve.