SemanticKernel之LLama3案例
之前的篇章都是用SemanticKernel来连接OpenAI的API,当然是需要费用,另外还有使用限制,本篇来说明在SK中使用开源模型LLama3。
首先引入Nuget包,这里使用的是LLamaSharp这个三方包,因为没有显卡,只能跑在CPU上,所以也需要引入对应的Cpu包,最后引入SK的LLama版的包。
<ItemGroup> <PackageReference Include="LLamaSharp" Version="0.11.2" /> <PackageReference Include="LLamaSharp.Backend.Cpu" Version="0.11.2" /> <PackageReference Include="LLamaSharp.semantic-kernel" Version="0.11.2" /> </ItemGroup>
接下就是下载最新的LLama3了,扩展名是gguf,如下代码就可以轻松地跑起本地小模型了。
using LLama.Common; using LLama; using LLamaSharp.SemanticKernel.ChatCompletion; using System.Text; using ChatHistory = LLama.Common.ChatHistory; using AuthorRole = LLama.Common.AuthorRole; await SKRunAsync(); async Task SKRunAsync() { var modelPath = @"C:\llama\llama-2-coder-7b.Q8_0.gguf"; var parameters = new ModelParams(modelPath) { ContextSize = 1024, Seed = 1337, GpuLayerCount = 5, Encoding = Encoding.UTF8, }; using var model = LLamaWeights.LoadFromFile(parameters); var ex = new StatelessExecutor(model, parameters); var chatGPT = new LLamaSharpChatCompletion(ex); var chatHistory = chatGPT.CreateNewChat(@"这是assistant和user之间的对话。 assistant是一名.net和C#专家,能准确回答user提出的专业问题。"); Console.WriteLine("开始聊天:"); Console.WriteLine("------------------------"); while (true) { Console.Write("user:"); var userMessage = Console.ReadLine(); chatHistory.AddUserMessage(userMessage); var first = true; var content = ""; await foreach (var reply in chatGPT.GetStreamingChatMessageContentsAsync(chatHistory)) { if (first) { first = false; Console.Write(reply.Role + ":"); } content += reply.Content; Console.Write(reply.Content); } chatHistory.AddAssistantMessage(content); } }
下面是具体的效果,除了慢点,没有GPT强大点,其他都是很香的,关键是没有key,轻松跑,不怕信用卡超支。
文章来源微信公众号
想要更快更方便的了解相关知识,可以关注微信公众号
****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端