-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateChatMessageCommand.cs
More file actions
120 lines (101 loc) · 4.55 KB
/
CreateChatMessageCommand.cs
File metadata and controls
120 lines (101 loc) · 4.55 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
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
using Goodtocode.AgentFramework.Core.Application.Abstractions;
using Goodtocode.AgentFramework.Core.Application.Common.Exceptions;
using Goodtocode.AgentFramework.Core.Domain.Auth;
using Goodtocode.AgentFramework.Core.Domain.ChatCompletion;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
namespace Goodtocode.AgentFramework.Core.Application.ChatCompletion;
public class CreateChatMessageCommand : IRequest<ChatMessageDto>, IUserInfoRequest
{
public Guid Id { get; set; }
public Guid ChatSessionId { get; set; }
public string? Message { get; set; }
public IUserEntity? UserInfo { get; set; }
}
public class CreateChatMessageCommandHandler(AIAgent agent, IAgentFrameworkContext context) : IRequestHandler<CreateChatMessageCommand, ChatMessageDto>
{
private readonly AIAgent _agent = agent;
private readonly IAgentFrameworkContext _context = context;
public async Task<ChatMessageDto> Handle(CreateChatMessageCommand request, CancellationToken cancellationToken)
{
GuardAgainstSessionNotFound(_context.ChatSessions, request!.ChatSessionId);
GuardAgainstEmptyMessage(request?.Message);
GuardAgainstIdExists(_context.ChatMessages, request!.Id);
GuardAgainstEmptyUser(request?.UserInfo);
GuardAgainstUnauthorizedUser(_context.ChatSessions, request!.UserInfo!);
var chatSession = _context.ChatSessions.Find(request.ChatSessionId);
var chatHistory = new List<ChatMessage>();
foreach (ChatMessageEntity message in chatSession!.Messages)
{
chatHistory.Add(new ChatMessage(
message.Role == ChatMessageRole.user ? ChatRole.User : ChatRole.Assistant,
message.Content));
}
chatHistory.Add(new ChatMessage(ChatRole.User, request!.Message!));
var agentResponse = await _agent.RunAsync(chatHistory, cancellationToken: cancellationToken);
var response = agentResponse.Messages.LastOrDefault();
GuardAgainstNullAgentResponse(response);
var chatMessage = ChatMessageEntity.Create(
request.Id,
chatSession.Id,
ChatMessageRole.user,
request.Message!
);
chatSession.Messages.Add(chatMessage);
_context.ChatMessages.Add(chatMessage);
var agentReply = (response?.Contents?.LastOrDefault()?.ToString()) ?? string.Empty;
var chatMessageResponse = ChatMessageEntity.Create(
Guid.NewGuid(),
chatSession.Id,
ChatMessageRole.assistant,
agentReply
);
chatSession.Messages.Add(chatMessageResponse);
_context.ChatMessages.Add(chatMessageResponse);
await _context.SaveChangesAsync(cancellationToken);
return ChatMessageDto.CreateFrom(chatMessage);
}
private static void GuardAgainstSessionNotFound(DbSet<ChatSessionEntity> dbSet, Guid sessionId)
{
if (sessionId != Guid.Empty && !dbSet.Any(x => x.Id == sessionId))
throw new CustomValidationException(
[
new("ChatSessionId", "Chat Session does not exist")
]);
}
private static void GuardAgainstEmptyMessage(string? message)
{
if (string.IsNullOrWhiteSpace(message))
throw new CustomValidationException(
[
new("Message", "A message is required as a prompt to get an AI response")
]);
}
private static void GuardAgainstIdExists(DbSet<ChatMessageEntity> dbSet, Guid id)
{
if (dbSet.Any(x => x.Id == id))
throw new CustomConflictException("Id already exists");
}
private static void GuardAgainstEmptyUser(IUserEntity? userInfo)
{
if (userInfo == null || userInfo.OwnerId == Guid.Empty || userInfo.TenantId == Guid.Empty)
throw new CustomValidationException(
[
new("UserInfo", "User information is required to create a chat message")
]);
}
private static void GuardAgainstUnauthorizedUser(DbSet<ChatSessionEntity> dbSet, IUserEntity userInfo)
{
bool isAuthorized = dbSet.Any(x => x.Actor != null && x.Actor.OwnerId == userInfo.OwnerId);
if (!isAuthorized)
throw new CustomValidationException(
[
new("UserInfo", "User is not authorized to create a chat message in this session")
]);
}
private static void GuardAgainstNullAgentResponse(ChatMessage? response)
{
if (response == null)
throw new CustomValidationException([new("ChatMessage","Agent response cannot be null")]);
}
}