用本地 OpenAI 兼容服務(wù))
AutoGen .NET 連接 LM Studio使用 AutoGen.LMStudio 包調(diào)用本地 OpenAI 兼容服務(wù)【免費下載鏈接】autogenA programming framework for agentic AI項目地址: https://gitcode.com/GitHub_Trending/au/autogenAutoGen.LMStudio 是 AutoGen .NET 中專門用于消費 LM Studio 本地服務(wù)器所暴露的 OpenAI 兼容openai-likeAPI 的封裝包。本篇基于倉庫中該包的 README、源碼實現(xiàn)與官方示例講解其安裝方式、LMStudioConfig/LMStudioAgent的用法與參數(shù)、內(nèi)部如何通過自定義 HTTP 傳輸層把 OpenAI SDK 請求重定向到本地服務(wù)以及在較新版本中推薦的替代方案OpenAIChatAgent接法幫助你在 .NET 應(yīng)用中把 LLM 對話能力完全落地到本地、離線環(huán)境。包定位與安裝AutoGen.LMStudio的定位非常聚焦讓 AutoGen 的 agent 能夠把模型請求發(fā)往運行在本地的 LM Studio 服務(wù)而不依賴云端 OpenAI 服務(wù)。從項目文件 AutoGen.LMStudio.csproj 可以看到該包引用了AutoGen.Core提供IAgent、IMessage等核心抽象與ILLMConfig接口和AutoGen.OpenAI.V1提供GPTAgent與 OpenAI 客戶端封裝這決定了它的實現(xiàn)思路是復(fù)用 OpenAI 客戶端、只替換目標(biāo)地址。安裝方式摘自 dotnet/src/AutoGen.LMStudio/README.md在.csproj中添加ItemGroup PackageReference IncludeAutoGen.LMStudio VersionAUTOGEN_VERSION / /ItemGroup其中AUTOGEN_VERSION需替換為你實際采用的 AutoGen 版本號倉庫中所有 README 均使用占位符寫法發(fā)布時由打包流程填充?;居梅↙MStudioConfig 與 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?);要真正跑通前提是你已在本機(jī)啟動 LM Studio 并開啟其本地開發(fā)服務(wù)器LM Studio 的默認(rèn)端口為 1234示例代碼中使用了 5000只要與實際服務(wù)端口一致即可并且已在 LM Studio 中加載了一個模型。LMStudioConfighost port 生成服務(wù) URILMStudioConfig.cs 的實現(xiàn)非常精簡提供了兩個構(gòu)造重載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 等的統(tǒng)一契約構(gòu)造時固定拼接http://{host}:{port}即默認(rèn)走 HTTP 明文連接——這與本地服務(wù)器的使用場景相符也支持直接傳入完整Uri便于復(fù)用既有配置。LMStudioAgent內(nèi)部是一個 GPTAgentLMStudioAgent.cs 的構(gòu)造函數(shù)暴露了完整參數(shù)面比 README 示例多出 temperature、maxTokens、function calling 相關(guān)參數(shù)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默認(rèn)You are a helpful AI assistanttemperature默認(rèn)0.7fmaxTokens默認(rèn)1024functions/functionMap可選的函數(shù)定義與處理函數(shù)映射表示該 agent 在協(xié)議層支持 OpenAI 風(fēng)格的 function calling——能否實際生效取決于 LM Studio 所選模型是否支持工具調(diào)用。從源碼結(jié)構(gòu)看LMStudioAgent本質(zhì)上是一個組合包裝內(nèi)部持有GPTAgent innerAgentGenerateReplyAsync、Name等IAgent成員全部直接委托給內(nèi)部 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的取值本地服務(wù)對模型標(biāo)識不敏感任意占位字符串均可。源碼解析請求是如何被重定向到本地服務(wù)的LMStudioAgent的核心在于ConfigOpenAIClientForLMStudio與私有類CustomHttpClientHandler。其做法不是修改 OpenAI SDK 的默認(rèn) 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因為本地服務(wù)器不需要鑒權(quán)ServiceVersion.V2022_12_01指定了 OpenAI 客戶端的服務(wù)版本真正起作用的是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); }即在每次發(fā)送請求前把 OpenAI SDK 生成的RequestUri的 Host 部分替換為 LM Studio 的地址http://{host}:{port}保留原有的路徑與查詢串如/chat/completions再交由基類發(fā)出。這是把一個標(biāo)準(zhǔn) OpenAI SDK 客戶端無縫指向任意 OpenAI 兼容本地服務(wù)的經(jīng)典手法后續(xù)版本中的 Ollama 等第三方接入示例沿用了同樣的模式。版本提示Obsolete 標(biāo)記與推薦的 OpenAIChatAgent 寫法需要注意的是LMStudioAgent.cs 類上帶有如下特性[Obsolete(Use OpenAIChatAgent to connect to LM Studio)] public class LMStudioAgent : IAgent也就是說倉庫當(dāng)前版本已將LMStudioAgent標(biāo)記為過時推薦使用AutoGen.OpenAI包中的OpenAIChatAgent直接連接 LM Studio。官方示例 Example08_LMStudio.cs 展示的正是這一新寫法示例默認(rèn)端口為 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 重寫必須調(diào)用RegisterMessageConnector()OpenAIChatAgent使用 OpenAI V1 的新消息模型需要消息連接器把 AutoGen 核心消息類型TextMessage、FunctionCallMessage等轉(zhuǎn)換為 OpenAI 協(xié)議消息。同一示例中模型名does-not-matter與舊實現(xiàn)的modelName: llm語義一致——本地服務(wù)對模型標(biāo)識不敏感。倉庫中類似的第三方 OpenAI 兼容服務(wù)接入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 本地服務(wù)器的 openai-like API。使用前提歸納本機(jī)已安裝并啟動 LM Studio且其本地開發(fā)服務(wù)器默認(rèn)http://localhost:1234已加載模型若使用舊版AutoGen.LMStudio包其內(nèi)部依賴AutoGen.OpenAI.V1的GPTAgent會因Obsolete特性在編譯期產(chǎn)生過時警告建議遷移到OpenAIChatAgent方案函數(shù)調(diào)用、結(jié)構(gòu)化輸出等高級能力能否生效取決于 LM Studio 中實際加載的模型是否支持相應(yīng) OpenAI 特性倉庫文檔對這類平臺差異也提示以對應(yīng)平臺文檔為準(zhǔn)。相關(guān)源碼與文檔索引類型路徑包 README本文檔依據(jù)dotnet/src/AutoGen.LMStudio/README.mdAgent 實現(xiàn)含 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創(chuàng)作聲明:本文部分內(nèi)容由AI輔助生成(AIGC),僅供參考