-
Notifications
You must be signed in to change notification settings - Fork 13
/
Program.cs
58 lines (49 loc) · 1.82 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using OpenAI.ChatGpt;
using OpenAI.ChatGpt.Models;
using Console = Spectre.Console.AnsiConsole;
Console.MarkupLine("[underline yellow]Welcome to ChatGPT Console![/]");
Console.MarkupLine("[underline red]Press Ctrl+C to stop writing[/]");
Console.WriteLine();
var name = Console.Ask<string?>("What's your [green]name[/]?") ?? "Me";
var apiKey = LoadApiKey();
await using ChatService chatService = await ChatGPT.CreateInMemoryChat(
apiKey,
config: new ChatGPTConfig() { MaxTokens = 200 },
initialDialog: Dialog.StartAsSystem($"You are helpful assistant for a person named {name}.")
);
SetupCancellation(chatService);
Console.MarkupLine("[underline yellow]Start chat. Now ask something ChatGPT...[/]");
while (Console.Ask<string>($"[underline green]{name}[/]: ") is { } userMessage)
{
Console.Markup("[underline red]ChatGPT[/]: ");
var stream = chatService.StreamNextMessageResponse(userMessage, throwOnCancellation: false);
await foreach (string chunk in stream.SkipWhile(string.IsNullOrWhiteSpace))
{
if (!chatService.IsCancelled) Console.Write(chunk);
}
Console.WriteLine();
}
string LoadApiKey()
{
var key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
?? Console.Ask<string>("Please enter your [green]OpenAI API key[/] " +
"(you can get it from https://platform.openai.com/account/api-keys): ");
return key;
}
void SetupCancellation(ChatService chat)
{
System.Console.CancelKeyPress += (_, args) =>
{
if (chat.IsWriting && !chat.IsCancelled)
{
chat.Stop();
args.Cancel = true;
Console.Write($"...{Environment.NewLine}Stopped. Press Ctrl+C again to exit.");
}
else
{
Console.WriteLine();
Console.WriteLine("Bye!");
}
};
}