在 .NET 中使用 Semantic Kernel 集成 AWS Bedrock Agent:环境准备、配置与七个实战示例
在 .NET 中使用 Semantic Kernel 集成 AWS Bedrock Agent环境准备、配置与七个实战示例【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel导读本文以 dotnet/samples/GettingStartedWithAgents/BedrockAgent/README.md 为骨架完整讲解在 Semantic Kernel 的 .NET 版本中使用AWS Bedrock Agent的全过程从 AWS 账号与 IAM 权限准备、用户机密user-secrets配置到如何基于 Agents.Bedrock.csproj 提供的BedrockAgent类型创建、调用和管理 Bedrock Agent。读完本文你将能够配置好运行环境通过代码创建与复用 Bedrock Agent并依次掌握 Code Interpreter、Kernel Functions、Trace 追踪、知识库检索、多 Agent 群聊以及 YAML 声明式创建等实战能力。一、前置条件在运行任何 Bedrock Agent 示例之前需要完成以下两方面的准备AWS 账号与模型访问权限你需要一个有效的 AWS 账号并在 Amazon Bedrock 控制台中为所选基础模型开启访问权限对应 README 中提到的 model access 页面。只有完成模型访问授权后续创建 Agent 时指定FoundationModel才不会被拒绝。AWS CLI 的安装与配置安装并配置 AWS CLI确保本地环境能够通过凭证访问 AWS API。语义内核的 Bedrock Agent 连接器底层依赖 AWS SDKAmazon.BedrockAgent与Amazon.BedrockAgentRuntime因此 AWS CLI 配置的凭证会被 SDK 自动读取使用。说明所有示例均为 xUnit 测试项目运行环境需要能访问 AWS 服务。示例项目位于dotnet/samples/GettingStartedWithAgents其 csproj 中通过ProjectReference引用了 Agents.Bedrock.csproj见 GettingStartedWithAgents.csproj。二、运行前的用户机密user-secrets配置README 指出运行示例前需要在项目中配置两个用户机密。示例项目在 GettingStartedWithAgents.csproj 中声明了UserSecretsId因此可以直接使用dotnet user-secrets命令写入配置。2.1BedrockAgent:AgentResourceRoleArn这是 Bedrock Agent 执行时扮演的 IAM 角色 ARN。获取方式在 AWS 控制台进入IAM → Roles点击目标角色在摘要Summary区域即可看到该角色的 ARN。dotnet user-secrets set BedrockAgent:AgentResourceRoleArn arn:aws:iam::...:role/...在示例基类 BaseBedrockAgentTest.cs 中可以看到该值会被传入CreateAgentRequest.AgentResourceRoleArn用于在 Bedrock 服务端创建 Agent 时绑定执行角色protected CreateAgentRequest GetCreateAgentRequest(string agentName) new() { AgentName agentName, Description AgentDescription, Instruction AgentInstruction, AgentResourceRoleArn TestConfiguration.BedrockAgent.AgentResourceRoleArn, FoundationModel TestConfiguration.BedrockAgent.FoundationModel, };2.2BedrockAgent:FoundationModel指定 Agent 使用的基础模型。你需要确认账号对该模型有访问权限——在 IAM 角色附加的策略中Resource部分会列出你有权访问的模型列表。模型 ID 以 AWS 官方文档中models-supported页面为准。dotnet user-secrets set BedrockAgent:FoundationModel ...从源码看模型 ID 会被直接设置为CreateAgentRequest.FoundationModel因此在示例中可以动态替换为你账号下可用的任意已授权模型。提示在 Step07_BedrockAgent_Declarative.cs 中这些机密还会以${BedrockAgent:FoundationModel}、${BedrockAgent:AgentResourceRoleArn}的占位符形式被 YAML 配置引用实现声明式创建详见第七节。三、为 IAM 角色添加bedrock:InvokeModelWithResponseStream权限当 Agent 需要流式streaming返回模型推理结果时必须为 IAM 角色授予bedrock:InvokeModelWithResponseStream操作权限。README 给出了完整的控制台操作步骤打开 IAM 控制台在左侧导航窗格Access management下选择Roles找到要编辑的角色并点击进入在Permissions policies标签页点击要编辑的策略在Permissions defined in this policy区域点击服务——如果你已有 Bedrock Agent 服务访问权应能看到Bedrock点击服务再点击Edit在右侧添加操作搜索InvokeModelWithResponseStream勾选该操作后滚动到底部点击Next按提示保存更改。从源码侧可以印证该权限的用途Step01_BedrockAgent.cs 的UseNewAgentStreaming测试调用了bedrockAgent.InvokeStreamingAsync(...)底层会通过AmazonBedrockAgentRuntimeClient触发流式推理因此需要对应 IAM action。四、基础示例创建、复用与流式调用 Agent4.1 核心类型在 Semantic Kernel 中Bedrock Agent 通过 BedrockAgent.cs 中的BedrockAgent类暴露。它继承自Agent构造函数接收三个核心参数public BedrockAgent( Amazon.BedrockAgent.Model.Agent agentModel, IAmazonBedrockAgent client, IAmazonBedrockAgentRuntime runtimeClient)agentModel已在 Bedrock Agent 服务上存在的一个 Agent 模型包含AgentId、AgentName、Instruction等元数据client用于管理 Agent创建、删除等的 Bedrock Agent 客户端runtimeClient用于 Agent 运行时推理的客户端。此外BedrockAgent.cs 定义了一个静态字段WorkingDraftAgentAlias TSTALIASID——Bedrock 会为工作草稿版本创建默认别名供运行时调用使用。4.2 创建新 Agent 并交互Step01_BedrockAgent.cs 展示了最小可用流程先通过CreateAndPrepareAgentAsync在服务端创建 Agent再用BedrockAgent包装后配合BedrockAgentThread发起对话// 创建 Agent服务端 var agentModel await this.Client.CreateAndPrepareAgentAsync(this.GetCreateAgentRequest(agentName)); var bedrockAgent new BedrockAgent(agentModel, this.Client, this.RuntimeClient); // 创建会话线程并提问 AgentThread bedrockAgentThread new BedrockAgentThread(this.RuntimeClient); var responses bedrockAgent.InvokeAsync( new ChatMessageContent(AuthorRole.User, Why is the sky blue in one sentence?), bedrockAgentThread, null); await foreach (ChatMessageContent response in responses) { this.Output.WriteLine(response.Content); } // 清理删除服务端 Agent 与线程 await bedrockAgent.Client.DeleteAgentAsync(new() { AgentId bedrockAgent.Id }); await bedrockAgentThread.DeleteAsync();要点InvokeAsync接受ICollectionChatMessageContent、可选的AgentThread、可选的BedrockAgentInvokeOptions与CancellationToken见 BedrockAgent.cs传入空消息集合会抛出InvalidOperationException见 BedrockAgent.cs示例在finally中主动删除服务端 Agent避免测试反复运行时在 AWS 侧累积资源。4.3 复用已存在的 AgentStep01_BedrockAgent.cs 展示了如何通过 Agent ID 加载已存在的 Agentvar agentId bedrock-agent-id; // 替换为实际 Agent ID var getAgentResponse await this.Client.GetAgentAsync(new() { AgentId agentId }); var bedrockAgent new BedrockAgent(getAgentResponse.Agent, this.Client, this.RuntimeClient);4.4 流式调用Step01_BedrockAgent.cs 展示了InvokeStreamingAsync的用法返回类型为StreamingChatMessageContent适合构建逐字输出的聊天体验。五、Code Interpreter让 Agent 执行代码并返回文件Step02_BedrockAgent_CodeInterpreter.cs 演示了如何为 Agent 启用代码解释器var agentModel await this.Client.CreateAndPrepareAgentAsync(this.GetCreateAgentRequest(agentName)); var bedrockAgent new BedrockAgent(agentModel, this.Client, this.RuntimeClient); // 关键创建代码解释器 action group 并让 Agent 就绪 await bedrockAgent.CreateCodeInterpreterActionGroupAsync();随后让 Agent 根据数据生成柱状图示例中的熊猫 5、老虎 8、狮子 3、猴子 6、海豚 2代码解释器会执行 Python 代码并产出图表文件。示例中通过response.Items.OfTypeBinaryContent().FirstOrDefault()提取返回的二进制文件见 Step02_BedrockAgent_CodeInterpreter.cs再调用binaryContent.WriteToFile(filePath, overwrite: true)将图表保存到测试程序集所在目录文件名从binaryContent.Metadata[Name]读取。若响应中没有文件示例会抛出InvalidOperationException(No file found in the response.)。六、Kernel Functions将 Semantic Kernel 插件接入 Bedrock Agent6.1 基本用法Step03_BedrockAgent_Functions.cs 展示了如何把 Semantic Kernel 插件Plugin注册为 Bedrock Agent 的函数// 1. 构造 Kernel 并注册插件 Kernel kernel new(); kernel.Plugins.Add(KernelPluginFactory.CreateFromTypeWeatherPlugin()); kernel.Plugins.Add(KernelPluginFactory.CreateFromTypeMenuPlugin()); // 2. 创建 BedrockAgent 并挂载 Kernel var bedrockAgent new BedrockAgent(agentModel, this.Client, this.RuntimeClient) { Kernel kernel, }; // 3. 将 Kernel 函数创建为 action group 并准备就绪 await bedrockAgent.CreateKernelFunctionActionGroupAsync();插件使用[KernelFunction]与[Description]特性声明语义内核会将这些元数据转换成 Bedrock 可识别的函数描述private sealed class WeatherPlugin { [KernelFunction, Description(Provides real-time weather information.)] public string Current([Description(The location to get the weather for.)] string location) $The current weather in {location} is 72 degrees.; [KernelFunction, Description(Forecast weather information.)] public string Forecast([Description(The location to get the weather for.)] string location) $The forecast for {location} is 75 degrees tomorrow.; }6.2 复杂类型返回示例还验证了函数可以返回复杂类型MenuPlugin的GetMenu()返回MenuItem[]GetItemPrice返回float?并包含Category、Name、Price、IsSpecial等属性的结构化数据见 Step03_BedrockAgent_Functions.cs。Agent 可以根据用户提问如今天的特色汤是什么、多少钱自主选择并调用对应函数。6.3 并行函数调用UseAgentWithParallelFunctionsAsync测试见 Step03_BedrockAgent_Functions.cs让 Agent 同时回答西雅图当前天气与西雅图天气预报演示 Bedrock Agent 支持在同一轮中并行调用多个 Kernel 函数。七、Trace观察 Agent 的思考过程Step04_BedrockAgent_Trace.cs 通过BedrockAgentInvokeOptions.EnableTrace true开启追踪BedrockAgentInvokeOptions options new() { EnableTrace true, }; var responses bedrockAgent.InvokeAsync( [new ChatMessageContent(AuthorRole.User, userQuery)], agentThread, options); await foreach (ChatMessageContent response in responses) { if (response.InnerContent is Listobject? innerContents) { // 可能存在多条 trace存放在 InnerContent 中 var traceParts innerContents.OfTypeTracePart().ToList(); foreach (var tracePart in traceParts) { this.OutputTrace(tracePart.Trace); } } }OutputTrace方法见 Step04_BedrockAgent_Trace.cs重点展示了Orchestration traceModelInvocationInput模型的系统提示词与函数描述等输入文本ModelInvocationOutput.RawResponse.Content模型原始输出如thinking、function_calls内的工具调用 XMLModelInvocationOutput.Metadata.Usage输入/输出 token 用量。示例输出可见 Agent 决策链条先决定调用Current获取实时天气再调用Forecast获取预报最后汇总答案。Trace 对排查 Agent 行为、理解函数选择逻辑与估算 token 消耗非常有用。八、File Search关联知识库进行 RAG 检索Step05_BedrockAgent_FileSearch.cs 演示将 Agent 与 Bedrock Knowledge Base 关联使 Agent 能基于文档集合回答问题private const string KnowledgeBaseId [KnowledgeBaseId]; // 替换为有效 ID var bedrockAgent new BedrockAgent(agentModel, this.Client, this.RuntimeClient); // 关联知识库并附带描述指令 await bedrockAgent.AssociateAgentKnowledgeBaseAsync( KnowledgeBaseId, You will find information here.);调用方式与基础示例一致——示例中的提问是什么是 Semantic Kernel假设知识库中存放了相关文档见 Step05_BedrockAgent_FileSearch.cs。由于需要预先创建知识库并持有合法KnowledgeBaseId该测试默认以[Fact(Skip ...)]跳过读者需替换 ID 后取消 Skip 才能运行。这为在 Bedrock Agent 上构建 RAG 应用提供了直接模板。九、多 Agent 群聊Bedrock Agent 与 ChatCompletionAgent 协作Step06_BedrockAgent_AgentChat.cs 演示如何将 Bedrock Agent 放入AgentGroupChat与一个充当西语翻译的ChatCompletionAgent对话var chat new AgentGroupChat(bedrockAgent, chatCompletionAgent) { ExecutionSettings new() { TerminationStrategy new MultiTurnTerminationStrategy(2), } }; string[] userQueries [ Why is the sky blue in one sentence?, Why do we have seasons in one sentence? ]; foreach (var userQuery in userQueries) { chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, userQuery)); await foreach (var response in chat.InvokeAsync()) { this.Output.WriteLine($[{response.AuthorName}]: {response.Content}); } }MultiTurnTerminationStrategy继承自TerminationStrategy通过MaximumIterations turns控制最多两个 Agent 各发言一轮后结束见 Step06_BedrockAgent_AgentChat.cs。这说明 Bedrock Agent 与语义内核其他 Agent 类型可以无缝混编在同一群聊中。十、声明式创建用 YAML 定义 Bedrock Agent10.1 基础 AgentStep07_BedrockAgent_Declarative.cs 使用BedrockAgentFactory.CreateAgentFromYamlAsync以 YAML 定义 Agent并通过${...}占位符从配置user-secrets取值type: bedrock_agent name: StoryAgent description: Story Telling Agent instructions: Tell a story suitable for children about the topic provided by the user. model: id: ${BedrockAgent:FoundationModel} connection: type: bedrock agent_resource_role_arn: ${BedrockAgent:AgentResourceRoleArn}10.2 加载已有 Agent只需提供id与类型即可复用已存在 Agent见 Step07_BedrockAgent_Declarative.csid: ${BedrockAgent:AgentId} type: bedrock_agent10.3 声明式启用工具YAML 中可通过tools列表声明式地启用各类工具代码解释器见 Step07_BedrockAgent_Declarative.cstools: - type: code_interpreter函数调用见 Step07_BedrockAgent_Declarative.cs函数需在运行时通过factory.CreateAgentFromYamlAsync(text, new() { Kernel this._kernel }, ...)传入挂载了对应插件的 Kerneltools: - id: Current type: function description: Provides real-time weather information. options: parameters: - name: location type: string required: true description: The location to get the weather for. - id: Forecast type: function description: Forecast weather information. options: parameters: - name: location type: string required: true description: The location to get the weather for.知识库检索见 Step07_BedrockAgent_Declarative.cstools: - type: knowledge_base description: You will find information here. options: knowledge_base_id: ${BedrockAgent:KnowledgeBaseId}声明式方式将 Agent 的定义与代码解耦便于通过配置文件管理和复用 Agent 资产。十一、底层实现与运行要点从源码结构看dotnet/src/Agents/Bedrock 目录中除BedrockAgent.cs外还包括BedrockAgentThread.cs封装会话线程session对应示例中显式创建与删除的BedrockAgentThreadBedrockAgentChannel.csAgent 与线程之间的通道实现负责运行时消息流转BedrockAgentInvokeOptions.cs提供EnableTrace等调用选项BedrockAgentFactory.cs位于Definition/子目录YAML 声明式创建的入口Extensions/下的若干扩展类承载CreateCodeInterpreterActionGroupAsync、CreateKernelFunctionActionGroupAsync、AssociateAgentKnowledgeBaseAsync等能力。运行示例时请注意示例以 xUnit 测试形式组织直接dotnet test运行会真实调用 AWS 服务并产生费用请确保账号有对应模型访问权每次创建后示例都会在finally中调用DeleteAgentAsync清理资源所有机密配置优先通过dotnet user-secrets写入本项目UserSecretsId见 GettingStartedWithAgents.csproj也可参考同仓库 settings.json 示例 的方式组织配置结构。十二、小结以 README 为核心结合 BedrockAgent 源码与七个示例你已掌握从零配置到高阶用法的完整路径场景示例文件关键 API基础创建/复用/流式Step01_BedrockAgent.csCreateAndPrepareAgentAsync、InvokeAsync、InvokeStreamingAsync代码解释器Step02_BedrockAgent_CodeInterpreter.csCreateCodeInterpreterActionGroupAsync、BinaryContentKernel 函数Step03_BedrockAgent_Functions.csCreateKernelFunctionActionGroupAsyncTrace 追踪Step04_BedrockAgent_Trace.csBedrockAgentInvokeOptions.EnableTrace知识库检索Step05_BedrockAgent_FileSearch.csAssociateAgentKnowledgeBaseAsync多 Agent 群聊Step06_BedrockAgent_AgentChat.csAgentGroupChat、TerminationStrategyYAML 声明式Step07_BedrockAgent_Declarative.csBedrockAgentFactory.CreateAgentFromYamlAsync在此基础上你可以在自己的 .NET 应用中直接引入Agents.Bedrock包以相同模式把 Bedrock Agent 接入 Semantic Kernel 的 Agent 生态组合函数、知识库与多 Agent 编排构建真实业务方案。【免费下载链接】semantic-kernelIntegrate cutting-edge LLM technology quickly and easily into your apps项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考