如何通过SK集成chatGPT实现DotNet项目工程化?

智能助手服务

以下案例将讲解如何实现天气插件

当前文档对应src/assistant/Chat.SemanticServer项目

首先我们介绍一下Chat.SemanticServer的技术架构

SemanticKernel 是什么?

Semantic Kernel是一个SDK,它将OpenAI、Azure OpenAI和Hugging Face等大型语言模型(LLMs)与传统的编程语言如C#、Python和Java集成在一起。Semantic Kernel通过允许您定义可以在几行代码中链接在一起的插件来实现这一目标。

如何集成使用SemanticKernel

以下是添加IKernel,OpenAIOptions.ModelOpenAIOptions.Key在一开始使用了builder.Configuration.GetSection("OpenAI").Get<OpenAIOptions>();绑定。对应配置文件,OpenAIChatCompletion则是用于直接请求OpenAI。

"OpenAI": {"Key": "","Endpoint": "","Model": "gpt-3.5-turbo"}
builder.Services.AddTransient<IKernel>((services) =>
{var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();return Kernel.Builder.WithOpenAIChatCompletionService(OpenAIOptions.Model,OpenAIOptions.Key,httpClient: httpClientFactory.CreateClient("ChatGPT")).Build();
}).AddSingleton<OpenAIChatCompletion>((services) =>
{var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();return new OpenAIChatCompletion(OpenAIOptions.Model, OpenAIOptions.Key,httpClient: httpClientFactory.CreateClient("ChatGPT"));
});

在项目中存在plugins文件夹,这是提供的插件目录,在BasePlugin目录下存在一个识别意图的插件。

config.json对应当前插件的一些参数配置,

{"schema": 1,"type": "completion","description": "获取用户的意图。","completion": {"max_tokens": 500,"temperature": 0.0,"top_p": 0.0,"presence_penalty": 0.0,"frequency_penalty": 0.0},"input": {"parameters": [{"name": "input","description": "用户的请求。","defaultValue": ""},{"name": "history","description": "对话的历史。","defaultValue": ""},{"name": "options","description": "可供选择的选项。","defaultValue": ""}]}
}

skprompt.txt则是当前插件使用的prompt

加载插件

在这里我们注入了IKernel

    private readonly IKernel _kernel;private readonly IHttpClientFactory _httpClientFactory;private readonly RedisClient _redisClient;private readonly ILogger<IntelligentAssistantHandle> _logger;private readonly OpenAIChatCompletion _chatCompletion;public IntelligentAssistantHandle(IKernel kernel, RedisClient redisClient,ILogger<IntelligentAssistantHandle> logger, IHttpClientFactory httpClientFactory,OpenAIChatCompletion chatCompletion){_kernel = kernel;_redisClient = redisClient;_logger = logger;_httpClientFactory = httpClientFactory;_chatCompletion = chatCompletion;_redisClient.Subscribe(nameof(IntelligentAssistantEto),((s, o) => { HandleAsync(JsonSerializer.Deserialize<IntelligentAssistantEto>(o as string)); }));}

然后准备加载插件。


//对话摘要  SK.Skills.Core 核心技能
_kernel.ImportSkill(new ConversationSummarySkill(_kernel), "ConversationSummarySkill");// 插件根目录
var pluginsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "plugins");// 这个是添加BasePlugin目录下面的所有插件,会自动扫描
var intentPlugin = _kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "BasePlugin");// 这个是添加Travel目录下面的所有插件,会自动扫描
var travelPlugin = _kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "Travel");// 这个是添加ChatPlugin目录下面的所有插件,会自动扫描
var chatPlugin = _kernel.ImportSemanticSkillFromDirectory(pluginsDirectory, "ChatPlugin");// 这个是添加WeatherPlugin类插件,并且给定插件命名WeatherPlugin
var getWeather = _kernel.ImportSkill(new WeatherPlugin(_httpClientFactory), "WeatherPlugin");

使用插件,首先我们创建了一个ContextVariablesinput则是GetIntent插件中的的{{$input}}options则对应{{$options}}getIntentVariables则将替换对应的prompt中响应的参数。

var getIntentVariables = new ContextVariables{["input"] = value,["options"] = "Weather,Attractions,Delicacy,Traffic" //给GPT的意图,通过Prompt限定选用这些里面的};
string intent = (await _kernel.RunAsync(getIntentVariables, intentPlugin["GetIntent"])).Result.Trim();

plugins/BasePlugin/GetIntent/skprompt.txt内容

{{ConversationSummarySkill.SummarizeConversation $history}}
用户: {{$input}}---------------------------------------------
提供用户的意图。其意图应为以下内容之一: {{$options}}意图: 

意图识别完成以后,当执行完成GetIntentintent相应会根据options中提供的参数返回与之匹配的参数,

然后下面的代码将根据返回的意图进行实际上的操作,或加载相应的插件,比如当intent返回Weather,则首先从chatPlugin中使用Weather插件,并且传递当前用户输入内容,在这里将提取用户需要获取天气的城市。

完成返回以后将在使用MathFunction = _kernel.Skills.GetFunction("WeatherPlugin", "GetWeather")的方式获取WeatherPlugin插件的GetWeather方法,并且将得到的参数传递到_kernel.RunAsync执行的时候则会掉用GetWeather方法,这个时候会由插件返回的json在组合成定义的模板消息进行返回,就完成了调用。

            ISKFunction MathFunction = null;SKContext? result = null;//获取意图后动态调用Funif (intent is "Attractions" or "Delicacy" or "Traffic"){MathFunction = _kernel.Skills.GetFunction("Travel", intent);result = await _kernel.RunAsync(value, MathFunction);}else if (intent is "Weather"){var newValue = (await _kernel.RunAsync(new ContextVariables{["input"] = value}, chatPlugin["Weather"])).Result;MathFunction = _kernel.Skills.GetFunction("WeatherPlugin", "GetWeather");result = await _kernel.RunAsync(newValue, MathFunction);if (!result.Result.IsNullOrWhiteSpace()){if (result.Result.IsNullOrEmpty()){await SendMessage("获取天气失败了!", item.RevertId, item.Id);return;}var weather = JsonSerializer.Deserialize<GetWeatherModule>(result.Result);var live = weather?.lives.FirstOrDefault();await SendMessage(WeatherTemplate.Replace("{province}", live!.city).Replace("{weather}", live?.weather).Replace("{temperature_float}", live?.temperature_float).Replace("{winddirection}", live?.winddirection).Replace("{humidity}", live.humidity), item.RevertId, item.Id);return;}}else{var chatHistory = _chatCompletion.CreateNewChat();chatHistory.AddUserMessage(value);var reply = await _chatCompletion.GenerateMessageAsync(chatHistory);return;}

Weather的prompt

我会给你一句话,你需要找到需要获取天气的城市,如果存在时间也提供给我:
{{$input}}仅返回结果,除此之外不要有多余内容,按照如下格式:
{"city":"","time":""
}

WeatherPlugin获取天气插件


/// <summary>
/// 获取天气插件
/// </summary>
public class WeatherPlugin
{private static List<AdCode>? _codes;static WeatherPlugin(){var path = Path.Combine(AppContext.BaseDirectory, "adcode.json");if (File.Exists(path)){var str = File.ReadAllText(path);_codes = JsonSerializer.Deserialize<List<AdCode>>(str);}_codes ??= new List<AdCode>();}private readonly IHttpClientFactory _httpClientFactory;public WeatherPlugin(IHttpClientFactory httpClientFactory){_httpClientFactory = httpClientFactory;}[SKFunction, Description("获取天气")][SKParameter("input", "入参")]public async Task<string> GetWeather(SKContext context){var weatherInput = JsonSerializer.Deserialize<WeatherInput>(context.Result);var value = _codes.FirstOrDefault(x => x.name.StartsWith(weatherInput.city));if (value == null){return "请先描述指定城市!";}var http = _httpClientFactory.CreateClient(nameof(WeatherPlugin));var result = await http.GetAsync("https://restapi.amap.com/v3/weather/weatherInfo?key={高德天气api的key}&extensions=base&output=JSON&city=" +value.adcode);if (result.IsSuccessStatusCode){return await result.Content.ReadAsStringAsync();}return string.Empty;}
}public class WeatherInput
{public string city { get; set; }public string time { get; set; }
}public class AdCode
{public string name { get; set; }public string adcode { get; set; }public string citycode { get; set; }
}

效果图

以上代码可从仓库获取

项目开源地址

体验地址:https://chat.tokengo.top/ (可以使用Gitee快捷登录)
Github : https://github.com/239573049/chat
Gitee: https://gitee.com/hejiale010426/chat

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/139248.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

React Hooks之useReducer

一、useReducer const [state, dispatch] useReducer(reducer, initialArg, init?)useState 的替代方案。它接收一个形如 (state, action) > newState 的 reducer&#xff0c;并返回当前的 state 以及与其配套的 dispatch 方法。数据结构简单用useState&#xff0c;复杂时…

linux虚机新增加磁盘后在系统中查不到

问题描述 在虚机管理平台上对某一linux主机添加了一块硬盘&#xff0c;但在系统中并未显示 通过执行 lsblk&#xff0c;并未看到新增的硬盘信息 解决方法 1. 可通过重启服务器解决 2. 如果不能重启服务器&#xff0c;可重新扫描下 scsi总线 查看总线&#xff1a; ls /s…

全流程TOUGH系列软件应用丨入门丨基础丨进阶丨实操

TOUGH系列软件是由美国劳伦斯伯克利实验室开发的&#xff0c;旨在解决非饱和带中地下水、热运移的通用模拟软件。和传统地下水模拟软件Feflow和Modflow不同&#xff0c;TOUGH系列软件采用模块化设计和有限积分差网格剖分方法&#xff0c;通过配合不同状态方程&#xff08;EOS模…

Python---if选择判断结构、嵌套结构(if elif else)

1、if选择判断结构作用 if 英 /ɪf/ conj. &#xff08;表条件&#xff09;如果&#xff1b;&#xff08;表假设&#xff09;要是&#xff0c;假如&#xff1b;无论何时&#xff1b;虽然&#xff0c;即使&#xff1b;&#xff08;用于间接疑问&#xff09;是否&#xff1b…

GPT4 Plugins 插件 WebPilot 生成抖音文案

1. 生成抖音文案 1.1. 准备1篇优秀的抖音文案范例 1.2. Promept公式 你是一个有1000万粉丝的抖音主播&#xff0c; 请模仿下面的抖音脚本文案&#xff0c;重新改与一篇文章改写成2分钟的抖音视频脚本&#xff0c; 要求前一部分是十分有争议性的内容&#xff0c;并且能够引发…

Ubuntu 18.04 LTS中cmake-gui编译opencv-3.4.16并供Qt Creator调用

一、安装opencv 1.下载opencv-3.4.16的源码并解压 2.在解压后的文件夹内新建文件夹build以及opencv_install 3.启动cmake-gui并设置 sudo cmake-gui&#xff08;1&#xff09;设置界面中source及build路径 &#xff08;2&#xff09;点击configure&#xff0c;选择第一个def…

外置告警蜂鸣器使用小坑

告警蜂鸣器调试小坑 昨天调试新产品&#xff0c;由于IMO、MSC组织和IEC标准规定&#xff0c;不能使用带红色指示灯的蜂鸣器&#xff0c;于是更换了个不带灯。然而奇怪的现象出现了两次短响的程序在有的页面正常&#xff0c;有的页面就变成一声了。搞了一天&#xff0c;把各种寄…

变电站数字孪生3D可视化运维系统,实现电力行业智慧化数字化信息化转型升级

变电站数字孪生3D可视化运维系统&#xff0c;实现电力行业智慧化数字化信息化转型升级。近年来&#xff0c;随着科技不断发展与进步&#xff0c;我国在智慧电网国网电力建设方面取得了长足进展。目前已经在多个地区和国家建立起了智慧电网电力项目并投入运行&#xff0c;这些项…

如何实现前端懒加载图像?

聚沙成塔每天进步一点点 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xff01;这个专栏是为那些对Web开发感兴趣、刚刚踏入前端领域的朋友们量身打造的。无论你是完全的新手还是有一些基础的开发…

自动驾驶的法律和伦理问题

随着自动驾驶技术的不断发展&#xff0c;出现了一系列与法律和伦理有关的问题。这些问题涵盖了自动驾驶的法律框架、道路规则以及伦理挑战。本文将探讨这些问题&#xff0c;并分析自动驾驶所带来的法律和伦理挑战。 自动驾驶的法律框架 自动驾驶的法律框架是制定和管理自动驾…

解决微信小程序导入项目报错: [app.json文件内容错误]app.json未找到

目录 场景描述 原因分析 解决方法 场景描述 使用微信开发者工具导入项目后&#xff0c;打开控制台&#xff0c;出现报错提示&#xff1a;[app.json文件内容错误]app.json 未找到&#xff0c;如下图&#xff1a; 原因分析 一级文件目录里确实找不到app.json文件&#xff0c…

云上攻防-云原生篇K8s安全Config泄漏Etcd存储Dashboard鉴权Proxy暴露

文章目录 云原生-K8s安全-etcd未授权访问云原生-K8s安全-Dashboard未授权访问云原生-K8s安全-Configfile鉴权文件泄漏云原生-K8s安全-Kubectl Proxy不安全配置 云原生-K8s安全-etcd未授权访问 攻击2379端口&#xff1a;默认通过证书认证&#xff0c;主要存放节点的数据&#x…