-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateLearningPlan.cs
More file actions
73 lines (61 loc) · 2.54 KB
/
Copy pathGenerateLearningPlan.cs
File metadata and controls
73 lines (61 loc) · 2.54 KB
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
using HoTeach.Entities;
using HoTeach.Infrastructure.Interfaces;
using HoTeach.Requests;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OpenAI.Chat;
using Path = HoTeach.Entities.Path;
namespace HoTeach
{
public class GenerateLearningPlan(ChatClient client, IRepository<UserPreferences> prefRepo, IRepository<Path> pathRepo, ILogger<GenerateLearningPlan> logger)
{
[Function("GenerateLearningPlan")]
public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req)
{
try
{
var principal = AuthHelper.ValidateToken(req);
if (!AuthHelper.HasScope(principal, "hoteach:default"))
{
return new UnauthorizedResult();
}
logger.LogInformation($"Authenticated user: {principal.Identity.Name}");
}
catch (Exception ex)
{
logger.LogWarning(ex.Message);
return new UnauthorizedResult();
}
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
if (string.IsNullOrEmpty(requestBody))
{
return new BadRequestObjectResult("Request body is empty.");
}
var data = JsonConvert.DeserializeObject<GeneratePathRequest>(requestBody);
if (data == null || string.IsNullOrEmpty(data.UserId))
return new BadRequestObjectResult("UserId is required.");
var preferences = await prefRepo.GetFirstOrDefaultAsync(p => p.UserId == data.UserId);
if (preferences is null)
return new NotFoundObjectResult("Preferences not found.");
var systemMessage = GeneratePrompt.SystemMessage();
var userMessage = GeneratePrompt.UserMessage(preferences);
var messages = new List<ChatMessage>
{
new SystemChatMessage(systemMessage),
new UserChatMessage(userMessage)
};
var response = await client.CompleteChatAsync(messages);
var responseText = response.Value.Content[0].Text;
await pathRepo.InsertAsync(new Path
{
Request = userMessage,
PathContent = responseText,
UserId = data.UserId
});
return new OkObjectResult(responseText);
}
}
}