资讯动态

AutoGen .NET 双世代包体系与快速上手:从 ConversableAgent 对话到事件驱动新 API

发布时间:2026/9/6 18:07:00 来源:尧图企业网站定制
AutoGen .NET 双世代包体系与快速上手从 ConversableAgent 对话到事件驱动新 API【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogen本文基于 AutoGen 仓库的 dotnet/README.md 展开系统讲解 .NET 版本 AutoGen 的两套包体系AutoGen.*旧包与Microsoft.AutoGen.*新包、NuGet 安装与 Nightly 源配置、ConversableAgent 最小对话示例以及事件驱动 Hello 样本的完整运行机制。读完本文你将能够在 .NET 8 环境中安装并运行 AutoGen理解旧版对话式 API 与新版事件驱动 API 的差异并掌握 .NET 独有的源码生成器与代码执行能力。两代 .NET 包体系AutoGen.* 与 Microsoft.AutoGen.*dotnet/README.md 开篇即说明仓库中的 .NET 包分为两套包前缀定位状态AutoGen.*派生自 AutoGen 0.2 for .NET 的旧包ConversableAgent 对话模型将逐步废弃并逐步移植进新包Microsoft.AutoGen.*基于事件驱动模型event-driven model的新包API 尚不稳定可能随时变化这个“双轨并行”的现状意味着如果你要快速跑通一个 LLM 对话原型仍应使用AutoGen.*系列如果你要构建可长期演进、可分布式部署的 Agent 应用则应以Microsoft.AutoGen.*的 Hello 样本为起点并关注其 API 变更。安装 AutoGen .NET 包官方安装指引位于 dotnet/website/articles/Installation.md其中列出了完整的包清单可按需选择一个或多个安装AutoGen一键全家桶依赖AutoGen.Core、AutoGen.OpenAI、AutoGen.LMStudio、AutoGen.SemanticKernel和AutoGen.SourceGeneratorAutoGen.Core核心包提供消息类型、Agent 与群聊的抽象不引入Azure.AI.OpenAI或 Semantic Kernel 等外部依赖适合只想使用 AutoGen 抽象群聊、内置消息类型、workflow、middleware并自行实现 Agent 的场景AutoGen.OpenAI/AutoGen.Mistral/AutoGen.Ollama/AutoGen.Anthropic/AutoGen.LMStudio/AutoGen.Gemini/AutoGen.AzureAIInference各自提供对应 LLM 后端的集成 AgentAutoGen.SemanticKernel基于 Semantic Kernel 的集成 AgentAutoGen.SourceGenerator源码生成器支持类型安全的函数定义生成AutoGen.DotnetInteractive基于 dotnet interactive 的代码执行支持当前支持 C#、F#、PowerShell 与 Python。官方给出的选型建议是只想装一个包享受核心功能就选AutoGen只要抽象、不要额外依赖就选AutoGen.Core只想要类型安全的函数调用源码生成能力、连 AutoGen 抽象都不要就只装AutoGen.SourceGenerator。安装命令dotnet add package AutoGen使用 Nightly 构建dotnet/README.md 指出 Nightly 构建托管在 Azure DevOps 的AutoGen-Nightlyfeed 上。要消费 Nightly 包需要把 feed 加入NuGet.config或全局 NuGet 配置。在项目根目录创建本地NuGet.config?xml version1.0 encodingutf-8? configuration packageSources clear / add keyAutoGen value$(FEED_URL) / !-- replace $(FEED_URL) with the feed url -- !-- other feeds -- /packageSources disabledPackageSources / /configuration或全局添加源注意dotnet-tools源提供Microsoft.DotNet.Interactive.VisualStudio包是AutoGen.DotnetInteractive运行所依赖的dotnet nuget add source FEED_URL --name AutoGen dotnet nuget add source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json --name dotnet-tools添加源后即可指定版本号安装 Nightly 包dotnet add package AutoGen VERSION快速上手用 ConversableAgent 与助手聊天以下是 dotnet/README.md 给出的最小可运行片段使用AutoGen.*旧包using AutoGen; using AutoGen.OpenAI; var openAIKey Environment.GetEnvironmentVariable(OPENAI_API_KEY) ?? throw new Exception(Please set OPENAI_API_KEY environment variable.); var gpt35Config new OpenAIConfig(openAIKey, gpt-3.5-turbo); var assistantAgent new AssistantAgent( name: assistant, systemMessage: You are an assistant that help user to do some tasks., llmConfig: new ConversableAgentConfig { Temperature 0, ConfigList [gpt35Config], }) .RegisterPrintMessage(); // register a hook to print message nicely to console // set human input mode to ALWAYS so that user always provide input var userProxyAgent new UserProxyAgent( name: user, humanInputMode: HumanInputMode.ALWAYS) .RegisterPrintMessage(); // start the conversation await userProxyAgent.InitiateChatAsync( receiver: assistantAgent, message: Hey assistant, please do me a favor., maxRound: 10);这段代码的关键点可以结合源码进一步确认两个内置 Agent 的构造参数完全一致。查看 AssistantAgent 与 UserProxyAgent 的源码二者均继承自ConversableAgent构造参数为name、systemMessage、llmConfig、isTermination终止判定回调、humanInputMode、functionMap工具映射与defaultReply。二者的唯一区别是humanInputMode的默认值AssistantAgent默认HumanInputMode.NEVER从不向人类要输入UserProxyAgent默认HumanInputMode.ALWAYS始终向人类要输入。示例中显式传入ALWAYS即让对话循环在每一轮都等待终端用户输入。llmConfig中的ConfigList支持多模型回退OpenAIConfig(openAIKey, gpt-3.5-turbo)描述了模型与凭据Temperature 0表示关闭随机性以获得确定性输出。.RegisterPrintMessage()注册一个 middleware 钩子将消息格式化打印到控制台属于 AutoGen.Core 的 middleware 机制方便调试对话内容。InitiateChatAsync(receiver, message, maxRound)由 UserProxy 发起与助手的对话maxRound: 10限制最大对话轮数防止循环不终止。更完整的对话示例可参考仓库内 AutoGen.Basic.Sample 样本项目其中包含两 Agent 数学对话、函数调用、动态群聊、Dalle GPT4V 图像生成、UserProxy、LM Studio、ReAct Agent 等十多个示例如 Example01_AssistantAgent.cs、Example03_Agent_FunctionCall.cs、Example04_Dynamic_GroupChat_Coding_Task.cs。新包入门事件驱动的 Hello 样本README 指出要开始使用Microsoft.AutoGen.*新包请查看 samples 目录尤其是 Hello 样本。该样本是一个 .NET Aspire 多项目工程包含以下子项目Hello.AppHostAspire App Host负责编排启动 .NET 后端、.NET Agent 与 Python Agent跨语言 xlang 演示并可打开 Aspire Dashboard 查看遥测与日志HelloAgent最小事件驱动 Agent仅监听事件并回复HelloAIAgents在 HelloAgent 基础上注入IChatClient用 LLM 生成打油诗式问候演示如何扩展 AgentHelloAgentState演示带状态的 Agentprotos/agent_events.proto自定义消息的 protobuf 定义。运行前提为 .NET 8.0 及以上命令为cd dotnet/samples/Hello dotnet runHelloAgent 的事件处理机制HelloAgent.cs 展示了新包的核心编程模型——订阅 Topic、处理消息、发布新消息[TypeSubscription(HelloTopic)] public class HelloAgent( IHostApplicationLifetime hostApplicationLifetime, AgentId id, IAgentRuntime runtime, LoggerBaseAgent? logger null) : BaseAgent(id, runtime, Hello Agent, logger), IHandleNewMessageReceived, IHandleConversationClosed, IHandleShutdown { // 接收 Program.cs 中发布的新消息 public async ValueTask HandleAsync(NewMessageReceived item, MessageContext messageContext) { Console.Out.WriteLine(item.Message); ConversationClosed goodbye new ConversationClosed { UserId this.Id.Type, UserMessage Goodbye }; // 发布 ConversationClosed触发自身的对应 handler await this.PublishMessageAsync(goodbye, new TopicId(HelloTopic)); } public async ValueTask HandleAsync(ConversationClosed item, MessageContext messageContext) { Console.Out.WriteLine(${item.UserId} said {item.UserMessage}); if (Environment.GetEnvironmentVariable(STAY_ALIVE_ON_GOODBYE) ! true) { await this.PublishMessageAsync(new Shutdown(), new TopicId(HelloTopic)); } } public async ValueTask HandleAsync(Shutdown item, MessageContext messageContext) { Console.WriteLine(Shutting down...); hostApplicationLifetime.StopApplication(); // 关闭应用 } }从源码结构看这里体现了新 API 的几个关键概念[TypeSubscription(HelloTopic)]特性声明 Agent 订阅的主题IHandleT接口把 protobuf 消息类型映射到HandleAsync处理方法消息类型NewMessageReceived、ConversationClosed、Shutdown由 gRPC protobuf 规范生成 C# 类仓库根目录的 protos/ 目录存放了agent_worker.proto与cloudevent.proto等基础定义开发者也可以在项目中新增.proto文件定义自定义消息PublishMessageAsync(message, new TopicId(HelloTopic))把新消息发回事件总线形成“收消息 → 处理 → 发新消息 → 触发下一个 handler”的链式编排。App Builder 与进程内 / 分布式两种运行时HelloAgent/Program.cs 演示了AgentsAppBuilder的两种启动方式var appBuilder new AgentsAppBuilder(); bool usingGrpc false; if (hostAddress is string agentHost) // 设置了 --host 或 AGENT_HOST 环境变量 { usingGrpc true; appBuilder.AddGrpcAgentWorker(agentHost).AddAgentHelloAgent(HelloAgent); } else { // 进程内运行时允许消息投递给自身并注册 Hello Agent appBuilder.UseInProcessRuntime(deliverToSelf: true).AddAgentHelloAgent(HelloAgent); } var app await appBuilder.BuildAsync(); await app.StartAsync(); var message new NewMessageReceived { Message Hello World! }; await app.PublishMessageAsync(message, new TopicId(HelloTopic)); await app.WaitForShutdownAsync();命令行参数说明来自同文件内PrintHelp()--host hostAddress通过 gRPC 网关连接分布式运行时也可用环境变量AGENT_HOST指定--nosend不发送启动消息等待其他 Agent 先发消息注意在 InProcessRuntime 下无效环境变量STAY_ALIVE_ON_GOODBYEtrue时Agent 收到 Goodbye 后不自我关闭便于 Aspire 多 Agent 场景中保持存活。HelloAppHost 的 Program.cs 则演示了 .NET Aspire 的编排启动 AgentHost 后端WithExternalHttpEndpoints()为 .NET Agent 与 Python Agent 分别注入AGENT_HOST端点实现同一事件总线上 C# 与 Python Agent 互通的 xlang 场景。更多新包概念可继续阅读 HelloAgent 的 README其中包含事件流程图、事件处理器写法、继承与组合、自定义 protobuf 消息含.csproj中引入Grpc.Tools的配置片段等细节。功能支持矩阵与 .NET 独有能力dotnet/README.md 的 Functionality 一节明确了当前 .NET 版的功能边界能力状态说明ConversableAgent 函数调用已支持通过functionMap或[Function]特性绑定工具代码执行已支持仅 .NET 版由 dotnet-interactive 驱动见 AutoGen.DotnetInteractive 包双 Agent 对话已支持参见 TwoAgentTest 等测试群聊Group chat已支持实现位于 AutoGen.Core/GroupChat增强型 LLM 推理计划中README 中仍为未完成项类型安全函数定义源码生成已支持.NET 独有AutoGen.SourceGenerator包值得强调的是 .NET 独有的源码生成器AutoGen.SourceGenerator 让你在方法上标注[Function]特性编译期即自动生成FunctionDefinition与 JSON 参数反序列化包装器免去手写函数 schema 并保证签名同步。使用步骤在.csproj中设置GenerateDocumentationFile为true启用 XML 文档特性参数的描述会取自 XML doc 注释并引用AutoGen.SourceGenerator包在public partial class中为方法标注[Function]方法需为public参数与返回值尽量使用基础类型以获得最佳性能using AutoGen; public partial class MyFunctions { /// summary /// Add two numbers. /// /summary /// param nameaThe first number./param /// param namebThe second number./param [Function] public Taskstring AddAsync(int a, int b) { return Task.FromResult(${a} {b} {a b}); } }生成结果包含三部分一个与参数对应的私有 schema 类AddAsyncSchema、一个AddAsyncWrapper把 LLM 返回的 JSON 字符串反序列化为强类型参数并调用原方法、一个AddAsyncFunction属性把方法名、XML 文档与参数类型映射为FunctionDefinition供 Agent 注册为工具。生成的 JSON schema 使用 CamelCase 命名策略int参数映射为number类型。更多示例见 AutoGen.SourceGenerator.Tests。样本索引与延伸路径除了本文重点剖析的 Hello 样本dotnet/samples/ 目录还提供了分层递进的实践路径AgentChat/AutoGen.Basic.Sample旧包对话式 API 的完整示例集数学对话、函数调用、群聊、Dalle/GPT4V、UserProxy、LM Studio、Semantic Kernel、JSON 模式等AgentChat/AutoGen.OpenAI.Sample连接 Azure OpenAI、Ollama、o1-preview、结构化输出、JSON 模式AgentChat/AutoGen.Gemini.Sample 与 AutoGen.Ollama.SampleGoogle Gemini / Vertex 与 OllamaLLaMA、LLaVA集成AgentChat/AutoGen.SemanticKernel.SampleSemantic Kernel 集成与内核函数跨 Agent 复用GettingStarted 与 GettingStartedGrpc新包最小示例及其 gRPC 分布式版本含message.proto自定义消息定义dev-team基于新包构建的多 Agent 开发团队协作系统含完整的服务端Agents/Options/Services、protobuf 契约Protos/messages.proto、states.proto与 Aspire 编排是理解事件驱动模型如何落地为真实应用的最佳范本。小结AutoGen 的 .NET 生态正处于从“ConversableAgent 对话模型”AutoGen.*向“事件驱动消息模型”Microsoft.AutoGen.*迁移的阶段。旧包提供了即装即用的助手对话、函数调用、群聊与基于 dotnet-interactive 的代码执行配合AutoGen.SourceGenerator的类型安全函数定义能快速搭建 LLM 应用原型新包则以 Topic 订阅、protobuf 消息契约、进程内/gRPC 双运行时为核心通过 Hello、GettingStartedGrpc、dev-team 等样本展示了可分布式、可跨语言.NET 与 Python的 Agent 编排能力。由于新包 API 尚未稳定实践中建议以旧包做功能验证、以新包做架构演进跟踪并关注 Nightly feed 获取最新构建。【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogen创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价