當前位置: 妍妍網 > 碼農

.NET 6+Semantic Kernel快速接入OpenAI

2024-05-28碼農

大家好,我是Edison。

今天我們快速地使用Semantic Kernel來整合OpenAI,使用20來行程式碼快速實作一個簡單的AIGC套用。

這裏,我就不多介紹Semantic Kernel了,包括它的一些主要特性如Planners, Functions, Plugins等,這些都留到以後寫系列文章再來詳細介紹吧。

現階段你只需要了解, Semantic Kernel 與 LangChain 類似,但 Semantic Kernel 是為套用開發 開發人員建立的SDK計畫,它支持.NET, Python 以及 Java,但是對.NET支持最成熟(微軟自家孩子嘛),可以讓你的套用很輕易的整合AI大語言模型

.NET6套用整合OpenAI

這裏,我們快速透過一個.NET 6 控制台應用程式來使用Semantic Kernel整合OpenAI建立一個AIGC套用。

第一步 :建立一個.NET6控制台應用程式;

第二步 :新建一個appsettings.json,填入以下配置:

{"LLM_API_MODEL": "mistral-7b-instruct","LLM_API_BASE_URL": "https://api.your-company.com/llm","LLM_API_KEY": "your-llm-api-key" // Replace this value with your llm api key}

這裏我使用的是我司內部提供的大語言模型API,它是OpenAI相容的。

第三步 :透過NuGet管理器安裝以下元件包:

  • Microsoft.SemanticKernel,1.11.0

  • Microsoft.SemanticKernel.Connectors.OpenAI,1.11.0

  • Microsoft.Extensions.Http,8.0.0

  • Microsoft.Extensions.Configuration, 6.0.0

  • Microsoft.Extensions.Configuration.Json, 6.0.0

  • 第四步 :建立一個OpenAiConfiguration類用於接收appsettings的配置:

    public classOpenAiConfiguration{publicstring ModelId { get; set; }publicstring EndPoint { get; set; }publicstring ApiKey { get; set; }publicOpenAiConfiguration(string modelId, string endPoint, string apiKey) { ModelId = modelId; EndPoint = endPoint; ApiKey = apiKey; }}

    第五步 :建立一個用於轉發OpenAI請求的HttpClientHandler,它會將API請求轉發你的大語言模型API地址,當然,你的大語言模型API必須是OpenAI相容的才行

    public classCustomOpenAiHandler : HttpClientHandler{privatereadonlystring _openAiBaseAddress;publicCustomOpenAiHandler(string openAiBaseAddress) { _openAiBaseAddress = openAiBaseAddress; }protectedoverrideasync Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { request.RequestUri = new Uri($"{_openAiBaseAddress}{request.RequestUri.PathAndQuery}");returnawaitbase.SendAsync(request, cancellationToken); }}

    第六步 在Program.cs中添加以下核心步驟的程式碼,加上註釋,合計29行,快速實作一個AIGC套用。

    using Microsoft.Extensions.Configuration;using Microsoft.SemanticKernel;using SemanticKernelDemo.Configurations;using SemanticKernelDemo.Handlers;// Step1. Load your custom configurationvar configuration = new ConfigurationBuilder().AddJsonFile($"appsettings.json");var config = configuration.Build();var openAiConfiguration = new OpenAiConfiguration(config.Getp("LLM_API_MODEL").Value, config.Getp("LLM_API_BASE_URL").Value, config.Getp("LLM_API_KEY").Value);// Step2. Create a kernel from Your LLM APIvar openAiClient = new HttpClient(new CustomOpenAiHandler(openAiConfiguration.EndPoint));var builder = Kernel.CreateBuilder();builder.AddOpenAIChatCompletion(openAiConfiguration.ModelId, openAiConfiguration.ApiKey, httpClient: openAiClient);var kernel = builder.Build();// Step3. Create a chat between you and kernelvar promptTemplate = @"<message role=""user"">{0}</message>";Console.Write("You: ");var userMessage = string.Empty;while (!string.IsNullOrEmpty(userMessage = Console.ReadLine())){var prompt = string.Format(promptTemplate, userMessage);var summarize = kernel.CreateFunctionFromPrompt(prompt);var response = kernel.InvokeStreamingAsync(summarize); Console.Write("AI: ");awaitforeach (var item in response) Console.Write(item.ToString()); Console.WriteLine(Environment.NewLine + "---------------------------------------------------------------------"); Console.Write("You: ");}

    執行一下,結果如下圖所示:

    小結

    本文介紹了如何在.NET 6環境下使用Semantic Kernel快速接入OpenAI大預言模型API來實作一個AIGC套用,20來行程式碼就可以實作,是不是很方便?

    如果你對Semantic Kernel感興趣,請在留言區留言,後續我也可以考慮整理一個系列文章,逐步深入了解和套用Semantic Kernel。

    年終總結:

    數位化轉型:

    C#刷演算法題:

    C#刷設計模式:

    .NET面試:

    .NET大會: