首页 > 编程语言 >星火大模型C#调用实现

星火大模型C#调用实现

时间:2024-04-18 17:57:04浏览次数:22  
标签:调用 string get C# set 星火 date new public

static ClientWebSocket webSocket0;
static CancellationToken cancellation;
// 应用APPID(必须为webapi类型应用,并开通星火认知大模型授权)
const string x_appid = "xxxxx";
// 接口密钥(webapi类型应用开通星火认知大模型后,控制台--我的应用---星火认知大模型---相应服务的apikey)
const string api_secret = "xxxxxxx";
// 接口密钥(webapi类型应用开通星火认知大模型后,控制台--我的应用---星火认知大模型---相应服务的apisecret)
const string api_key = "xxxxxx";

static string hostUrl = "https://spark-api.xf-yun.com/v3.5/chat";
private void Form2_Load(object sender, EventArgs e)
{
    Tasker(textBox1);
}
async public static void Tasker(TextBox box)
{

    string authUrl = GetAuthUrl();
    string url = authUrl.Replace("http://", "ws://").Replace("https://", "wss://");
    using (webSocket0 = new ClientWebSocket())
    {
        try
        {
            await webSocket0.ConnectAsync(new Uri(url), cancellation);

            JsonRequest request = new JsonRequest();
            request.header = new Header()
            {
                app_id = x_appid,
                uid = "12345"
            };
            request.parameter = new Parameter()
            {
                chat = new Chat()
                {
                    domain = "generalv3.5",//模型领域,默认为星火通用大模型
                    temperature = 0.5,//温度采样阈值,用于控制生成内容的随机性和多样性,值越大多样性越高;范围(0,1)
                    max_tokens = 1024,//生成内容的最大长度,范围(0,4096)
                }
            };
            request.payload = new Payload()
            {
                message = new Message()
                {
                    text = new List<Content>
                                        {
                        //new Content() { role = "system", content = "你现在扮演李白,你豪情万丈,狂放不羁;接下来请用李白的口吻和用户对话。" },
                                            new Content() { role = "user", content = "百度的地址是多少" },
                                            // new Content() { role = "assistant", content = "....." }, // AI的历史回答结果,这里省略了具体内容,可以根据需要添加更多历史对话信息和最新问题的内容。
                                        }
                }
            };

            string jsonString = JsonConvert.SerializeObject(request);
            //连接成功,开始发送数据


            var frameData2 = System.Text.Encoding.UTF8.GetBytes(jsonString.ToString());


            webSocket0.SendAsync(new ArraySegment<byte>(frameData2), WebSocketMessageType.Text, true, cancellation);

            // 接收流式返回结果进行解析
            byte[] receiveBuffer = new byte[1024];
            WebSocketReceiveResult result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
            String resp = "";
            while (!result.CloseStatus.HasValue)
            {
                if (result.MessageType == WebSocketMessageType.Text)
                {
                    string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
                    //将结果构造为json

                    JObject jsonObj = JObject.Parse(receivedMessage);
                    int code = (int)jsonObj["header"]["code"];
                    JArray textArray1 = (JArray)jsonObj["payload"]["choices"]["text"];
                    string content1 = (string)textArray1[0]["content"];
                    box.Text = box.Text+content1;
                    if (0 == code)
                    {
                        int status = (int)jsonObj["payload"]["choices"]["status"];


                        JArray textArray = (JArray)jsonObj["payload"]["choices"]["text"];
                        string content = (string)textArray[0]["content"];
                        resp += content;

                        if (status != 2)
                        {
                            
                            //MessageBox.Show($"已接收到数据: {receivedMessage}");
                        }
                        else
                        {
                            //MessageBox.Show($"最后一帧: {receivedMessage}");
                            int totalTokens = (int)jsonObj["payload"]["usage"]["text"]["total_tokens"];
                            //MessageBox.Show($"整体返回结果: {resp}");
                            //MessageBox.Show($"本次消耗token数: {totalTokens}");
                            break;
                        }

                    }
                    else
                    {
                        MessageBox.Show($"请求报错: {receivedMessage}");
                    }


                }
                else if (result.MessageType == WebSocketMessageType.Close)
                {
                    MessageBox.Show("已关闭WebSocket连接");
                    break;
                }

                result = await webSocket0.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellation);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
}

// 返回code为错误码时,请查询https://www.xfyun.cn/document/error-code解决方案
static string GetAuthUrl()
{
    string date = DateTime.UtcNow.ToString("r");

    Uri uri = new Uri(hostUrl);
    StringBuilder builder = new StringBuilder("host: ").Append(uri.Host).Append("\n").//
                            Append("date: ").Append(date).Append("\n").//
                            Append("GET ").Append(uri.LocalPath).Append(" HTTP/1.1");

    string sha = HMACsha256(api_secret, builder.ToString());
    string authorization = string.Format("api_key=\"{0}\", algorithm=\"{1}\", headers=\"{2}\", signature=\"{3}\"", api_key, "hmac-sha256", "host date request-line", sha);
    //System.Web.HttpUtility.UrlEncode

    string NewUrl = "https://" + uri.Host + uri.LocalPath;

    string path1 = "authorization" + "=" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(authorization));
    date = date.Replace(" ", "%20").Replace(":", "%3A").Replace(",", "%2C");
    string path2 = "date" + "=" + date;
    string path3 = "host" + "=" + uri.Host;

    NewUrl = NewUrl + "?" + path1 + "&" + path2 + "&" + path3;
    return NewUrl;
}




public static string HMACsha256(string apiSecretIsKey, string buider)
{
    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(apiSecretIsKey);
    System.Security.Cryptography.HMACSHA256 hMACSHA256 = new System.Security.Cryptography.HMACSHA256(bytes);
    byte[] date = System.Text.Encoding.UTF8.GetBytes(buider);
    date = hMACSHA256.ComputeHash(date);
    hMACSHA256.Clear();

    return Convert.ToBase64String(date);

}

  

//构造请求体
public class JsonRequest
{
    public Header header { get; set; }
    public Parameter parameter { get; set; }
    public Payload payload { get; set; }
}

public class Header
{
    public string app_id { get; set; }
    public string uid { get; set; }
}

public class Parameter
{
    public Chat chat { get; set; }
}

public class Chat
{
    public string domain { get; set; }
    public double temperature { get; set; }
    public int max_tokens { get; set; }
}

public class Payload
{
    public Message message { get; set; }
}

public class Message
{
    public List<Content> text { get; set; }
}

public class Content
{
    public string role { get; set; }
    public string content { get; set; }
}

 

标签:调用,string,get,C#,set,星火,date,new,public
From: https://www.cnblogs.com/liao-long/p/18144103

相关文章

  • java-collections-map t
    MapMap常用子类HashMap:HashMap是最常用的Map实现之一,它基于哈希表实现,提供了O(1)时间复杂度的插入、删除和查找操作。Hashtable:Hashtable是较早期的Java集合类,它是线程安全的,但性能通常比HashMap差,因为它的方法是同步的。TreeMap:TreeMap是基于红黑树实现的有序Ma......
  • C# Lock锁对象的理解
    我们lock的一般是对象,不是值类型和字符串。1、为什么不能lock值类型比如lock(1)呢?lock本质上Monitor.Enter,Monitor.Enter会使值类型装箱,每次lock的是装箱后的对象。lock其实是类似编译器的语法糖,因此编译器直接限制住不能lock值类型。退一万步说,就算能编译器允许你lock(1),......
  • Pyecharts制作动态GDP柱状图
    学习使用pyecharts制作动态柱状图使用csv模块进行csv数据文件处理importcsvfrompyecharts.chartsimportBar,Timelinefrompyecharts.optionsimport*frompyecharts.globalsimportThemeTypedefdealCSVFile():"""读取处理csv数据文件:retu......
  • VKL144C/D LQFP48/SSOP48仪器仪表超低功耗/超省电LCD液晶段码驱动IC: 分贝仪、测光仪
    VKL144C/D概述:VKL144C/D是一个点阵式存储映射的LCD驱动器,可支持最大144点(36SEGx4COM)的LCD屏。单片机可通过I2C接口配置显示参数和读写显示数据,可配置4种功耗模式,也可通过关显示和关振荡器进入省电模式。其高抗干扰,低功耗的特性适用于水电气表以及工控仪表类产品。特点•工......
  • 使用c#8语法
    [C#]framework修改项目语言为C#8.0_.netframework项目如何修改c#语言-CSDN博客在项目文件中增加一条:<PropertyGroupCondition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"><PlatformTarget>AnyCPU</PlatformTarget><DebugSy......
  • Vue的class类面向对象
    一.准备工作JavaScript语言中,生成实例对象的传统方法是通过构造函数functionAnimal(name,age){this.name=name;this.age=age;}Animal.prototype.showName=function(){console.log(this.name);......
  • 10 个优化技巧,减少 Docker 镜像大小【转】
    什么是docker?Docker是一种容器引擎,可以在容器内运行一段代码。Docker镜像是在任何地方运行您的应用程序而无需担心应用程序依赖性的方式。要构建镜像,docker使用一个名为Dockerfile的文件。Dockerfile是一个包含许多指令(RUN、COPY、EXPOSE等)的文件。成功执行这些命令后,do......
  • CF1933D Turtle Tenacity: Continual Mods
    思路:此题其实很简单,不要被邪恶的出题人迷惑了双眼。此题判断有解一共有两种情况。通过题意可以知道将原数组排序后如果\(b_{1}\neb_{2}\),那么最后的结果一定\(\ne0\),这是第一种情况。第二种情况其实就是第一种情况的变形,在排序后\(b_{1}=b_{2}\)的情况下,如果\(b\)......
  • P7177 [COCI2014-2015#4] MRAVI 题解
    思路。我们知道最初添加的液体越多,那么每个蚂蚁得到的液体也就越多,又因为标签里有深搜,所以可以用DFS+二分解决(感觉说了一通废话),算是比较常规的一种解法了。在此题中我们需要魔改一下建树,需在其中添加判断此边是否为超级管道和处理通过液体的百分比这两段代码。DFS和二分的代......
  • 使用 Dockerfile 定制镜像【转】
    前言大家好,本文是对Docker自定义镜像的详细讲解,讲解了如何进行构建自己的Docker镜像以及Dockerfile的操作指令。希望对大家有所帮助~一、使用Dockerfile定制镜像1.1、Dockerfile定制镜像镜像的定制实际上就是定制每一层所添加的配置、文件。如果我们可以把每一层修改......