
Semantic Kernel A2A 协议实战构建多智能体 Client/Server 示例的完整指南【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel本指南以dotnet/samples/Demos/A2AClientServer示例为核心系统讲解如何在 Semantic Kernel.NET中基于 Google A2AAgent-to-Agent协议构建一个多智能体系统包括将 Semantic Kernel Agent 以 A2A 服务器形式对外发布、通过命令行客户端跨进程调用远程 Agent以及使用 REST Client 与 A2A Inspector 完成协议级调试验证。读完本文你将掌握 A2A Server 的启动与参数配置、A2A Client 的远程 Agent 编排方式以及三种不同的测试与验证手段。注意A2A 协议目前仍处于快速发展阶段示例会随协议演进持续更新。本示例基于A2A/A2A.AspNetCore包构建对应仓库内 Agents.A2A 源码而不是 README 中早期描述的 SharpA2A.Core运行请以当前仓库实际引用的包为准。示例总体架构该示例由两个组件组成演示了一个客户端 三个远程服务器的多智能体协作拓扑A2AServer一个 ASP.NET Core 主机进程你需要启动三个实例分别对应三个 A2A 服务器每个服务器只暴露一个 AgentInvoice发票Agent、Policy政策Agent与Logistics物流Agent。A2AClient一个带命令行界面的客户端应用通过 A2A 协议连接远程 A2A 服务器在回答用户问题时按需调用这些远程 Agent。整体拓扑如下图所示——Host Client Agent 作为编排中枢通过 A2A 协议访问三个远程 Agent示例的源码结构与实现原理示例代码集中在 A2AClientServer 目录下核心文件如下文件作用A2AServer/Program.cs解析--agentId/--agentType命令行参数依据配置选择 Chat Completion 或 Azure AI Foundry 实现并注册 A2A 端点A2AServer/HostAgentFactory.cs工厂方法分别创建基于 Chat Completion 与 Azure AI Foundry 的A2AHostAgent并生成对应的 Agent CardA2AServer/Plugins/InvoiceQueryPlugin.cs发票查询插件提供三个[KernelFunction]与内置模拟数据A2AClient/Program.cs客户端入口读取配置、初始化 Host 客户端 Agent并启动交互式命令行循环A2AClient/HostClientAgent.cs核心编排逻辑通过A2AClientA2ACardResolver连接远程 Agent并转换为 Kernel Function 供宿主 Agent 调用两个项目均面向net10.0除引用 NuGet 包A2A、A2A.AspNetCore外还以项目引用的方式直接关联仓库源码src/Agents/A2A/Agents.A2A.csproj、src/Agents/Core/Agents.Core.csproj、src/Agents/AzureAI/Agents.AzureAI.csproj与src/Connectors/Connectors.OpenAI/Connectors.OpenAI.csproj参见 A2AClient.csproj 与 A2AServer.csproj因此可直接跟随源码深入理解 A2A 的底层实现。服务器端如何把 Agent 暴露为 A2A 端点从 A2AServer/Program.cs 可以看到服务器端的关键链路通过遍历启动参数解析--agentId与--agentType不区分大小写随后从环境变量与 .NET User Secrets 读取配置若同时提供了A2AServer:Endpoint与--agentId则走Azure AI Foundry分支HostAgentFactory.CreateFoundryHostAgentAsync使用PersistentAgentsClient与AzureCliCredential获取已创建的 Agent 定义包装为AzureAIAgent否则若提供了A2AServer:ApiKey则走Chat Completion分支CreateChatCompletionHostAgentAsync构建 Kernel、AddOpenAIChatCompletion创建配置了FunctionChoiceBehavior.Auto()的ChatCompletionAgent两种分支都会为 Invoice / Policy / Logistics 分别构造符合规范的AgentCard包含名称、描述、版本、输入输出模式、能力与技能示例等字段最后通过app.MapA2A(hostAgent.TaskManager!, /)与app.MapWellKnownAgentCard(hostAgent.TaskManager!, /)注册消息端点与标准 Agent Card 发现端点/.well-known/agent-card.json。其中A2AHostAgent与A2AAgent等类型定义于仓库 src/Agents/A2A如 A2AHostAgent.cs、A2AAgent.cs。发票查询插件Agent 能力的具体载体InvoiceQueryPlugin.cs 是一个纯模拟数据插件内置 10 张发票记录包含交易号、发票号、公司名、发票日期与商品明细T-Shirts / Hats / Glasses 的数量与单价。它向模型暴露了三个 Kernel FunctionQueryInvoices(companyName, startDate, endDate)按公司名及可选时间范围检索QueryByTransactionId(transactionId)按交易号精确查询示例中TICKET-XYZ987即对应 Contoso 的INV789发票QueryByInvoiceId(invoiceId)按发票号查询。发票日期在初始化时随机落在最近两个月内。该插件正是示例中 Invoice Agent 回答订单数量不符类问题时依赖的工具函数。配置密钥与环境变量示例支持两种后端Chat Completion AgentOpenAI API与Azure AI AgentAzure AI Foundry。配置统一通过 .NET User Secrets 注入。配置 Chat Completion Agent首先为客户端提供 OpenAI API Keydotnet user-secrets set A2AClient:ApiKey ...如果服务器端也要使用 Chat Completion Agent则为服务器设置 OpenAI Keydotnet user-secrets set A2AServer:ApiKey ...随后在A2AServer目录下启动三个服务器实例每个实例对应一个 Agent端口互不相同cd A2AServer dotnet run --urls http://localhost:5000;https://localhost:5010 --agentType invoicecd A2AServer dotnet run --urls http://localhost:5001;https://localhost:5011 --agentType policycd A2AServer dotnet run --urls http://localhost:5002;https://localhost:5012 --agentType logistics每个实例同时绑定 HTTP 与 HTTPS 端口--agentType支持invoice、policy、logistics三种取值其他取值会在 Program.cs 中抛出ArgumentException。模型 ID 可通过A2AServer:ModelId覆盖默认值为gpt-4o-mini。配置 Azure AI Agents使用 Azure AI Foundry 时你需要先在 Foundry 项目中创建三个 Agent然后提供项目 Endpoint 与各 Agent 的 ID。各 Agent 的系统指令建议如下Invoice AgentYou specialize in handling queries related to invoices.Policy AgentYou specialize in handling queries related to policies and customer communications. Always reply with exactly this text: Policy: Short Shipment Dispute Handling Policy V2.1 Summary: For short shipments reported by customers, first verify internal shipment records (SAP) and physical logistics scan data (BigQuery). If discrepancy is confirmed and logistics data shows fewer items packed than invoiced, issue a credit for the missing items. Document the resolution in SAP CRM and notify the customer via email within 2 business days, referencing the original invoice and the credit memo number. Use the Formal Credit Notification email template.Logistics AgentYou specialize in handling queries related to logistics. Always reply with exactly: Shipment number: SHPMT-SAP-001 Item: TSHIRT-RED-L Quantity: 900接着设置 Azure AI Foundry 项目 Endpointdotnet user-secrets set A2AServer:Endpoint ...然后启动三个服务器实例注意此时需额外传入--agentIdcd A2AServer dotnet run --urls http://localhost:5000;https://localhost:5010 --agentId Invoice Agent Id --agentType invoicecd A2AServer dotnet run --urls http://localhost:5001;https://localhost:5011 --agentId Policy Agent Id --agentType policycd A2AServer dotnet run --urls http://localhost:5002;https://localhost:5012 --agentId Logistics Agent Id --agentType logistics从源码看Azure AI 分支使用AzureCliCredentialAzure CLI 登录凭据完成身份认证而 Agent 定义通过PersistentAgentsClient.Administration.GetAgentAsync(assistantId)从 Foundry 拉取具体可见 HostAgentFactory.cs。方式一使用 REST Client 测试 Agent示例自带一个 .http 文件可直接在 Visual Studio 中打开并点击发送无需额外安装工具。在 Visual Studio 中打开A2AServer/A2AServer.http文件头部定义了三个主机变量hostInvoice http://localhost:5000、hostPolicy http://localhost:5001、hostLogistics http://localhost:5002对每个 Agent 都有两类预置请求以 Invoice Agent 为例查询 Agent CardGET {{hostInvoice}}/.well-known/agent-card.json通过 A2A 协议发送消息POST {{hostInvoice}} Content-Type: application/json { id: 1, jsonrpc: 2.0, method: message/send, params: { id: 12345, message: { role: user, messageId: msg_1, parts: [ { kind: text, text: Show me all invoices for Contoso? } ] } } }请求体遵循 JSON-RPC 2.0 约定method为message/sendparams.message中携带role、messageId与parts文本片段。当前仓库中的.http文件还将消息体升级为带kind: message的完整消息结构见 A2AServer.http并覆盖了 Policy、Logistics 的卡片查询与消息发送请求可作为协议级测试的完整参考。查询 Agent Card 的示例输出如下通过 A2A 协议向 Agent 发送消息的示例输出如下方式二使用 A2A Inspector 调试验证A2A Inspector 是一个基于 Web 的工具专为帮助开发者检查、调试并验证实现了 Google A2A 协议的服务器而设计。它提供友好的界面与 A2A Agent 交互、查看通信过程并校验实现是否符合协议规范。使用 Docker 运行 Inspector 是上手最快的方式。运行后按以下步骤操作在浏览器中访问 Inspectorhttp://127.0.0.1:8080/输入你正在运行的 Agent 地址例如http://host.docker.internal:5000点击连接后Agent Card 会被展示并自动校验输入消息并通过 A2A 协议发送给 Agent响应会被自动校验并在界面中展示可以选中响应查看原始 JSON连接 Agent 后展示的 Agent Card发送消息后得到的响应示例响应对应的原始 JSON 内容配置 A2A 客户端A2A 客户端通过 A2A 协议连接远程 Agent。默认情况下客户端会连接示例 A2A Server 提供的三个 Agent其地址如下Invoice Agent:http://localhost:5000/Policy Agent:http://localhost:5001/Logistics Agent:http://localhost:5002/如需更换 Agent 列表使用分号分隔的 URL 字符串覆盖配置dotnet user-secrets set A2AClient:AgentUrls http://localhost:5000/;http://localhost:5001/;http://localhost:5002/从 A2AClient/Program.cs 可以看到客户端还会读取两个可选配置A2AClient:ModelId默认gpt-4.1与必填的A2AClient:ApiKeyAgentUrls未设置时的默认值正是上述三个地址。客户端编排的源码级原理客户端的能力源于 HostClientAgent.cs 中的InitializeAgentAsync对每个 Agent URL 创建A2AClient基于HttpClient超时 60 秒与A2ACardResolver先通过GetAgentCardAsync拉取 Agent Card再包装为A2AAgent对应仓库 src/Agents/A2A/A2AAgent.cs通过AgentKernelFunctionFactory.CreateFromAgent把每个远程 Agent 转换为 Kernel Function汇总成名为AgentPlugin的插件并挂载到 Kernel宿主ChatCompletionAgent名为HostClient开启FunctionChoiceBehavior.Auto()从而让大模型在回答问题时自动决定调用哪个远程 Agent自定义的ConsoleOutputFunctionInvocationFilter实现了IFunctionInvocationFilter在每次远程调用前后把调用参数与响应内容以缩进形式打印到控制台——这正是运行日志中Calling Agent .../Response from Agent ...片段的来源。客户端通过System.CommandLine解析命令行使用ChatHistoryAgentThread维护会话支持输入:q或quit退出见 A2AClient/Program.cs。运行完整示例按照以下步骤端到端运行整个示例按上文命令启动三个 A2A 服务器实例Chat Completion 或 Azure AI 配置二选一启动 A2A 客户端cd A2AClient dotnet run输入请求例如Customer is disputing transaction TICKET-XYZ987 as they claim the received fewer t-shirts than ordered.宿主客户端 Agent 会自动调用远程 Agent所有调用都会在控制台输出最终答案会综合远程 Agent 返回的信息。下述示例输出中三个 Agent 都被调用实际运行中可能只看到 Policy 与 Invoice Agent。A2A 客户端的示例输出A2AClient dotnet run info: A2AClient[0] Initializing Semantic Kernel agent with model: gpt-4o-mini User (:q or quit to exit): Customer is disputing transaction TICKET-XYZ987 as they claim the received fewer t-shirts than ordered. Calling Agent InvoiceAgent with arguments: query: TICKET-XYZ987 instructions: Investigate the transaction details for TICKET-XYZ987 and verify the number of t-shirts ordered versus the number received. Response from Agent InvoiceAgent: The invoice associated with the transaction ID TICKET-XYZ987 is for the company Contoso. It was issued on June 18, 2025. The products in the invoice include 150 T-Shirts priced at $10.00 each, 200 Hats priced at $15.00 each, and 300 Glasses priced at $5.00 each. If you need more details or a copy of the invoice, please let me know! Calling Agent LogisticsAgent with arguments: query: TICKET-XYZ987 instructions: Check the shipping details for TICKET-XYZ987, specifically the quantity of t-shirts dispatched to confirm if fewer t-shirts were sent. Response from Agent LogisticsAgent: Shipment number: SHPMT-SAP-001 Item: TSHIRT-RED-L Quantity: 900 Calling Agent PolicyAgent with arguments: query: TICKET-XYZ987 instructions: Review the policy regarding disputes and claims related to shipment discrepancies, especially concerning t-shirts. Response from Agent PolicyAgent: Policy: Short Shipment Dispute Handling Policy V2.1 Summary: For short shipments reported by customers, first verify internal shipment records (SAP) and physical logistics scan data (BigQuery). If discrepancy is confirmed and logistics data shows fewer items packed than invoiced, issue a credit for the missing items. Document the resolution in SAP CRM and notify the customer via email within 2 business days, referencing the original invoice and the credit memo number. Use the Formal Credit Notification email template. Agent: Heres the investigation result for transaction TICKET-XYZ987: 1. **Invoice Details**: The invoice for transaction TICKET-XYZ987 indicates that 150 t-shirts were ordered. 2. **Shipment Details**: The logistics records show that a total of 900 t-shirts were dispatched under the shipment number SHPMT-SAP-001. There seems to be a significant discrepancy between the number of t-shirts ordered and the number shipped. According to the Short Shipment Dispute Handling Policy, the next steps are as follows: 1. **Confirm Discrepancy**: Since the logistics data confirms that 900 t-shirts were packed, it is necessary to check if this aligns with the customers claim. 2. **Issue Credit**: If the customer is indeed correct and fewer items were actually received compared to what was invoiced, you would need to issue a credit for the missing items. 3. **Document Resolution**: Ensure to document the resolution in SAP CRM. 4. **Notify the Customer**: Notify the customer via email within 2 business days, using the Formal Credit Notification email template, and reference both the original invoice and the credit memo number. Please let me know if you would like to proceed with any specific action! User (:q or quit to exit):从输出可以看到完整的编排闭环宿主 Agent 先向 Invoice Agent 核实订单/发票明细150 件 T 恤再向 Logistics Agent 核实发货数量900 件最后依据 Policy Agent 返回的短装争议处理政策 V2.1组织处理步骤——发票、物流与政策三类信息被交叉验证后汇总为最终答复。这与 InvoiceQueryPlugin.cs 中TICKET-XYZ987对应的模拟发票数据完全吻合。小结通过这个示例可以掌握一套可复用的 A2A 集成路径服务器端用MapA2AMapWellKnownAgentCard暴露协议端点用A2AHostAgent包装任意 Semantic Kernel AgentChat Completion 或 Azure AI Foundry 皆可客户端用A2ACardResolver发现远程能力、用AgentKernelFunctionFactory将远程 Agent 变为可调用的 Kernel Function交由宿主 Agent 自动编排。配合 REST Client 与 A2A Inspector 两种调试手段即可在开发阶段完成协议合规性与消息链路的双重验证。相关实现细节可继续深入阅读仓库 dotnet/src/Agents/A2A 与 dotnet/samples/Demos/A2AClientServer 下的源码与示例。【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考