
AutoGen .NET 框架入门用事件驱动模型构建可扩展的多智能体 AI 系统【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogenAutoGen .NET 是微软 AutoGen 多智能体框架的 .NET 实现定位为用于构建 AI 智能体与应用的事件驱动编程框架docs/dotnet/index.md。本文以仓库中docs/dotnet/index.md这份 .NET 文档门户为主体完整覆盖其介绍的包体系与安装方式并结合仓库源码与 GettingStarted 示例 深入讲解智能体Agent、消息Message、订阅Subscription与运行时Runtime的核心机制读完后你将能够在 .NET 应用中定义智能体、完成本地流程编排并理解分布式 gRPC 运行时的扩展路径。一、AutoGen .NET 的整体定位官方文档门户docs/dotnet/index.md将 AutoGen .NET 划分为两大板块板块定位适用场景Core事件驱动的编程框架用于构建可扩展的多智能体 AI 系统业务流程中确定性与动态的智能体工作流、多智能体协作研究、跨语言分布式智能体、与事件驱动/云原生应用集成AgentChat构建对话式单/多智能体应用的编程框架构建在 Core 之上聊天中心chat-centric的对话编排应用文档明确给出的选型建议是如果你要构建工作流或分布式智能体系统请从 Core 开始Start here if you are building workflows or distributed agent systems。从源码结构看dotnet/src/Microsoft.AutoGen/这一分层得到了印证Contracts/核心契约包含AgentId、AgentProxy、IAgent、IHandle、TopicId、MessageContext等类型定义Core/进程内运行时实现包含BaseAgent、InProcessRuntime、AgentsApp、TypeSubscriptionAttribute等Core.Grpc/分布式系统的 .NET 客户端运行时API 与 Core 保持一致RuntimeGateway.Grpc/分布式系统的服务端网关支持多网关管理智能体集群并实现 Python 与 .NET 智能体的跨语言互操作AgentHost/基于 .NET Aspire 的宿主工程用于托管 gRPC 服务Extensions/对 Aspire、Microsoft.Extensions.AIMEAI、Semantic Kernel 的集成扩展AgentChat/对话编排实现含RoundRobinGroupChat、ChatAgentBase、终止条件Terminations等Agents/一组可直接使用的默认智能体如InferenceAgent、ConsoleAgent、FileAgent。二、包体系与安装方式2.1 Core 与 AgentChat 两条安装路径文档门户给出的 Core 安装命令docs/dotnet/index.mddotnet add package Microsoft.AutoGen.Contracts dotnet add package Microsoft.AutoGen.Core # optionally - for distributed agent systems: dotnet add package Microsoft.AutoGen.RuntimeGateway.Grpc dotnet add package Microsoft.AutoGen.AgentHost # other optional packages dotnet add package Microsoft.AutoGen.Agents dotnet add package Microsoft.AutoGen.Extensions.Aspire dotnet add package Microsoft.AutoGen.Extensions.MEAI dotnet add package Microsoft.AutoGen.Extensions.SemanticKernel即ContractsCore是单进程内编写并运行智能体的最小集合RuntimeGateway.GrpcAgentHost面向跨进程、跨语言的分布式场景Agents与三个Extensions.*包为可选增强。更详细的安装文档 Installation 补充了三种等价方式并给出了带版本号0.4.0-dev.1的示例dotnet add package Microsoft.AutoGen.Contracts --version 0.4.0-dev.1 dotnet add package Microsoft.AutoGen.Core --version 0.4.0-dev.1Package Manager 方式PM NuGet\Install-Package Microsoft.AutoGen.Contracts -Version 0.4.0-dev.1 PM NuGet\Install-Package Microsoft.AutoGen.Core -Version 0.4.0-dev.1或直接写入 csproj 的PackageReferencePackageReference IncludeMicrosoft.AutoGen.Contracts Version0.4.0-dev.1 / PackageReference IncludeMicrosoft.AutoGen.Core Version0.4.0-dev.1 /该文档还明确了各包的职责边界Microsoft.AutoGen.AgentChat—— 在 Core SDK 之上实现聊天中心的多智能体编排Microsoft.AutoGen.Agents—— 提供少量开箱即用的默认智能体Microsoft.AutoGen.Extensions—— 对 Aspire、Microsoft.Extensions.AI、Semantic Kernel 的扩展支持Microsoft.AutoGen.Core.Grpc—— 分布式系统中智能体的 .NET 客户端运行时API 与Microsoft.AutoGen.Core相同意味着从单进程切到分布式API 不变Microsoft.AutoGen.RuntimeGateway.Grpc—— 分布式系统的 .NET 服务端可运行多个网关来管理智能体集群并启用跨语言互操作Microsoft.AutoGen.AgentHost—— 托管 gRPC 服务的 .NET Aspire 工程。2.2 从源码结构印证包边界对照 dotnet/src/Microsoft.AutoGen/ 下的工程划分每个 NuGet 包都对应一个 csprojMicrosoft.AutoGen.Contracts.csproj、Microsoft.AutoGen.Core.csproj、Microsoft.AutoGen.Core.Grpc.csproj、Microsoft.AutoGen.RuntimeGateway.Grpc.csproj、Microsoft.AutoGen.AgentHost.csproj、Microsoft.AutoGen.AgentChat.csproj、Microsoft.AutoGen.Agents.csproj以及Extensions/下的Microsoft.AutoGen.Extensions.Aspire.csproj、Microsoft.AutoGen.Extensions.MEAI.csproj、Microsoft.AutoGen.Extensions.SemanticKernel.csproj。这与文档中的包清单一一对应可以确认文档描述的就是当前仓库实际的构建产物。分布式网关内部还依赖 Orleans见RuntimeGateway.Grpc/Services/Orleans/下的RegistryGrain.cs、MessageRegistryGrain.cs等从源码结构看网关用 Orleans 的 Grain 来实现智能体注册表与消息注册表的分布式状态管理。三、核心概念速览AgentId、Topic 与订阅在动手写代码前需要理解三个基础类型均位于Microsoft.AutoGen.Contracts即 Contracts 工程AgentId智能体实例在运行时含分布式运行时中的唯一标识充当接收消息的地址。从 AgentId.cs 可见它由Type与Key两个字段组成支持type/key字符串互转AgentId.FromStr并带有严格校验Type必须匹配^[a-zA-Z_][a-zA-Z0-9_]*$字母/数字/下划线且不能以数字开头Key只能包含 ASCII 32–126 的可见字符。TopicId消息的发布目标主题。智能体先订阅某个主题才能收到发布到该主题上的消息。订阅Subscription分为按类型订阅[TypeSubscription(topic)]与按类型前缀订阅[TypePrefixSubscription]实现见 TypePrefixSubscriptionAttribute.cs使智能体响应某类消息并产出某类消息。四、实战Modifier / Checker 倒计时示例官方 Tutorial 定义了两个智能体Modifier与Checker共同完成从 10 倒数到 1 的计数流程Modifier修改计数Checker检查计数并在到达 1 时停止应用。完整示例代码位于 dotnet/samples/GettingStarted/。4.1 定义消息类型消息就是普通的 C# 类。示例用CountMessage传递当前计数用CountUpdate传递更新后的计数CountMessage.cs、CountUpdate.csnamespace GettingStartedSample; public class CountMessage { public int Content { get; set; } }namespace GettingStartedSample; public class CountUpdate { public int NewCount { get; set; } }教程强调把消息类型拆分为强类型类才能构建智能体响应某些类型、产出某些类型的工作流——这正是类型化订阅type subscription的基础。4.2 继承 BaseAgent 创建智能体AutoGen 中智能体是一个能收发消息的类消息到达后做什么由智能体自身逻辑决定。定义方式是继承Microsoft.AutoGen.Core.BaseAgentusing Microsoft.AutoGen.Contracts; using Microsoft.AutoGen.Core; public class Modifier( AgentId id, IAgentRuntime runtime, ) : BaseAgent(id, runtime, MyAgent, null), { }AgentId和IAgentRuntime总是由运行时注入构造函数并转发给基类另两个参数是智能体描述与可选的 logger。这一机制在 BaseAgent.cs 中得到确认基类构造函数保存Id、Runtime、Description并在构造时通过ReflectInvokers()反射收集智能体实现的所有IHandle/IHandle,接口建立消息类型 → HandlerInvoker的字典。4.3 实现 Handler 并添加订阅要让Modifier收到CountMessage、修改计数后产出CountUpdate需要实现IHandleCountMessage接口并用[TypeSubscription]特性声明订阅主题[TypeSubscription(default)] public class Modifier( // ... ) : BaseAgent(...), IHandleCountMessage { public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext) { // ... } }[TypeSubscription(default)]把智能体绑定到名为default的主题没有这一步消息不会投递给智能体。消息到达时BaseAgent.OnMessageAsyncBaseAgent.cs会先取消息的运行时类型从handlerInvokers字典查找匹配的 invoker 并调用找不到则返回 null——也就是说类型不匹配的消息会被静默忽略。4.4 发布消息与传入自定义参数Handler 内通过PublishMessageAsync把结果发布到指定主题教程还演示了如何向智能体传入自定义参数一个用于修改计数的函数public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext) { int newValue item.Content - 1; Console.WriteLine($\nModifier:\nModified {item.Content} to {newValue}); CountUpdate updateMessage new CountUpdate { NewCount newValue }; await this.PublishMessageAsync(updateMessage, topic: new TopicId(default)); }PublishMessageAsync最终委托给Runtime.PublishMessageAsync见 BaseAgent.cs并自动带上sender: this.Id。SendMessageAsync则用于点对点 RPC 式投递二者共同构成智能体的通信原语。Modifier 的完整最终实现Modifier.cs通过构造函数注入ModifyF modifyFunc使如何修改计数可配置using ModifyF System.Funcint, int; namespace GettingStartedSample; [TypeSubscription(default)] public class Modifier( AgentId id, IAgentRuntime runtime, ModifyF modifyFunc ) : BaseAgent(id, runtime, Modifier, null), IHandleCountMessage { public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext) { int newValue modifyFunc(item.Content); Console.WriteLine($\nModifier:\nModified {item.Content} to {newValue}); CountUpdate updateMessage new CountUpdate { NewCount newValue }; await this.PublishMessageAsync(updateMessage, topic: new TopicId(default)); } }4.5 Checker检查条件并停止应用Checker订阅同一个default主题响应CountUpdate。未达终止条件时它把新计数包装成CountMessage重新发布驱动下一轮迭代达到条件时则通过依赖注入获得的IHostApplicationLifetime停止整个应用Checker.cs[TypeSubscription(default)] public class Checker( AgentId id, IAgentRuntime runtime, IHostApplicationLifetime hostApplicationLifetime, TerminationF runUntilFunc ) : BaseAgent(id, runtime, Modifier, null), IHandleCountUpdate { public async ValueTask HandleAsync(CountUpdate item, MessageContext messageContext) { if (!runUntilFunc(item.NewCount)) { Console.WriteLine($\nChecker:\n{item.NewCount} passed the check, continue.); await this.PublishMessageAsync(new CountMessage { Content item.NewCount }, new TopicId(default)); } else { Console.WriteLine($\nChecker:\n{item.NewCount} failed the check, stopping.); hostApplicationLifetime.StopApplication(); } } }这里体现了 Core 的消息循环工作流模式CountMessage → Modifier → CountUpdate → Checker → CountMessage → ...直到 Checker 判定x 1触发停机。4.6 组装与启动AgentsAppBuilder应用入口Program.cs分三步。第一步定义修改与终止两个函数using ModifyF System.Funcint, int; using TerminationF System.Funcint, bool; ModifyF modifyFunc (int x) x - 1; TerminationF runUntilFunc (int x) { return x 1; };第二步创建 builder指定使用进程内运行时、把函数注册为单例服务、注册两个智能体类然后构建并启动AgentsAppBuilder appBuilder new AgentsAppBuilder(); appBuilder.UseInProcessRuntime(); appBuilder.Services.TryAddSingleton(modifyFunc); appBuilder.Services.TryAddSingleton(runUntilFunc); appBuilder.AddAgentChecker(Checker); appBuilder.AddAgentModifier(Modifier); var app await appBuilder.BuildAsync(); await app.StartAsync();UseInProcessRuntime()对应 InProcessRuntime.cs 实现的本地运行时换成 gRPC 运行时后智能体即可分布在多个进程/语言中而上述 API 保持不变由 AgentsAppBuilderExtensions.cs 提供的扩展方法接入。第三步用初始消息CountMessage { Content 10 }启动流程发布到智能体所订阅的default主题然后等待应用关闭await app.PublishMessageAsync(new CountMessage { Content 10 }, new TopicId(default)); // Run until application shutdown await app.WaitForShutdownAsync();运行后控制台会看到从 10 到 1 的倒数输出。教程还给出了三个练手方向改变初始计数把修改函数改成递增记得同步修改 Checker 的终止条件新增一个只负责输出到控制台的智能体提示定义新的消息类型并订阅default主题。五、分布式与扩展路径文档门户给出的分布式包组合Microsoft.AutoGen.RuntimeGateway.GrpcMicrosoft.AutoGen.AgentHost在源码中的落点是客户端侧GrpcAgentRuntime.cs 与GrpcMessageRouter.cs实现远程消息路由配合ProtobufMessageSerializer.cs、ProtobufSerializationRegistry.cs完成消息的 Protobuf 序列化/反序列化——这也是跨语言互操作的技术基础消息按 Protobuf 编码在 Python 与 .NET 智能体之间流转服务端侧RuntimeGateway.Grpc/Services/Grpc/下的GrpcGatewayService.cs、GrpcWorkerConnection.cs提供 gRPC 网关与 worker 连接管理Services/Orleans/下的RegistryGrain.cs、MessageRegistryGrain.cs、MessageRegistryQueue.cs维护注册表与消息队列的分布式状态宿主侧AgentHost 工程含Dockerfile与Program.cs提供了可直接部署的 gRPC 服务宿主。仓库中还有配套的跨语言测试与示例可作参考test/Microsoft.AutoGen.Core.Grpc.Tests/含messages.proto以及dotnet/samples/GettingStartedGrpc/含message.proto的 gRPC 版倒计时示例test/Microsoft.AutoGen.Integration.Tests/下则包含 Aspire AppHost 场景的集成测试如 HelloAppHostIntegrationTests.cs。在生态集成方面Extensions/目录提供了三个方向的官方扩展AspireExtensions/Aspire/AspireHostingExtensions.cs与 .NET Aspire 应用模型集成仓库的dotnet/samples/Hello/与dotnet/samples/dev-team/两个 Aspire 示例工程展示了完整的 AppHost 编排形态MEAIExtensions/MEAI/MEAIHostingExtensions.cs对接 Microsoft.Extensions.AI 的聊天补全服务SemanticKernelExtensions/SemanticKernel/SemanticKernelHostingExtensions.cs与 Semantic Kernel 集成。六、小结与适用前提包选择单进程内的事件驱动智能体工作流只需Microsoft.AutoGen.ContractsMicrosoft.AutoGen.Core跨进程/跨语言Python ↔ .NET集群再引入Microsoft.AutoGen.RuntimeGateway.GrpcMicrosoft.AutoGen.AgentHost客户端可替换为 API 相同的Microsoft.AutoGen.Core.Grpc。编程模型定义强类型消息类 → 继承BaseAgent并实现IHandleT→ 用[TypeSubscription(topic)]绑定主题 → 通过AgentsAppBuilderUseInProcessRuntime()或 gRPC 运行时注册并启动 → 向主题发布初始消息驱动流程。适用前提文档中安装命令示例的版本为0.4.0-dev.1开发预览版本生产环境应核对 NuGet 上对应的稳定版本AgentChat在文档门户中标注为Coming soon即将推出其功能细节以 Installation 文档 与Microsoft.AutoGen.AgentChat.csproj的实际能力为准。想继续深入建议按以下顺序阅读仓库文件Tutorial完整教学、Installation包清单、dotnet/samples/GettingStarted/Program.cs最小可运行示例、dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs智能体基类与消息分派原理、dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs智能体身份规范。【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogen创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考