using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
// API的URL
string apiUrl = "https://api.openai.com/v1/chat/completions";
// 设置API的请求头
WebRequest request = WebRequest.Create(apiUrl);
request.Method = "POST";
request.Headers.Add("Authorization", "Bearer {YOUR_API_KEY}"); // 替换为你的API密钥
request.ContentType = "application/json";
// 设置API的请求体,包含输入和参数
string input = "请问天气怎么样?";
string prompt = "用户:" + input + "\n助理:";
int maxTokens = 50;
string requestBody = "{ \"messages\": [{ \"role\": \"system\", \"content\": \"You are a helpful assistant.\" }, { \"role\": \"user\", \"content\": \"" + prompt + "\" }], \"max_tokens\": " + maxTokens + " }";
byte[] byteArray = Encoding.UTF8.GetBytes(requestBody);
request.ContentLength = byteArray.Length;
// 发送请求并获取响应
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string responseJson = reader.ReadToEnd();
Console.WriteLine(responseJson);
// 在这里处理API的响应
}
response.Close();
}
}
标签:byteArray,string,c#,request,System,ai,API,using,chatgpt From: https://www.cnblogs.com/wang2650/p/17317982.html