ChatGpt API
1.创建c#控制台程序
注意
我创建的控制台程序目标框架为**.NET7**
2.Nuget安装Betalgo.OpenAI.GTP3 包
3.以流式方式输出
public class Program
{
protected static readonly string API_KEY = "输入你的APIKEY";
protected static List<ChatMessage> s_chat_message = new List<ChatMessage>();
static void Main(string[] args)
{
Console.WriteLine("准备就绪");
while(true)
{
string? prompt = Console.ReadLine();
if(!string.IsNullOrEmpty(prompt))
{
args = prompt.Split(' ');
switch(args[0])
{
case "clear":
{
s_chat_message.Clear();
Console.WriteLine("已清空上下文");
continue;
}
case "load":
{
if(args.Length > 1)
{
string file_path = args[1];
if (File.Exists(file_path))
{
string json_data = File.ReadAllText(file_path, Encoding.UTF8);
List<ChatMessage>? list_chat_message = JsonSerializer.Deserialize<List<ChatMessage>>(json_data);
if (list_chat_message != null)
s_chat_message = list_chat_message;
Console.WriteLine("success");
}
else Console.WriteLine("error");
}
break;
}
case "save":
{
if(args.Length > 1)
{
string file_path = args[1];
if(File.Exists(file_path))
{
string json_data = JsonSerializer.Serialize(s_chat_message);
string? dir_name = Path.GetDirectoryName(file_path);
if(!string.IsNullOrEmpty(dir_name) && !Directory.Exists(dir_name))
Directory.CreateDirectory(dir_name);
File.WriteAllText(file_path, json_data);
Console.WriteLine("success");
}
else Console.WriteLine("error");
}
break;
}
}
_ = Completion(prompt);
}
}
}
protected static async Task<bool> Completion(string prompt)
{
s_chat_message.Add(ChatMessage.FromUser(prompt));
var openAiService = new OpenAIService(new OpenAiOptions()
{
ApiKey = API_KEY
});
ChatCompletionCreateRequest request = new ChatCompletionCreateRequest()
{
Messages = s_chat_message
};
var completionResult = openAiService.ChatCompletion.CreateCompletionAsStream(request, Models.ChatGpt3_5Turbo);
string print_content = string.Empty;
await foreach (var completion in completionResult)
{
if (completion.Successful)
{
Console.Write(completion.Choices.FirstOrDefault()?.Message.Content);
print_content += completion.Choices.FirstOrDefault()?.Message.Content;
}
else
{
Console.WriteLine("Unknown Error");
Console.WriteLine($"{completion?.Error?.Code}: {completion?.Error?.Message}");
print_content = string.Empty;
}
}
if(!string.IsNullOrEmpty(print_content))
{
s_chat_message.Add(ChatMessage.FromAssistance(print_content));
}
Console.WriteLine(System.Environment.NewLine);
Console.WriteLine("完成");
return true;
}
}