.NET 6+Semantic Kernel快速接入OpenAI接口

大家好,我是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 class OpenAiConfiguration
{
    public string ModelId { get; set; }
    public string EndPoint { get; set; }
    public string ApiKey { get; set; }

    public OpenAiConfiguration(string modelId, string endPoint, string apiKey)
    {
        ModelId = modelId;
        EndPoint = endPoint;
        ApiKey = apiKey;
    }
}

第五步:创建一个用于转发OpenAI请求的HttpClientHandler,它会将API请求转发你的大语言模型API地址,当然,你的大语言模型API必须是OpenAI兼容的才行。

复制代码
public class CustomOpenAiHandler : HttpClientHandler
{
    private readonly string _openAiBaseAddress;

    public CustomOpenAiHandler(string openAiBaseAddress)
    {
        _openAiBaseAddress = openAiBaseAddress;
    }

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.RequestUri = new Uri($"{_openAiBaseAddress}{request.RequestUri.PathAndQuery}");
        return await base.SendAsync(request, cancellationToken);
    }
}

第六步:在Program.cs中添加以下核心步骤的代码,加上注释,合计29行,快速实现一个AIGC应用。

复制代码
using Microsoft.Extensions.Configuration;
using Microsoft.SemanticKernel;
using SemanticKernelDemo.Configurations;
using SemanticKernelDemo.Handlers;

// Step1. Load your custom configuration
var configuration = new ConfigurationBuilder().AddJsonFile($"appsettings.json");
var config = configuration.Build();
var openAiConfiguration = new OpenAiConfiguration(config.GetSection("LLM_API_MODEL").Value, config.GetSection("LLM_API_BASE_URL").Value, config.GetSection("LLM_API_KEY").Value);
// Step2. Create a kernel from Your LLM API
var 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 kernel
var 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: ");
    await foreach (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。


作者:周旭龙

出处:https://edisonchou.cnblogs.com

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

相关推荐
春末的南方城市26 分钟前
VidSketch:具有扩散控制的手绘草图驱动视频生成
人工智能·深度学习·计算机视觉·aigc
Francek Chen1 小时前
【大模型科普】AIGC技术发展与应用实践(一文读懂AIGC)
人工智能·深度学习·语言模型·大模型·aigc
kakaZhui2 小时前
【多模态大模型】GLM-4-Voice端到端语音交互机器人VoiceAI
人工智能·chatgpt·机器人·aigc·llama
LittleNyima8 小时前
【代码解读】阿里最新开源视频生成模型 Wan 2.1 实现解析
人工智能·stable diffusion·aigc·音视频
寻道码路10 小时前
深度剖析 Video-RAG:厦门大学和罗切斯特大学联合推出的一种用于长视频理解的检索增强生成技术
人工智能·语言模型·开源·aigc·音视频·ai编程
AIGC安琪13 小时前
AI绘画(Stable Diffusion)喂饭级教程
人工智能·ai作画·stable diffusion·aigc·美女
春末的南方城市14 小时前
CineMaster: 用于电影文本到视频生成的 3D 感知且可控的框架。
人工智能·数码相机·计算机视觉·语言模型·aigc·图像生成
EdisonZhou15 小时前
基于Microsoft.Extensions.VectorData实现语义搜索
llm·aigc·.net core
隔岸观火烧连营15 小时前
JBoltAI_SpringBoot如何基于Deepseek官网API区分 R1大模型深度思考和具体回答的内容?
spring·aigc
村中少年17 小时前
使用DeepSeek/chatgpt等AI工具辅助网络协议流量数据包分析
网络协议·chatgpt·wireshark·json·aigc