-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApi.cs
265 lines (234 loc) · 10.6 KB
/
Api.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System.Globalization;
using System.Text.Json;
namespace TeacherAI;
public static class Api
{
private static readonly JsonSerializerOptions jsonOptions = new() { PropertyNameCaseInsensitive = true };
public static void MapApiPaths(this WebApplication app)
{
var group = app.MapGroup("/api").ValidateAntiforgery();
group.MapPost("/chat", [Authorize] async (ChatRequest chatRequest, HttpContext context, IHttpClientFactory httpClientFactory, IHubContext<ChatHub, IChatClient> hubContext) =>
{
var ticks = DateTime.UtcNow.Ticks;
var nameParts = context.User.Identity.Name.Split('@');
var service = new TableService(nameParts[1]);
var remainingCredits = Organisation.Instance.UserCreditsPerWeek - await service.CalculateUsageAsync(nameParts[0]);
if (remainingCredits <= 0) return Results.BadRequest("Insufficient credits.");
chatRequest.Messages.Insert(0, new()
{
Role = "system",
Content = $"You are a friendly and professional assistant, supporting teachers in a UK secondary school. Use British English. " +
$"It is {DateTime.UtcNow:d MMM yyyy}."
});
ChatGPTCompletion response = null;
var model = OpenAIModel.Dictionary[chatRequest.ModelType];
try
{
var chat = new ChatGPT(httpClientFactory.CreateClient("OpenAI"), model.Name, hubContext.Clients, chatRequest.ConnectionId);
response = await chat.SendGptRequestStreamingAsync(chatRequest.Messages, chatRequest.Temperature, 0.95, $"{ticks}");
if (response.FinishReason is not "prompt_filter" and not "error")
{
chatRequest.Messages.Add(new() { Role = "assistant", Content = response.Content });
}
}
finally
{
#if !DEBUG
await service.LogChatAsync(nameParts[0], chatRequest, ticks, response?.PromptTokens ?? 0, response?.CompletionTokens ?? 0, GetFilterReason(response.FinishReason));
#endif
}
var thisUsage = (double)((response.PromptTokens * model.CostPerPromptToken) + (response.CompletionTokens * model.CostPerCompletionToken));
var data = new ChatResponse
{
Response = response.Content,
FinishReason = response.FinishReason,
RemainingCredits = Math.Max((int)Math.Round(remainingCredits - thisUsage, 0, MidpointRounding.AwayFromZero), 0),
Stop = response.PromptTokens + response.CompletionTokens > (chatRequest.ModelType == "default" ? 10000 : 3200) || response.FinishReason != "stop"
};
return Results.Ok(data);
});
group.MapPost("/feedback", async (FeedbackRequest feedbackRequest, HttpContext context, IHttpClientFactory httpClientFactory, IHubContext<ChatHub, IChatClient> hubContext, IWebHostEnvironment env) =>
{
var nameParts = context.User.Identity.Name.Split('@');
var service = new TableService(nameParts[1]);
var remainingCredits = Organisation.Instance.UserCreditsPerWeek - await service.CalculateUsageAsync(nameParts[0]);
if (remainingCredits <= 0) return Results.BadRequest("Insufficient credits.");
var spreadsheet = new Spreadsheet(feedbackRequest.Url);
try
{
await spreadsheet.OpenAsync();
}
catch (SpreadsheetSetupException exc)
{
return Results.Problem(exc.Message);
}
var defaultModelName = OpenAIModel.Dictionary["default"].Name;
var chat = new ChatGPT(httpClientFactory.CreateClient("OpenAI"), defaultModelName);
var systemPrompt = new ChatGPTMessage
{
Role = "system",
Content =
@"You are a teacher who marks student work. Evaluate it against all the points in the grading criteria, using the same headings that are written at the start of each bullet point.
Output format:
{
""evaluation"": ""* Criterion heading - Yes, evidence: ... (or) No, reasoning: ...\n* Criterion heading - Yes, evidence: ... (or) No, reasoning: ..."",
""mark"": N,
""feedback"": ""Paragraph of feedback to the student (in the second person) including at least two strengths and a development area"",
""task"": ""Task for the student to add or rewrite a paragraph to reach a higher mark or elevate their response if it already achieved full marks"",
""spag"": ""Comment on spelling, punctuation, and grammar; say 'All correct' or identify all the errors and how to fix them""
}"
};
var total = spreadsheet.Responses.Count(o => o.Mark is null);
var index = 0;
for (var i = 0; i < spreadsheet.Responses.Count; i++)
{
var studentWork = spreadsheet.Responses[i];
if (studentWork.Mark is not null) continue;
await hubContext.Clients.Client(feedbackRequest.ConnectionId).Feedback(studentWork.Name, index++, total);
var userPrompt = new ChatGPTMessage
{
Role = "user",
Content = $"# Question\n\"\"\"\n{spreadsheet.Question}\n\"\"\"\n\n# Grading criteria:\n\"\"\"\n{spreadsheet.MarkScheme}\n\"\"\"\n\n" +
$"# Student answer:\n\"\"\"\n{studentWork.Response}\n\"\"\""
};
var prompts = new List<ChatGPTMessage>() { systemPrompt, userPrompt };
ChatGPTCompletion response = null;
var ticks = DateTime.UtcNow.Ticks;
try
{
response = await chat.SendGptRequestAsync(prompts, 0, 0, $"{ticks}");
if (response.FinishReason is not "prompt_filter" and not "error")
{
prompts.Add(new() { Role = "assistant", Content = response.Content });
}
}
finally
{
if (!env.IsDevelopment())
{
var chatRequest = new ChatRequest
{
Messages = prompts,
Temperature = 0,
ConversationId = feedbackRequest.ConversationId,
ModelType = "default",
TemplateId = "feedback-spreadsheet"
};
await service.LogChatAsync(nameParts[0], chatRequest, ticks, response?.PromptTokens ?? 0, response?.CompletionTokens ?? 0, GetFilterReason(response.FinishReason));
}
}
FeedbackResponse feedback;
try
{
feedback = response.FinishReason == "stop"
? JsonSerializer.Deserialize<FeedbackResponse>(response.Content, jsonOptions)
: new() { Mark = -1, Evaluation = response.FinishReason == "error" ? "Error: marking failed" : "Error: content filter triggered" };
}
catch (JsonException)
{
feedback = new() { Mark = -1, Evaluation = "Error: unable to parse output" };
}
await spreadsheet.WriteFeedbackAsync(i, feedback);
}
return Results.Ok();
});
group.MapPost("/admin", [Authorize(Roles = Roles.Admin)] async (AdminRequest adminRequest, HttpContext context) =>
{
var nameParts = context.User.Identity.Name.Split('@');
var service = new TableService(nameParts[1]);
var parts = adminRequest.Command.ToLowerInvariant().Split(' ');
var command = parts[0];
switch (command)
{
case "spend":
if (parts.Length != 2 || !int.TryParse(parts[1], out var days)) return Results.Ok("Usage: spend {days}");
var spend = await service.CalculateTotalSpendAsync(days);
return Results.Ok($"Total spend for the past {days} {(days == 1 ? "day" : "days")}: {spend} credits");
case "credit":
if (parts.Length != 3 || !int.TryParse(parts[2], out var credits)) return Results.Ok("Usage: credit {username} {credits}");
await service.AddCreditsAsync(parts[1], credits);
return Results.Ok($"{credits} credits added to user {parts[1]}");
case "recent":
if (parts.Length != 2 || !int.TryParse(parts[1], out var n)) return Results.Ok("Usage: recent {n}");
var recent = await service.GetRecentChatsAsync(n);
if (recent.Count == 0) return Results.Ok("No conversations in the past 3 days.");
var intro = recent.Count == n ? $"{n} most recent conversations" : $"All {recent.Count} conversations from the past 3 days";
var output = $"{intro}:\n\n" + string.Join("\n\n",
recent.Select(o => $"# {o.First().RowKey.Split('_')[0]} - {new DateTime(long.Parse(o.First().RowKey.Split('_')[1], CultureInfo.InvariantCulture)):ddd d MMM 'at' HH:mm} " +
$"- {o.First().Template}\n\n{string.Join("\n\n", o.Select(c => $"**{o.First().RowKey.Split('_')[0]}**:\n\n{c.UserPrompt}\n\n**{c.Model}**:\n\n{c.Completion}"))}\n\n"));
return Results.Ok(output);
case "leaderboard":
if (parts.Length > 1) return Results.Ok("Usage: leaderboard");
var leaderboard = await service.GetLeaderboardAsync();
return Results.Ok("# This week's leaderboard\n\n| User | Words | Chats | Credits |\n| :-- | :-: | :-: | :-: |\n" + string.Join('\n', leaderboard));
default:
return Results.Ok("Unknown command.");
}
});
}
private static string GetFilterReason(string finishReason)
{
return finishReason switch
{
"prompt_filter" => "Harmful prompt",
"content_filter" => "Harmful completion",
_ => "OK"
};
}
}
public static class AntiForgeryExtensions
{
public static TBuilder ValidateAntiforgery<TBuilder>(this TBuilder builder) where TBuilder : IEndpointConventionBuilder
{
return builder.AddEndpointFilter(async (context, next) =>
{
try
{
var antiForgeryService = context.HttpContext.RequestServices.GetRequiredService<IAntiforgery>();
await antiForgeryService.ValidateRequestAsync(context.HttpContext);
}
catch (AntiforgeryValidationException)
{
return Results.BadRequest("Antiforgery token validation failed.");
}
return await next(context);
});
}
}
public class ChatRequest
{
public IList<ChatGPTMessage> Messages { get; set; }
public string ModelType { get; set; }
public double Temperature { get; set; }
public string TemplateId { get; set; }
public string ConversationId { get; set; }
public string ConnectionId { get; set; }
}
public class ChatResponse
{
public string Response { get; set; }
public int RemainingCredits { get; set; }
public bool Stop { get; set; }
public string FinishReason { get; set; }
}
public class AdminRequest
{
public string Command { get; set; }
}
public class FeedbackRequest
{
public string Url { get; set; }
public string ConversationId { get; set; }
public string ConnectionId { get; set; }
}
public class FeedbackResponse
{
public string Evaluation { get; set; }
public int Mark { get; set; }
public string Feedback { get; set; }
public string Task { get; set; }
public string SPaG { get; set; }
}