AutoGen .NET 连接 LM Studio:使用 AutoGen.LMStudio 包调用本地 OpenAI 兼容服务

AutoGen .NET 连接 LM Studio:使用 AutoGen.LMStudio 包调用本地 OpenAI 兼容服务 AutoGen .NET 连接 LM Studio使用 AutoGen.LMStudio 包调用本地 OpenAI 兼容服务【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogenAutoGen.LMStudio 是 AutoGen .NET 中专门用于消费 LM Studio 本地服务器所暴露的 OpenAI 兼容openai-likeAPI 的封装包。本篇基于仓库中该包的 README、源码实现与官方示例讲解其安装方式、LMStudioConfig/LMStudioAgent的用法与参数、内部如何通过自定义 HTTP 传输层把 OpenAI SDK 请求重定向到本地服务以及在较新版本中推荐的替代方案OpenAIChatAgent接法帮助你在 .NET 应用中把 LLM 对话能力完全落地到本地、离线环境。包定位与安装AutoGen.LMStudio的定位非常聚焦让 AutoGen 的 agent 能够把模型请求发往运行在本地的 LM Studio 服务而不依赖云端 OpenAI 服务。从项目文件 AutoGen.LMStudio.csproj 可以看到该包引用了AutoGen.Core提供IAgent、IMessage等核心抽象与ILLMConfig接口和AutoGen.OpenAI.V1提供GPTAgent与 OpenAI 客户端封装这决定了它的实现思路是复用 OpenAI 客户端、只替换目标地址。安装方式摘自 dotnet/src/AutoGen.LMStudio/README.md在.csproj中添加ItemGroup PackageReference IncludeAutoGen.LMStudio VersionAUTOGEN_VERSION / /ItemGroup其中AUTOGEN_VERSION需替换为你实际采用的 AutoGen 版本号仓库中所有 README 均使用占位符写法发布时由打包流程填充。基本用法LMStudioConfig 与 LMStudioAgentREADME 给出的最小可用示例如下using AutoGen.LMStudio; var localServerEndpoint localhost; var port 5000; var lmStudioConfig new LMStudioConfig(localServerEndpoint, port); var agent new LMStudioAgent( name: agent, systemMessage: You are an agent that help user to do some tasks., lmStudioConfig: lmStudioConfig) .RegisterPrintMessage(); // register a hook to print message nicely to console await agent.SendAsync(Can you write a piece of C# code to calculate 100th of fibonacci?);要真正跑通前提是你已在本机启动 LM Studio 并开启其本地开发服务器LM Studio 的默认端口为 1234示例代码中使用了 5000只要与实际服务端口一致即可并且已在 LM Studio 中加载了一个模型。LMStudioConfighost port 生成服务 URILMStudioConfig.cs 的实现非常精简提供了两个构造重载public class LMStudioConfig : ILLMConfig { public LMStudioConfig(string host, int port) { this.Host host; this.Port port; this.Uri new Uri($http://{host}:{port}); } public LMStudioConfig(Uri uri) { this.Uri uri; this.Host uri.Host; this.Port uri.Port; } public string Host { get; } public int Port { get; } public Uri Uri { get; } }要点LMStudioConfig : ILLMConfig该接口定义于 dotnet/src/AutoGen.Core/ILLMConfig.cs是 AutoGen .NET 各 LLM 配置OpenAI、Azure OpenAI、LM Studio 等的统一契约构造时固定拼接http://{host}:{port}即默认走 HTTP 明文连接——这与本地服务器的使用场景相符也支持直接传入完整Uri便于复用既有配置。LMStudioAgent内部是一个 GPTAgentLMStudioAgent.cs 的构造函数暴露了完整参数面比 README 示例多出 temperature、maxTokens、function calling 相关参数public LMStudioAgent( string name, LMStudioConfig config, string systemMessage You are a helpful AI assistant, float temperature 0.7f, int maxTokens 1024, IEnumerableFunctionDefinition? functions null, IDictionarystring, Funcstring, Taskstring? functionMap null)nameagent 名称在群聊等场景下用于消息路由systemMessage默认You are a helpful AI assistanttemperature默认0.7fmaxTokens默认1024functions/functionMap可选的函数定义与处理函数映射表示该 agent 在协议层支持 OpenAI 风格的 function calling——能否实际生效取决于 LM Studio 所选模型是否支持工具调用。从源码结构看LMStudioAgent本质上是一个组合包装内部持有GPTAgent innerAgentGenerateReplyAsync、Name等IAgent成员全部直接委托给内部 agentvar client ConfigOpenAIClientForLMStudio(config); innerAgent new GPTAgent( name: name, systemMessage: systemMessage, openAIClient: client, modelName: llm, // model name doesnt matter for LM Studio temperature: temperature, maxTokens: maxTokens, functions: functions, functionMap: functionMap);注释说明了modelName: llm的取值本地服务对模型标识不敏感任意占位字符串均可。源码解析请求是如何被重定向到本地服务的LMStudioAgent的核心在于ConfigOpenAIClientForLMStudio与私有类CustomHttpClientHandler。其做法不是修改 OpenAI SDK 的默认 Endpoint 语义而是给OpenAIClient注入一个自定义HttpClientTransportprivate OpenAIClient ConfigOpenAIClientForLMStudio(LMStudioConfig config) { // create uri from host and port var uri config.Uri; var handler new CustomHttpClientHandler(uri); var httpClient new HttpClient(handler); var option new OpenAIClientOptions(OpenAIClientOptions.ServiceVersion.V2022_12_01) { Transport new HttpClientTransport(httpClient), }; return new OpenAIClient(api-key, option); }OpenAIClient使用占位 API Keyapi-key因为本地服务器不需要鉴权ServiceVersion.V2022_12_01指定了 OpenAI 客户端的服务版本真正起作用的是CustomHttpClientHandlerprotected override TaskHttpResponseMessage SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var uriBuilder new UriBuilder(_modelServiceUrl); uriBuilder.Path request.RequestUri?.PathAndQuery ?? throw new InvalidOperationException(RequestUri is null); request.RequestUri uriBuilder.Uri; return base.SendAsync(request, cancellationToken); }即在每次发送请求前把 OpenAI SDK 生成的RequestUri的 Host 部分替换为 LM Studio 的地址http://{host}:{port}保留原有的路径与查询串如/chat/completions再交由基类发出。这是把一个标准 OpenAI SDK 客户端无缝指向任意 OpenAI 兼容本地服务的经典手法后续版本中的 Ollama 等第三方接入示例沿用了同样的模式。版本提示Obsolete 标记与推荐的 OpenAIChatAgent 写法需要注意的是LMStudioAgent.cs 类上带有如下特性[Obsolete(Use OpenAIChatAgent to connect to LM Studio)] public class LMStudioAgent : IAgent也就是说仓库当前版本已将LMStudioAgent标记为过时推荐使用AutoGen.OpenAI包中的OpenAIChatAgent直接连接 LM Studio。官方示例 Example08_LMStudio.cs 展示的正是这一新写法示例默认端口为 LM Studio 惯用的 1234using System.ClientModel; using AutoGen.Core; using AutoGen.OpenAI; using AutoGen.OpenAI.Extension; using OpenAI; var endpoint http://localhost:1234; var openaiClient new OpenAIClient(new ApiKeyCredential(api-key), new OpenAIClientOptions { Endpoint new Uri(endpoint), }); var lmAgent new OpenAIChatAgent( chatClient: openaiClient.GetChatClient(does-not-matter), name: assistant) .RegisterMessageConnector() .RegisterPrintMessage(); await lmAgent.SendAsync(Can you write a piece of C# code to calculate 100th of fibonacci?);与旧版LMStudioAgent相比新写法有两点差异值得注意Endpoint 由OpenAIClientOptions.Endpoint直接指定无需再手写CustomHttpClientHandler做 URI 重写必须调用RegisterMessageConnector()OpenAIChatAgent使用 OpenAI V1 的新消息模型需要消息连接器把 AutoGen 核心消息类型TextMessage、FunctionCallMessage等转换为 OpenAI 协议消息。同一示例中模型名does-not-matter与旧实现的modelName: llm语义一致——本地服务对模型标识不敏感。仓库中类似的第三方 OpenAI 兼容服务接入Ollama 等可参考 Connect_To_Ollama.cs 与文档 OpenAIChatAgent-connect-to-third-party-api.md其核心思路占位 API Key 指定本地 Endpoint与 LM Studio 完全一致。更新历史与适用前提按 dotnet/src/AutoGen.LMStudio/README.md 的 Update history0.0.72024-02-11版本引入了LMStudioAgent以支持消费 LM Studio 本地服务器的 openai-like API。使用前提归纳本机已安装并启动 LM Studio且其本地开发服务器默认http://localhost:1234已加载模型若使用旧版AutoGen.LMStudio包其内部依赖AutoGen.OpenAI.V1的GPTAgent会因Obsolete特性在编译期产生过时警告建议迁移到OpenAIChatAgent方案函数调用、结构化输出等高级能力能否生效取决于 LM Studio 中实际加载的模型是否支持相应 OpenAI 特性仓库文档对这类平台差异也提示以对应平台文档为准。相关源码与文档索引类型路径包 README本文档依据dotnet/src/AutoGen.LMStudio/README.mdAgent 实现含 URI 重写逻辑dotnet/src/AutoGen.LMStudio/LMStudioAgent.cs配置类host/port → URIdotnet/src/AutoGen.LMStudio/LMStudioConfig.cs包工程文件依赖 AutoGen.Core / AutoGen.OpenAI.V1dotnet/src/AutoGen.LMStudio/AutoGen.LMStudio.csproj官方 LM Studio 示例OpenAIChatAgent 新写法dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example08_LMStudio.csILLMConfig 接口定义dotnet/src/AutoGen.Core/ILLMConfig.cs第三方 OpenAI API 接入文档dotnet/website/articles/OpenAIChatAgent-connect-to-third-party-api.md【免费下载链接】autogenA programming framework for agentic AI项目地址: https://gitcode.com/GitHub_Trending/au/autogen创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考