-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatGPT.cs
175 lines (153 loc) · 5.57 KB
/
ChatGPT.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.SignalR;
namespace TeacherAI;
public class ChatGPT(HttpClient client, string model, IHubClients<IChatClient> hub = null, string chatId = null)
{
public async Task<ChatGPTCompletion> SendGptRequestStreamingAsync(IList<ChatGPTMessage> prompts, double temperature, double topP, string identifier)
{
var request = new ChatGPTRequest
{
User = identifier,
Temperature = temperature,
TopP = topP,
Choices = 1,
Stream = true,
StreamOptions = new() { IncludeUsage = true },
Messages = prompts,
Model = model
};
using var body = JsonContent.Create(request);
using var message = new HttpRequestMessage(HttpMethod.Post, string.Empty) { Content = body };
using var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
if (response.StatusCode == HttpStatusCode.BadRequest) return new() { Content = "Request rejected.", FinishReason = "prompt_filter" };
if (!response.IsSuccessStatusCode) return new() { Content = "Request failed.", FinishReason = "error" };
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
var content = new StringBuilder();
string finishReason = null;
var promptTokens = 0;
var completionTokens = 0;
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (string.IsNullOrEmpty(line) || !line.StartsWith("data: ", StringComparison.Ordinal)) continue;
if (line == "data: [DONE]") break;
var chunk = JsonSerializer.Deserialize<ChatGPTResponseChunk>(line[6..]);
if (chunk?.Usage is not null)
{
promptTokens = chunk.Usage.PromptTokens;
completionTokens = chunk.Usage.CompletionTokens;
}
if (chunk?.FinishReason is not null) finishReason = chunk.FinishReason;
if (chunk?.Value is null) continue;
content.Append(chunk.Value);
if (hub is not null) await hub.Client(chatId).Type(chunk.Value);
}
return new() { Content = content.ToString(), FinishReason = finishReason, PromptTokens = promptTokens, CompletionTokens = completionTokens };
}
public async Task<ChatGPTCompletion> SendGptRequestAsync(IList<ChatGPTMessage> prompts, double temperature, double topP, string identifier)
{
var request = new ChatGPTRequest
{
User = identifier,
Temperature = temperature,
TopP = topP,
Choices = 1,
Messages = prompts,
Model = model
};
using var body = JsonContent.Create(request);
using var response = await client.PostAsync(string.Empty, body);
if (response.StatusCode == HttpStatusCode.BadRequest) return new() { Content = "Request rejected.", FinishReason = "prompt_filter" };
if (!response.IsSuccessStatusCode) return new() { Content = "Request failed.", FinishReason = "error" };
var data = JsonSerializer.Deserialize<ChatGPTResponse>(await response.Content.ReadAsStringAsync());
return new() { Content = data.Value, FinishReason = data.FinishReason };
}
}
public class ChatGPTRequest
{
[JsonPropertyName("messages")]
public IList<ChatGPTMessage> Messages { get; set; }
[JsonPropertyName("user")]
public string User { get; set; }
[JsonPropertyName("temperature")]
public double Temperature { get; set; }
[JsonPropertyName("top_p")]
public double TopP { get; set; }
[JsonPropertyName("n")]
public double Choices { get; set; }
[JsonPropertyName("stream")]
public bool Stream { get; set; }
[JsonPropertyName("model")]
public string Model { get; set; }
[JsonPropertyName("stream_options")]
public StreamOptions StreamOptions { get; set; }
}
public class StreamOptions
{
[JsonPropertyName("include_usage")]
public bool IncludeUsage { get; set; }
}
public class ChatGPTMessage
{
[JsonPropertyName("role")]
public string Role { get; set; }
[JsonPropertyName("content")]
public string Content { get; set; }
}
public class ChatGPTResponse
{
[JsonPropertyName("choices")]
public IList<ChatGPTResponseChoice> Choices { get; set; }
[JsonIgnore]
public string Value => Choices?[0].Message?.Content;
[JsonIgnore]
public string FinishReason => Choices?[0].FinishReason;
}
public class ChatGPTResponseChoice
{
[JsonPropertyName("message")]
public ChatGPTResponseMessage Message { get; set; }
[JsonPropertyName("finish_reason")]
public string FinishReason { get; set; }
}
public class ChatGPTResponseChunk
{
[JsonPropertyName("choices")]
public IList<ChatGPTResponseChunkChoice> Choices { get; set; }
[JsonIgnore]
public string Value => Choices is null || Choices.Count == 0 ? null : Choices[0].Delta?.Content;
[JsonIgnore]
public string FinishReason => Choices is null || Choices.Count == 0 ? null : Choices[0].FinishReason;
[JsonPropertyName("usage")]
public UsageData Usage { get; set; }
}
public class UsageData
{
[JsonPropertyName("prompt_tokens")]
public int PromptTokens { get; set; }
[JsonPropertyName("completion_tokens")]
public int CompletionTokens { get; set; }
}
public class ChatGPTResponseChunkChoice
{
[JsonPropertyName("delta")]
public ChatGPTResponseMessage Delta { get; set; }
[JsonPropertyName("finish_reason")]
public string FinishReason { get; set; }
}
public class ChatGPTResponseMessage
{
[JsonPropertyName("content")]
public string Content { get; set; }
}
public class ChatGPTCompletion
{
public string Content { get; set; }
public string FinishReason { get; set; }
public int PromptTokens { get; set; }
public int CompletionTokens { get; set; }
}