c#通过网上AI大模型实现对话功能
目录
- 基础使用
- 给大模型额外提供函数能力
- 用Microsoft.Extensions.AI库实现
- 用json格式回答
基础使用
https://siliconflow.cn/网站有些免费的大模型可以使用,去注册个账户,拿到apikey
引用 nuget
Microsoft.Extensions.AI.OpenAI
using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;namespace ConsoleApp2
{internal class Program{static async Task Main(string[] args){OpenAIClientOptions openAIClientOptions = new OpenAIClientOptions();openAIClientOptions.Endpoint = new Uri("https://api.siliconflow.cn/v1");// SiliconCloud API Keystring mySiliconCloudAPIKey = "你的api key";OpenAIClient client = new OpenAIClient(new ApiKeyCredential(mySiliconCloudAPIKey), openAIClientOptions);IChatClient chatClient = client.AsChatClient("Qwen/Qwen2.5-7B-Instruct");while (true){var response = chatClient.CompleteStreamingAsync(Console.ReadLine());//手动输入问题await foreach (var item in response){Console.Write(item.Text);}Console.Write("\r\n\r\n");}}}
}
给大模型额外提供函数能力
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;namespace ConsoleApp2
{internal class Program{static async Task Main(string[] args){OpenAIClientOptions openAIClientOptions = new OpenAIClientOptions();openAIClientOptions.Endpoint = new Uri("https://api.siliconflow.cn/v1");// SiliconCloud API Keystring mySiliconCloudAPIKey = "你的api key";OpenAIClient client = new OpenAIClient(new ApiKeyCredential(mySiliconCloudAPIKey), openAIClientOptions);var assistantClient = client.GetChatClient("Qwen/Qwen2.5-7B-Instruct");await FunctionCallPlayground(assistantClient, "how is the weather today in beijing?");Console.ReadKey();}private static async Task FunctionCallPlayground(ChatClient chatClient, string prompt){Console.WriteLine(prompt);var messages = new[]{new UserChatMessage( prompt)};BinaryData functionParameters = BinaryData.FromBytes("""{"type": "object","properties": {"city": {"type": "string","description": "The name of the city to query weather for."}},"required": ["city"],"additionalProperties": false}"""u8.ToArray());var chatTool = ChatTool.CreateFunctionTool("get_weather", "Get the current weather for a given city.", functionParameters);var options = new ChatCompletionOptions{Temperature = 0.01f,TopP = 0.95f,};options.Tools.Add(chatTool);var response = chatClient.CompleteChat(messages, options);// 假设我们只处理第一个工具调用请求var func1Name = response.Value.ToolCalls[0].FunctionName;var func1Args = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,string>>( response.Value.ToolCalls[0].FunctionArguments.ToString());var func1Out = await GetWeather(func1Args["city"] );options = new ChatCompletionOptions{Temperature = 0.01f,TopP = 0.95f,};response = chatClient.CompleteChat(new ChatMessage[] { messages[0] , new ToolChatMessage(response.Value.ToolCalls[0].Id, func1Out) }, options);Console.WriteLine(response.Value.Content.FirstOrDefault()?.Text);}private static async Task<string> GetWeather(string city){return $"23摄氏度";}}}
用Microsoft.Extensions.AI库实现
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel;namespace ConsoleApp2
{internal class Program{const string APIKEY = "你的apikey";static async Task Main(string[] args){OpenAIClientOptions openAIClientOptions = new OpenAIClientOptions();openAIClientOptions.Endpoint = new Uri("https://api.siliconflow.cn/v1");// SiliconCloud API Keystring mySiliconCloudAPIKey = APIKEY;var weathfunc = new GetWeatherFunction();var humidtyfunc = new GetHumidityFunction();ChatOptions chatOptions = new ChatOptions(){Temperature = 0.01f,TopP = 0.95f,Tools = new AIFunction[] { weathfunc, humidtyfunc }};OpenAIClient client = new OpenAIClient(new ApiKeyCredential(mySiliconCloudAPIKey), openAIClientOptions);IChatClient chatClient = client.AsChatClient("Qwen/Qwen2.5-7B-Instruct");while (true){var question = Console.ReadLine();//手动输入问题var response = await chatClient.CompleteAsync(question, chatOptions);_check:if(response.FinishReason == Microsoft.Extensions.AI.ChatFinishReason.ToolCalls){List<AIContent> callRets = new List<AIContent>();foreach( var aiContent in response.Choices[0].Contents){if(aiContent is FunctionCallContent callContent){var callid = callContent.CallId;var func = (AIFunction)chatOptions.Tools.FirstOrDefault(m=>((AIFunction)m).Metadata.Name == callContent.Name);var ret =await func!.InvokeAsync(callContent.Arguments);callRets.Add(new FunctionResultContent(callid , callContent.Name , ret));}}List<Microsoft.Extensions.AI.ChatMessage> list = new List<Microsoft.Extensions.AI.ChatMessage>();list.Add(new Microsoft.Extensions.AI.ChatMessage(Microsoft.Extensions.AI.ChatRole.User, question));list.Add(new Microsoft.Extensions.AI.ChatMessage(Microsoft.Extensions.AI.ChatRole.Tool, callRets));response = await chatClient.CompleteAsync(list, chatOptions);goto _check;}else{Console.WriteLine(response.Choices[0].Contents.FirstOrDefault()?.ToString());}Console.Write("\r\n");}}}public class GetWeatherFunction : AIFunction{Microsoft.Extensions.AI.AIFunctionMetadata _Metadata;public override AIFunctionMetadata Metadata => _Metadata;public GetWeatherFunction() {_Metadata = new Microsoft.Extensions.AI.AIFunctionMetadata("get_weather"){Description = "Get the current weather for a given city.",Parameters = new[] { new AIFunctionParameterMetadata("city") { ParameterType = typeof(string),Description = "The name of the city to query weather for.",IsRequired = true,} }, };}protected override async Task<object?> InvokeCoreAsync(IEnumerable<KeyValuePair<string, object?>> arguments, CancellationToken cancellationToken){return $"23摄氏度";}}public class GetHumidityFunction : AIFunction{Microsoft.Extensions.AI.AIFunctionMetadata _Metadata;public override AIFunctionMetadata Metadata => _Metadata;public GetHumidityFunction(){_Metadata = new Microsoft.Extensions.AI.AIFunctionMetadata("get_humidity"){Description = "获取指定城市的湿度",Parameters = new[] { new AIFunctionParameterMetadata("city") {ParameterType = typeof(string),Description = "要获取湿度的城市名称",IsRequired = true,} },};}protected override async Task<object?> InvokeCoreAsync(IEnumerable<KeyValuePair<string, object?>> arguments, CancellationToken cancellationToken){return $"70%";}}}
用json格式回答
通过设置ResponseFormat 为json,可以让大模型以json格式输出
上面代码修改为:
List<Microsoft.Extensions.AI.ChatMessage> list = new List<Microsoft.Extensions.AI.ChatMessage>();list.Add(new Microsoft.Extensions.AI.ChatMessage(Microsoft.Extensions.AI.ChatRole.User, question));list.Add(new Microsoft.Extensions.AI.ChatMessage(Microsoft.Extensions.AI.ChatRole.Tool, callRets));ChatOptions chatOptions2 = new ChatOptions(){Temperature = 0.01f,TopP = 0.95f,MaxOutputTokens = int.MaxValue,ResponseFormat = Microsoft.Extensions.AI.ChatResponseFormat.Json,};response = await chatClient.CompleteAsync(list, chatOptions2);
注意:如果你的提问需要调用你自己定义的函数去计算,那么,提问时不要设置ResponseFormat ,否则回答类型不会是FinishReason == Microsoft.Extensions.AI.ChatFinishReason.ToolCalls,也就无法触发你的程序去调用函数了,只有计算完结果后,回传结果给大模型时才设置 ResponseFormat = Microsoft.Extensions.AI.ChatResponseFormat.Json
提问需要这么提问:
北京现在的温度和湿度是多少?请用这种格式回答:[“温度值”,“湿度值”]
相关文章:
c#通过网上AI大模型实现对话功能
目录 基础使用给大模型额外提供函数能力用Microsoft.Extensions.AI库实现用json格式回答 基础使用 https://siliconflow.cn/网站有些免费的大模型可以使用,去注册个账户,拿到apikey 引用 nuget Microsoft.Extensions.AI.OpenAI using Microsoft.Extensi…...

pymysql模块
1.pymysql基本使用 打开数据库连接,使用cursor()方法获取操作游标执行SQL语句 获取命令执行的查询结果 1.1 打开数据库连接 # 打开数据库连接 db pymysql.connect(host127.0.0.1,userroot,port3306,password"123",databasedb5) 1.2 使用cursor()方法获取操作游…...

WPF-模板和样式
在 WPF(Windows Presentation Foundation)中,模板是一种强大的机制,用于定义控件的外观。它允许你将控件的逻辑(功能)和外观(UI)分离开来。例如,一个按钮控件,…...

网络编程 day1.2~day2——TCP和UDP的通信基础(TCP)
笔记脑图 作业: 1、将虚拟机调整到桥接模式联网。 2、TCP客户端服务器实现一遍。 服务器 #include <stdio.h> #include <string.h> #include <myhead.h> #define IP "192.168.60.44" #define PORT 6666 #define BACKLOG 20 int mai…...
element ui table 每行不同状态
table 每行定义值 tableData: [ { name: ,type:,location:, ziduan:,createtype:,ziduanvalue:,checkAll:true,checkedCities: [空, null, str随机, int随机],isIndeterminate: true,table_id:single,downloaddisabled:true,deldisabled:true} ], table c…...
力扣--LRC 142.训练计划IV
题目 给定两个以 有序链表 形式记录的训练计划 l1、l2,分别记录了两套核心肌群训练项目编号,请合并这两个训练计划,按训练项目编号 升序 记录于链表并返回。 注意:新链表是通过拼接给定的两个链表的所有节点组成的。 示例 1&am…...

windows下,用CMake编译qt项目,出现错误By not providing “FindQt5.cmake“...
开发环境:windows10 qt5.14, 编译器msvc2017x64,CMake3.30; 现象: CMakeList文件里,如有find_package(Qt5 COMPONENTS Widgets REQUIRED) target_link_libraries(dis_lib PRIVATE Qt5::Widgets) 用CMak…...

【element-tiptap】Tiptap编辑器核心概念----结构篇
core-concepts 前言:这篇文章来介绍一下 Tiptap 编辑器的一些核心概念 (一)结构 1、 Schemas 定义文档组成方式。一个文档就是标题、段落以及其他的节点组成的一棵树。 每一个 ProseMirror 的文档都有一个与之相关联的 schema,…...
半导体工艺与制造篇3 离子注入
离子注入工艺 一般掺杂的杂质类别,包括:提供载流子的施主杂质和受主杂质;产生复合中心的重金属杂质 离子注入往往需要生成井well,其中井的定义:晶圆与杂质之间形成的扩散层或杂质与杂质之间形成的扩散层 离子注入的目的:用掺杂改…...

利用开源的低代码表单设计器FcDesigner高效管理和渲染复杂表单结构
FcDesigner 是一个强大的开源低代码表单设计器组件,支持快速拖拽生成表单。提供丰富的自定义及扩展功能,FcDesigner支持多语言环境,并允许开发者进行二次开发。通过将表单设计输出为JSON格式,再通过渲染器进行加载,实现…...
淘宝 NPM 镜像源
npm i vant/weapp -S --production npm config set registry https://registry.npmmirror.com 要在淘宝 NPM 镜像站下载项目或依赖,你可以按照以下步骤操作: 1. 设置淘宝 NPM 镜像源 首先,你需要设置淘宝 NPM 镜像源以加速下载。可以通过…...

i春秋-GetFlag(md5加密,字符串比较绕过)
练习平台地址 竞赛中心 题目描述 题目内容 你好,单身狗,这是一个迷你文件管理器,你可以登录和下载文件,甚至得到旗帜 点击登录 发现capture需要满足条件substr(md5(captcha), 0, 6)xxxxxx 编写python脚本破解验证码 import has…...

SpringBoot中设置超时30分钟自动删除元素的List和Map
简介 在 Spring Boot 中,你可以使用多种方法来实现自动删除超时元素的 List 或 Map。以下是两种常见的方式: 如果你需要简单的功能并且不介意引入外部依赖,可以选择 Guava Cache。如果你想要更灵活的控制,使用 Spring 的调度功能…...

入门车载以太网(6) -- XCP on Ethernet
目录 1.寻址方式 2.数据帧格式 3.特殊指令 4.使用实例 了解了SOME/IP之后,继续来看看车载以太网在汽车标定领域的应用。 在汽车标定领域XCP是非常重要的协议,咱们先来回顾下基础概念。 XCP全称Universal Measurement and Calibration Protocol&a…...

DAY4 网络编程(广播和多线程并发)
作业1: 1、将广播发送和接收端实现一遍,完成一个发送端发送信息,对应多个接收端接收信息实验。 send.c代码: #include <myhead.h> #define IP "192.168.61.255"//广播IP #define PORT 7777 int main(int argc, …...
C++个人复习(4)
C中为什么要引入make_shared,它有什么优点 1. 减少内存分配次数 使用 make_shared 时,内存分配只发生一次,它同时分配了对象和控制块(用于管理引用计数等信息)。而如果直接使用 new 创建对象并传递给 shared_ptr,则会…...

Dockerhub镜像加速
一、背景 dockerhub由于被封锁和站点处于国外的原因,docker pull拉取镜像非常慢,有时候直接都无法拉取。严重妨碍了我们的学习进度以及日常使用。 总结了一些proxy代理的镜像站点,配置之后速度会有明显提升,大家可以参考使用。 二…...
11.20讲座笔记
信息门户 -------- 人才培养方案(重要) 结构化矛盾------需求方(企业) ------供给方(高校) 电子方向职业 -------- 基建、基础算力 -------中国 1st (已经相对完善饱和) 网…...
网络协议之UDP
一、UDP协议定义 UDP(User Datagram Protocol,用户数据报协议)是一种面向无连接的、不可靠的、基于数据报的传输层通信协议。UDP在传输数据时不需要建立连接,直接将数据包发送出去。这种特性使得UDP在实时性要求较高的应用场景中…...
Elasticsearch面试内容整理-常见问题和解决方案
在使用 Elasticsearch 的过程中,可能会遇到各种常见问题,如集群状态异常、分片未分配、查询性能低下等。这些问题往往影响系统的可用性和性能,因此理解这些问题的成因和解决方案非常重要。以下是 Elasticsearch 常见问题及其解决方案的整理。 集群状态问题 Elasticsearch 集…...

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析
1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具,该工具基于TUN接口实现其功能,利用反向TCP/TLS连接建立一条隐蔽的通信信道,支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式,适应复杂网…...

【WiFi帧结构】
文章目录 帧结构MAC头部管理帧 帧结构 Wi-Fi的帧分为三部分组成:MAC头部frame bodyFCS,其中MAC是固定格式的,frame body是可变长度。 MAC头部有frame control,duration,address1,address2,addre…...

3.3.1_1 检错编码(奇偶校验码)
从这节课开始,我们会探讨数据链路层的差错控制功能,差错控制功能的主要目标是要发现并且解决一个帧内部的位错误,我们需要使用特殊的编码技术去发现帧内部的位错误,当我们发现位错误之后,通常来说有两种解决方案。第一…...

【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)
可以使用Sqliteviz这个网站免费编写sql语句,它能够让用户直接在浏览器内练习SQL的语法,不需要安装任何软件。 链接如下: sqliteviz 注意: 在转写SQL语法时,关键字之间有一个特定的顺序,这个顺序会影响到…...

相机从app启动流程
一、流程框架图 二、具体流程分析 1、得到cameralist和对应的静态信息 目录如下: 重点代码分析: 启动相机前,先要通过getCameraIdList获取camera的个数以及id,然后可以通过getCameraCharacteristics获取对应id camera的capabilities(静态信息)进行一些openCamera前的…...

Ascend NPU上适配Step-Audio模型
1 概述 1.1 简述 Step-Audio 是业界首个集语音理解与生成控制一体化的产品级开源实时语音对话系统,支持多语言对话(如 中文,英文,日语),语音情感(如 开心,悲伤)&#x…...

使用LangGraph和LangSmith构建多智能体人工智能系统
现在,通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战,比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...
Mysql8 忘记密码重置,以及问题解决
1.使用免密登录 找到配置MySQL文件,我的文件路径是/etc/mysql/my.cnf,有的人的是/etc/mysql/mysql.cnf 在里最后加入 skip-grant-tables重启MySQL服务 service mysql restartShutting down MySQL… SUCCESS! Starting MySQL… SUCCESS! 重启成功 2.登…...
Oracle11g安装包
Oracle 11g安装包 适用于windows系统,64位 下载路径 oracle 11g 安装包...
Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析
Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析 一、第一轮基础概念问题 1. Spring框架的核心容器是什么?它的作用是什么? Spring框架的核心容器是IoC(控制反转)容器。它的主要作用是管理对…...