以下是一个基于C#控制台的示例程序使用stream为true调用chatgpt聊天完成接口并实现打字一样的效果输出回复
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ChatGPTDemo
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("开始聊天,请输入你的问题:");
while (true)
{
string input = Console.ReadLine();
// 构造请求的Json数据
string json = $"{{\"question\": \"{input}\", \"stream\": true}}";
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送POST请求
using (HttpClient client = new HttpClient())
{
var response = await client.PostAsync("https://api.openai.com/v1/chatgpt/complete", content);
if (response.IsSuccessStatusCode)
{
// 解析Json数据
string responseJson = await response.Content.ReadAsStringAsync();
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(responseJson);
string text = result.choices[0].text;
// 打印回复
foreach (char c in text)
{
Console.Write(c);
await Task.Delay(30);
}
Console.WriteLine();
}
else
{
Console.WriteLine($"请求失败,状态码:{response.StatusCode}");
}
}
}
}
}
}
原文地址: http://www.cveoy.top/t/topic/01c 著作权归作者所有。请勿转载和采集!