C# 使用 ChatGPT Completion 接口并使用 Stream 返回数据
以下是使用 C# 编写 ChatGPT 的 Completion for the Chat Message 接口并使用 Stream 返回的示例代码:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ChatGPTDemo
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
// 设置请求头信息
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 构造请求数据
var requestData = new
{
prompt = 'Hello',
max_tokens = 50,
temperature = 0.7,
stop = '\n'
};
// 发送POST请求并获取响应数据流
var response = await client.PostAsJsonAsync("https://api.openai.com/v1/completions", requestData);
var stream = await response.Content.ReadAsStreamAsync();
// 读取响应数据流并输出
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
Console.WriteLine(line);
}
}
}
}
}
在上述示例代码中,我们使用 HttpClient 发送 POST 请求,并通过 Content.ReadAsStreamAsync() 方法获取响应数据流。然后,我们使用 StreamReader 从数据流中读取响应数据,并将其输出到控制台。
原文地址: https://www.cveoy.top/t/topic/l6Dr 著作权归作者所有。请勿转载和采集!