這 A2AAgent 讓你的應用程式能夠連接到透過代理 對代理(Agent-to-Agent,A2A)協定暴露的遠端代理。 它將任何符合 A2A 的端點包裝成標準AIAgent,因此你可以使用熟悉的方法,RunAsync例如RunStreamingAsync與遠端代理互動,無論他們是用什麼框架或技術建置的。
警告
在連接 A2A 代理前,請確認你信任該端點 URL 以及操作遠端代理的組織或發佈者。 將來自遠端代理程式的回應視為不受信任的應用程式輸入。 在程式碼產生副作用或渲染內容之前,先驗證它們。
若要將代理框架代理作為 A2A 伺服器暴露,請參見 帶有 A2A 的主機代理。
開始使用
為您的專案新增所需的 NuGet 套件:
dotnet add package Microsoft.Agents.AI.A2A --prerelease
代理發現
在與遠端 A2A 代理溝通前,你需要先發現它並建立一個 AIAgent 實例。 A2A 協議定義了三種 發現策略,每種策略皆由代理框架支援。
知名的 URI
A2A 代理人可以讓他們的 代理人卡 在標準化路徑上被發現: https://{domain}/.well-known/agent-card.json。 使用 來 A2ACardResolver 取得卡片並在一通電話中建立代理:
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!"));
參考資料: A2ACardResolverExtensions。
Tip
GetAIAgentAsync 也接受一個可選 A2AClientOptions 的協定 選擇參數。
基於目錄的發現
在企業環境或公共市場中,代理卡通常由中央登記局管理。 如果你已經從此類登記冊取得 ,AgentCard請直接轉換成: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."));
直接配置
對於緊密耦合的系統或開發情境,且代理端點事先已知,請直接建立 並A2AClient將其轉換為: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();
Console.WriteLine(await agent.RunAsync("What can you help me with?"));
參考資料: A2AClientExtensions。
AsAIAgent 適用於任何 IA2AClient 實作。 它與 A2AAgent 建構子接受一個可選 A2AAgentOptions 的設定,以設定代理人的 Id、 Name、 Description和 。
覆寫代理卡識別碼
預設情況下,基於卡片的建立會使用 卡片的 Name 和 Description。 傳遞 agentOptions 至 AgentCard.AsAIAgent 或 A2ACardResolver.GetAIAgentAsync 以覆寫 Id、 Name、 Description。 您未設定的屬性會回溯到卡片的值:
using A2A;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.A2A;
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync(new A2AAgentOptions
{
Id = "travel-agent-id",
Name = "travel-agent",
Description = "Plans trips and suggests itineraries."
});
參考資料: A2AAgentOptions、 A2ACardResolverExtensions。
當你通過 agentOptions時,將 協定設定 傳入 clientOptions。 未 agentOptions 命名相同參數 options的超載 。
協定選擇
A2A 代理程式可以公開 HTTP+JSON、JSON-RPC 和 gRPC 綁定。 預設情況下,卡片式建立可接受 HTTP+JSON 及 JSON-RPC。 SDK 會選擇第一個符合 A2AClientOptions.PreferredBindings的介面AgentCard.SupportedInterfaces,因此卡片的介面順序決定選擇順序。
設定 PreferredBindings 為限制選取範圍至您列出的綁定。 這會在建立時選擇用戶端;當請求失敗時,它不會啟用自動故障轉移:
using A2A;
using Microsoft.Agents.AI;
A2ACardResolver agentCardResolver = new(
new Uri("https://a2a-agent.example.com"));
AgentCard agentCard = await agentCardResolver.GetAgentCardAsync();
// Select HTTP+JSON. Use ProtocolBindingNames.JsonRpc for JSON-RPC.
A2AClientOptions options = new()
{
PreferredBindings = [ProtocolBindingNames.HttpJson]
};
AIAgent agent = agentCard.AsAIAgent(options: options);
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
備註
遠端 A2A 代理必須在支援所選協定綁定的端點上可用。
如果你已經知道端點及其綁定,請跳過卡片,直接建立綁定的用戶端即可。 每個用戶端都實 IA2AClient作 ,因此你可以用 AsAIAgent()來轉換:
| Binding | Client | 包裝 |
|---|---|---|
| JSON-RPC | A2AClient |
A2A |
| HTTP+JSON | A2AHttpJsonClient |
A2A |
| gRPC | A2AGrpcClient |
A2A.Grpc |
using A2A;
using Microsoft.Agents.AI;
A2AHttpJsonClient a2aClient = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = a2aClient.AsAIAgent();
參考資料: A2AClientExtensions。
gRPC
該 A2A 套件不包含 gRPC 支援。 新增 A2A SDK 的選用 gRPC 套件:
dotnet add package A2A.Grpc --prerelease
若要進行卡片式的發現,請在應用程式啟動時註冊一次 gRPC 綁定。 該卡必須宣告 gRPC 介面:
using A2A;
using A2A.Grpc;
using Microsoft.Agents.AI;
A2AGrpcClientRegistration.Register();
A2ACardResolver resolver = new(new Uri("https://a2a-agent.example.com"));
AIAgent agent = await resolver.GetAIAgentAsync(
options: new A2AClientOptions
{
PreferredBindings = [ProtocolBindingNames.Grpc]
});
Console.WriteLine(await agent.RunAsync("Hello over gRPC!"));
參考資料: A2ACardResolverExtensions,A2A範例。
Discovery 仍會透過 HTTP 擷取代理卡,然後連接到卡中列出的 gRPC 端點。 直接建立申請 A2AGrpcClient 不需要註冊。
驗證與 HTTP 設定
對於 HTTP 綁定,請將 配置 HttpClient 的參數傳遞至 httpClientAgentCard.AsAIAgentA2ACardResolver.GetAIAgentAsync或 。 使用它來設定驗證標頭或逾時。
關於在轉發憑證前驗證已公告端點來源的驗證,請參閱 A2A 驗證指南。
課程與後續任務
建立一個會話並在不同回合重複使用,以保留遠端對話內容:
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();
Console.WriteLine(await agent.RunAsync("Plan a trip to Paris.", session));
Console.WriteLine(await agent.RunAsync("Make it three days.", session));
參考編號: A2AAgent、 A2AAgentSession。
該工作階段是追蹤下列協定狀態的 :A2AAgentSession
| Property | Purpose |
|---|---|
ContextId |
識別遠端對話。 |
TaskId |
當回應包含最近任務時,用來識別最近一次任務。 |
TaskState |
記錄用於傳送下一則訊息的任務狀態。 |
當任務狀態為 InputRequired時,請以正常 RunAsync 或 RunStreamingAsync 呼叫方式傳送請求的輸入。 代理程式會設定外寄訊息 TaskId 以繼續執行該任務。 對於其他狀態,它會傳送先前的任務識別碼。ReferenceTaskIds
持續保存並還原DeserializeSessionAsync該工作階段SerializeSessionAsync,以保留上下文、任務 ID、任務狀態與狀態袋。 若要從已知的上下文與工作 ID 建立工作階段,請使用 A2AAgent.CreateSessionAsync 過載。
Streaming
用於 RunStreamingAsync 在遠端代理程式處理請求時接收更新。
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);
}
}
參考編號: AIAgent.RunStreamingAsync。
串流更新可以代表訊息、任務快照、狀態更新或工件更新。
工作階段會在串流列舉完成後更新,而非每次更新後。 若要從中斷的串流中恢復,請使用儲存的延續令牌,如 Stream reconnection 所示。
背景回應
A2A 代理程式支援長期執行作業的 背景回應 。 當遠端代理程式回傳處於 Submitted or Working 狀態的任務時,回應會包含一個用於輪詢或串流重新連線的延續權杖。
備註
使用 Agent Framework .NET A2A 託管套件所託管的代理程式,總是會以訊息回應,因此其回應不包含延續權杖。 如需更多資訊,請參閱 「任務支援」。
任務完成度的輪詢
設定 AllowBackgroundResponses 為請求立即回傳,而非等待任務完成。 這會設定 ReturnImmediately A2A 請求的設定,並需要一個明確的會話:
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();
// Request an immediate response when the remote agent creates a task.
AgentRunOptions options = new() { AllowBackgroundResponses = true };
// Start the initial run with a long-running task.
AgentResponse response = await agent.RunAsync(
"Analyze quantum computing applications in cryptography.",
session,
options: options);
// Poll while the task is submitted or working.
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);
參考編號: AIAgent.RunAsync、 AgentRunOptions。
當您傳遞續續權杖時,會 RunAsync 以 取得現有任務 GetTaskAsync ,而非重新執行。 不要在通話中加入新訊息。
缺少延續標記並不一定代表成功。 等待輸入或驗證,以及失敗、取消或拒絕的任務,也不會回傳任何續續權杖。 檢視任務狀態,直到 response.RawRepresentation 您的應用程式需要區分這些結果。
串流重新連線
處於 Submitted 或 Working 狀態的串流任務快照包含延續權杖。 在代幣出現時請儲存;之後的更新可能就不會再包含這個功能了。 如果串流中斷,請使用儲存的令牌重新連接任務的事件串流。
以下範例會在儲存一個延續權杖以模擬中斷後停止讀取,然後再用該權杖重新連線。
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(
"Analyze quantum computing applications in cryptography.",
session))
{
// Save the token for reconnection after an interruption.
if (update.ContinuationToken is { } token)
{
continuationToken = token;
// Stop reading to simulate a stream interruption.
break;
}
}
// Reconnect after the simulated interruption.
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);
}
}
}
參考編號: AIAgent.RunStreamingAsync、 AgentRunOptions。
備註
重新連線不會從特定事件或文字偏移量恢復。 根據需要處理重複的任務快照或工件內容。
Tools
A2AAgent 是包覆遠端 A2A 代理程式的傳輸層級包裝器。 遠端代理使用的任何工具都存在於遠端端,對你的程式碼是隱形的。 代理框架的工具類型(功能工具、程式碼直譯器、檔案搜尋、託管/本地 MCP 等)本身並未設定 A2AAgent ——以擴展遠端代理的功能、更改遠端代理的設定。
若要讓其他代理程式呼叫遠端代理程式,請使用 AsAIFunction()。 完整範例請參閱 A2A 範例。
開始使用
安裝 A2A 套件:
pip install agent-framework-a2a --pre
初始化
A2AAgent 根據您事先對遠端代理程式的了解程度,可以透過三種方式初始化。
直接網址
對於開發或緊密耦合系統,且端點已知:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
response = await agent.run("Hello!")
print(response.messages[0].text)
當只提供 URL 時, A2AAgent 會在內部建立最小代理卡並使用 JSON-RPC 連接。
建立 A2AAgent 回應 Cookie 的 HTTP 客戶端不會持久化。 如果遠端服務需要 Cookie 來進行認證、會話或負載平衡,請通過 httpx.AsyncClienthttp_client=。 將客戶範圍設定為一個已認證的委託人,並在你的申請中關閉它。
所提供的 HTTP 用戶端仍為呼叫者擁有,包括你也傳遞 client=。
代理人卡
如果你有登記或目錄的, AgentCard 請直接轉交:
from agent_framework.a2a import A2AAgent
async with A2AAgent(agent_card=agent_card) as agent:
response = await agent.run("Plan a trip to Paris.")
print(response.messages[0].text)
當提供時 AgentCard , A2AAgent 會 name 違約並 description 從卡片中扣除。 它會利用卡片的 supported_interfaces。
知名 URI(A2ACardResolver)
使用 A2ACardResolver 該 a2a-sdk 以發現遠端代理在標準已知路徑/.well-known/agent.json上():
import httpx
from a2a.client import A2ACardResolver
from agent_framework.a2a import A2AAgent
async with httpx.AsyncClient(timeout=60.0) as http_client:
resolver = A2ACardResolver(httpx_client=http_client, base_url="https://a2a-agent.example.com")
agent_card = await resolver.get_agent_card()
async with A2AAgent(agent_card=agent_card) as agent:
response = await agent.run("What can you help me with?")
print(response.messages[0].text)
Streaming
在遠端代理處理請求時,使用 stream=True 以即時接收更新:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
stream = agent.run("Write a short story about a robot.", stream=True)
async for update in stream:
for content in update.contents:
if content.text:
print(content.text, end="", flush=True)
final = await stream.get_final_response()
print(f"\n({len(final.messages)} message(s))")
二元附加元件
A2AAgent 以原始二進位 A2A 零件形式傳送資料備份 Content 。 零位元組有效載荷適用於串流與非串流執行。 媒體類型、資料 URI 參數、base64 編碼及字元驗證仍然適用。
長時間執行的工作
預設情況下, A2AAgent 會等待遠端代理完成後才返回。 對於長期執行的任務,設定 background=True 顯示一個延續代幣,方便日後投票或訂閱:
from agent_framework.a2a import A2AAgent
async with A2AAgent(name="worker", url="https://a2a-agent.example.com") as agent:
# Start a long-running task
response = await agent.run("Process this large dataset", background=True)
if response.continuation_token:
# Poll for completion later
result = await agent.poll_task(response.continuation_token)
print(result)
你也可以重新訂閱 SSE 串流,而不必輪詢:
# Resubscribe to the task's event stream
response = await agent.run(continuation_token=response.continuation_token)
對話身份(context_id)
A2AAgent 將持久協定狀態 AgentSession.service_session_id 儲存為 A2AServiceSessionId 映射:
| Field | 類型 | Purpose |
|---|---|---|
context_id |
str |
識別 A2A 對話。 |
task_id |
str \| None |
追蹤最近一次遠端任務,以及回應何時產生的。 |
task_state |
TaskState \| None |
記錄最新的任務狀態,讓下一個請求能繼續輸入所需的任務或參考已完成的任務。 |
當你的應用程式已經知道 A2A 上下文時,建立一個結構化狀態的會話:
from agent_framework import AgentSession
from agent_framework.a2a import A2AAgent, A2AServiceSessionId
async with A2AAgent(name="remote", url="https://a2a-agent.example.com") as agent:
session = AgentSession(
service_session_id=A2AServiceSessionId(
context_id="my-conversation-1",
task_id=None,
task_state=None,
)
)
# The A2A message uses context_id="my-conversation-1".
response = await agent.run("Hello!", session=session)
# A2AAgent updates task_id and task_state from the response.
response = await agent.run("Follow-up question", session=session)
你也可以從 AgentSession() 第一個回覆的結構化映射開始,然後填 A2AAgent 入。 持續維持一般會話 session.to_dict() 並恢復 AgentSession.from_dict(...);A2A 上下文、任務 ID 與任務狀態保持一致。
對於 中的 TASK_STATE_INPUT_REQUIRED任務,下一則訊息會設定該 task_id 任務繼續執行相同任務。 對於其他任務狀態,會傳送 reference_task_ids 先前的任務 ID,讓遠端代理能從先前結果細化或繼續。
前向選擇跑情境
選擇function_invocation_kwargsclient_kwargs或必須連接遠端服務時,可作為允許清單使用forwarded_kwargs:
async with A2AAgent(
name="remote",
url="https://a2a-agent.example.com",
forwarded_kwargs=["tenant_id", "trace"],
) as agent:
response = await agent.run(
"Create the report.",
function_invocation_kwargs={"tenant_id": "contoso", "secret": "not-forwarded"},
client_kwargs={"trace": {"id": "abc"}},
)
只有列出的金鑰會被送入SendMessageRequest.metadataagent_framework,並依其來源映射分組。 預設不會發送執行 kwargs,且元資料不會被加入 HTTP 標頭或訊息歷史。
接收服務使用獨立的允許清單:
from agent_framework.a2a import A2AExecutor
executor = A2AExecutor(
local_agent,
accepted_function_invocation_kwargs=["tenant_id"],
accepted_client_kwargs=["trace"],
)
服務預設不接受任何服務。 只有當用戶端轉發其金鑰,且服務接受來自匹配來源映射的相同金鑰時,值才會到達本地代理。 將轉發的元資料視為請求上下文,而非認證或授權。
轉發的值必須與 JSON 相容。 映射鍵必須是字串,數字必須有限,整數必須介於 -(2**53) 與 2**53之間,包含。
Protobuf Struct 將數字儲存為雙重值,因此整數以浮點數值形式出現。 在請求發送前,無效的選取值會被觸發 AgentInvalidRequestException 。
Authentication
使用 AuthInterceptor 以確保 A2A 端點的安全:
from a2a.client.auth.interceptor import AuthInterceptor
from agent_framework.a2a import A2AAgent
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!")
逾時設定
A2AAgent 接受 或 intfloat 秒數。 這個值適用於連接、讀取、寫入和池超時等元件。 傳遞 httpx.Timeout 物件以分別配置這些值:
import httpx
from agent_framework.a2a import A2AAgent
# Simple timeout (applies to all components)
async with A2AAgent(name="remote", url="https://example.com", timeout=120) as agent:
...
# Fine-grained timeout
async with A2AAgent(
name="remote",
url="https://example.com",
timeout=httpx.Timeout(connect=10.0, read=120.0, write=10.0, pool=5.0),
) as agent:
...
當沒有指定逾時時,預設值為:10秒連線、60秒讀取、10秒寫入、5秒池。
Tools
A2AAgent 是包覆遠端 A2A 代理程式的傳輸層級包裝器。 遠端代理使用的任何工具都存在於遠端端,對你的程式碼是隱形的。 代理框架的工具類型(功能工具、程式碼直譯器、檔案搜尋、託管/本地 MCP 等)本身並未設定 A2AAgent ——以擴展遠端代理的功能、更改遠端代理的設定。
如果你想讓 Foundry 代理以工具方式呼叫 A2A 代理,請參考工廠資料get_a2a_toolFoundryChatClient。
Go 透過套件 provider/a2aprovider 支援遠端 A2A 代理。
安裝 Agent Framework 與 A2A 套件:
go get github.com/microsoft/agent-framework-go
go get github.com/a2aproject/a2a-go/v2
連接遠端 A2A 代理
解析遠端代理卡,從它建立一個 A2A 用戶端,並將用戶端包裝成標準的代理框架代理:
import (
"context"
"github.com/a2aproject/a2a-go/v2/a2aclient"
"github.com/a2aproject/a2a-go/v2/a2aclient/agentcard"
"github.com/microsoft/agent-framework-go/agent"
"github.com/microsoft/agent-framework-go/provider/a2aprovider"
)
ctx := context.Background()
card, err := agentcard.DefaultResolver.Resolve(ctx, "http://localhost:5000")
if err != nil {
panic(err)
}
client, err := a2aclient.NewFromCard(ctx, card)
if err != nil {
panic(err)
}
a := a2aprovider.NewAgent(
client,
a2aprovider.AgentConfig{
Config: agent.Config{
Name: card.Name,
Description: card.Description,
},
},
)
resp, err := a.RunText(ctx, "Hello!").Collect()
提供者將 A2A context_id 與任務 ID 儲存在代理框架會話中,以便後續訊息能維持對話的連續性。
協定選擇
如果遠端代理宣告多個傳輸綁定,建立 A2A 用戶端時請設定優先傳輸方式:
client, err := a2aclient.NewFromCard(
ctx,
card,
a2aclient.WithConfig(a2aclient.Config{
PreferredTransports: []a2a.TransportProtocol{a2a.TransportProtocolHTTPJSON},
}),
)
當你想偏好 JSON-RPC 時就用 a2a.TransportProtocolJSONRPC 。
長時間執行的工作
A2A 任務透過代理框架的延續標記浮現。 以明確指定的工作階段和 agent.AllowBackgroundResponses(true) 啟動執行程序,然後在不提供任何新訊息的情況下,透過呼叫 Run 並傳入接續權杖來進行輪詢:
session, err := a.CreateSession(ctx)
if err != nil {
panic(err)
}
resp, err := a.RunText(
ctx,
"Process this large dataset.",
agent.WithSession(session),
agent.AllowBackgroundResponses(true),
).Collect()
if err != nil {
panic(err)
}
for resp.ContinuationToken != "" {
resp, err = a.Run(
ctx,
nil,
agent.WithSession(session),
agent.WithContinuationToken(resp.ContinuationToken),
).Collect()
if err != nil {
panic(err)
}
}
對於中斷的串流執行,請從最後收到的更新中擷取 update.ContinuationToken,並將其連同 agent.WithContinuationToken(token) 和 agent.Stream(true) 傳遞給之後的串流執行。
使用遠端 A2A 代理作為工具
解析每個遠端代理,用 a2aprovider.NewAgent包裝,然後轉換成工具。agenttool.New
tools := make([]tool.Tool, 0, len(agentURLs))
for _, agentURL := range agentURLs {
card, err := agentcard.DefaultResolver.Resolve(ctx, agentURL)
if err != nil {
panic(err)
}
client, err := a2aclient.NewFromCard(ctx, card)
if err != nil {
panic(err)
}
remoteAgent := a2aprovider.NewAgent(client, a2aprovider.AgentConfig{
Config: agent.Config{
Name: card.Name,
Description: card.Description,
},
})
tools = append(tools, agenttool.New(remoteAgent, agenttool.Config{}))
}
Tip
請參閱 A2A 提供者範例 及 A2A 代理作為工具範例 ,以獲取完整可執行的範例。
下一步
深入探討: