C#对接chatgpt

西街长安
2023-05-31 / 1 评论 / 110 阅读 / 正在检测是否收录...
  1. 获取OpenAI API密钥:首先,需要在OpenAI网站上注册并获取API密钥。这将允许通过API与ChatGPT进行通信。
  2. 之后我们再创建几个类用于储存需要提交的数据。

    internal record class Message(string role,string content);
    internal class Data
     {
         public string model = "gpt-3.5-turbo";
         public Message[] messages;
         public float temperature=0.7f;
         public bool stream = false;//此处是告诉chatgpt是否通过流返回数据,如果为true,则后面代码中的Reader.ReadToEnd()要修改为Reader.ReadLine()
     }
  3. 发起HTTP请求:使用C#中的HttpClient类,可以发起HTTP POST请求来与OpenAI API进行通信。在请求标头中,需要设置Authorization标头,并在请求主体中提供必要的参数。

    using System.Text.Json;
    using System.Net.Http;
    using System.Text;
    using System.Net.Http.Headers;
    using System.Net.Http.Json;
    using Newtonsoft.Json;
    using System.Net;
    
    namespace ConsoleApp13
    {
     internal class Program
     {
         static void Main(string[] args)
         {
             string key = "这里填你的Key";
             string result = "";//这里是最后拿到的json数据
             HttpWebRequest http = (HttpWebRequest)WebRequest.Create("https://api.openai.com/v1/chat/completions");
             Data data = new Data() {
                 messages=new Message[] {new Message("user","用c#写登录功能")}
             };
             http.ContentType = "application/json";
             http.Method = "POST";
             http.Headers.Add("Authorization", $"Bearer {Key}");
             byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
             http.ContentLength = bytes.Length;
             using (Stream streamr = http.GetRequestStream())
             {
                 streamr.Write(bytes, 0, bytes.Length);
             }
             HttpWebResponse response = (HttpWebResponse)http.GetResponse();
             Stream stream = response.GetResponseStream();
             using (StreamReader reader = new StreamReader(stream))
             {
                 result = reader.ReadToEnd();
             }
                 
                 
             
         }
     }
    }

1

评论 (1)

取消
  1. 头像
    南浔
    Android · Google Chrome

    表情

    回复