BotSharp/src/Plugins/BotSharp.Plugin.ChatHub/Hooks/ChatHubConversationHook.cs

303 lines
11 KiB
C#
Raw Normal View History

2024-11-04 22:44:41 +00:00
using BotSharp.Abstraction.SideCar;
2023-11-22 16:27:55 +00:00
using Microsoft.AspNetCore.SignalR;
namespace BotSharp.Plugin.ChatHub.Hooks;
public class ChatHubConversationHook : ConversationHookBase
{
private readonly IServiceProvider _services;
private readonly IHubContext<SignalRHub> _chatHub;
2025-02-27 22:19:43 +00:00
private readonly ILogger<ChatHubConversationHook> _logger;
2023-11-28 03:19:07 +00:00
private readonly IUserIdentity _user;
2024-07-23 22:44:39 +00:00
private readonly BotSharpOptions _options;
2025-02-13 20:52:46 +00:00
private readonly ChatHubSettings _settings;
2024-07-23 22:44:39 +00:00
2025-02-13 20:52:46 +00:00
#region Events
2024-07-23 22:44:39 +00:00
private const string INIT_CLIENT_CONVERSATION = "OnConversationInitFromClient";
private const string RECEIVE_CLIENT_MESSAGE = "OnMessageReceivedFromClient";
private const string RECEIVE_ASSISTANT_MESSAGE = "OnMessageReceivedFromAssistant";
private const string GENERATE_SENDER_ACTION = "OnSenderActionGenerated";
private const string DELETE_MESSAGE = "OnMessageDeleted";
2024-10-07 21:35:39 +00:00
private const string GENERATE_NOTIFICATION = "OnNotificationGenerated";
2024-07-23 22:44:39 +00:00
#endregion
public ChatHubConversationHook(
IServiceProvider services,
2023-11-28 03:19:07 +00:00
IHubContext<SignalRHub> chatHub,
2025-02-27 22:19:43 +00:00
ILogger<ChatHubConversationHook> logger,
2024-03-18 19:36:41 +00:00
BotSharpOptions options,
2025-02-13 20:52:46 +00:00
ChatHubSettings settings,
2023-11-28 03:19:07 +00:00
IUserIdentity user)
2023-11-22 16:27:55 +00:00
{
_services = services;
_chatHub = chatHub;
2025-02-27 22:19:43 +00:00
_logger = logger;
2023-11-28 03:19:07 +00:00
_user = user;
2024-03-18 19:36:41 +00:00
_options = options;
2025-02-13 20:52:46 +00:00
_settings = settings;
2024-12-12 01:16:59 +00:00
Priority = -1; // Make sure this hook is the top one.
2023-11-22 16:27:55 +00:00
}
public override async Task OnConversationInitialized(Conversation conversation)
{
2024-10-29 19:59:46 +00:00
if (!AllowSendingMessage()) return;
2023-11-22 16:27:55 +00:00
var userService = _services.GetRequiredService<IUserService>();
var conv = ConversationViewModel.FromSession(conversation);
var user = await userService.GetUser(conv.User.Id);
conv.User = UserViewModel.FromUser(user);
2025-02-13 20:52:46 +00:00
await InitClientConversation(conv.Id, conv);
2023-11-22 16:27:55 +00:00
await base.OnConversationInitialized(conversation);
}
public override async Task OnMessageReceived(RoleDialogModel message)
{
2024-10-29 19:59:46 +00:00
if (!AllowSendingMessage()) return;
2023-11-22 16:27:55 +00:00
var conv = _services.GetRequiredService<IConversationService>();
var userService = _services.GetRequiredService<IUserService>();
var sender = await userService.GetMyProfile();
// Update console conversation UI for CSR
2024-07-23 22:44:39 +00:00
var model = new ChatResponseModel()
2023-11-22 16:27:55 +00:00
{
ConversationId = conv.ConversationId,
MessageId = message.MessageId,
2024-10-10 17:55:44 +00:00
Payload = message.Payload,
2024-04-23 21:27:09 +00:00
Text = !string.IsNullOrEmpty(message.SecondaryContent) ? message.SecondaryContent : message.Content,
2023-11-22 16:27:55 +00:00
Sender = UserViewModel.FromUser(sender)
2024-07-23 22:44:39 +00:00
};
2025-02-13 20:52:46 +00:00
await ReceiveClientMessage(conv.ConversationId, model);
2023-11-22 16:27:55 +00:00
2024-02-16 21:58:39 +00:00
// Send typing-on to client
2024-07-23 22:44:39 +00:00
var action = new ConversationSenderActionModel
2024-02-16 21:58:39 +00:00
{
ConversationId = conv.ConversationId,
SenderAction = SenderActionEnum.TypingOn
2024-07-23 22:44:39 +00:00
};
2025-02-13 20:52:46 +00:00
await GenerateSenderAction(conv.ConversationId, action);
2023-11-22 16:27:55 +00:00
await base.OnMessageReceived(message);
}
2024-05-01 15:45:12 +00:00
public override async Task OnFunctionExecuting(RoleDialogModel message)
{
var conv = _services.GetRequiredService<IConversationService>();
2024-07-23 22:44:39 +00:00
var action = new ConversationSenderActionModel
2024-05-01 15:45:12 +00:00
{
ConversationId = conv.ConversationId,
SenderAction = SenderActionEnum.TypingOn,
Indication = message.Indication
2024-07-23 22:44:39 +00:00
};
2025-02-13 20:52:46 +00:00
await GenerateSenderAction(conv.ConversationId, action);
2024-05-01 15:45:12 +00:00
await base.OnFunctionExecuting(message);
}
2024-03-18 19:36:41 +00:00
public override async Task OnPostbackMessageReceived(RoleDialogModel message, PostbackMessageModel replyMsg)
{
await this.OnMessageReceived(message);
}
2023-11-22 16:27:55 +00:00
public override async Task OnResponseGenerated(RoleDialogModel message)
{
2024-10-29 19:59:46 +00:00
if (!AllowSendingMessage()) return;
2023-11-22 16:27:55 +00:00
var conv = _services.GetRequiredService<IConversationService>();
2023-12-20 02:28:56 +00:00
var json = JsonSerializer.Serialize(new ChatResponseModel()
2023-11-22 16:27:55 +00:00
{
ConversationId = conv.ConversationId,
MessageId = message.MessageId,
2024-04-23 21:27:09 +00:00
Text = !string.IsNullOrEmpty(message.SecondaryContent) ? message.SecondaryContent : message.Content,
2024-02-28 16:16:46 +00:00
Function = message.FunctionName,
2024-04-23 21:27:09 +00:00
RichContent = message.SecondaryRichContent ?? message.RichContent,
2024-02-12 21:49:18 +00:00
Data = message.Data,
2023-11-22 16:27:55 +00:00
Sender = new UserViewModel()
{
FirstName = "AI",
LastName = "Assistant",
Role = AgentRole.Assistant
}
2024-03-18 19:36:41 +00:00
}, _options.JsonSerializerOptions);
2023-11-22 16:27:55 +00:00
2024-02-16 21:58:39 +00:00
// Send typing-off to client
2024-07-23 22:44:39 +00:00
var action = new ConversationSenderActionModel
2024-01-26 21:47:06 +00:00
{
2024-02-16 21:58:39 +00:00
ConversationId = conv.ConversationId,
SenderAction = SenderActionEnum.TypingOff
2024-07-23 22:44:39 +00:00
};
2024-02-15 20:43:36 +00:00
2025-02-13 20:52:46 +00:00
await GenerateSenderAction(conv.ConversationId, action);
await ReceiveAssistantMessage(conv.ConversationId, json);
2024-02-16 21:58:39 +00:00
await base.OnResponseGenerated(message);
2024-01-26 21:47:06 +00:00
}
2024-03-11 20:32:13 +00:00
2024-10-07 21:35:39 +00:00
public override async Task OnNotificationGenerated(RoleDialogModel message)
{
var conv = _services.GetRequiredService<IConversationService>();
var json = JsonSerializer.Serialize(new ChatResponseModel()
{
ConversationId = conv.ConversationId,
MessageId = message.MessageId,
Text = !string.IsNullOrEmpty(message.SecondaryContent) ? message.SecondaryContent : message.Content,
Function = message.FunctionName,
RichContent = message.SecondaryRichContent ?? message.RichContent,
Data = message.Data,
Sender = new UserViewModel()
{
FirstName = "AI",
LastName = "Assistant",
Role = AgentRole.Assistant
}
}, _options.JsonSerializerOptions);
2025-02-13 20:52:46 +00:00
await GenerateNotification(conv.ConversationId, json);
2024-10-07 21:35:39 +00:00
await base.OnNotificationGenerated(message);
}
2024-03-11 20:32:13 +00:00
public override async Task OnMessageDeleted(string conversationId, string messageId)
{
2024-07-23 22:44:39 +00:00
var model = new ChatResponseModel
2024-03-11 20:32:13 +00:00
{
ConversationId = conversationId,
MessageId = messageId
2024-07-23 22:44:39 +00:00
};
2025-02-13 20:52:46 +00:00
await DeleteMessage(conversationId, model);
2024-03-11 20:32:13 +00:00
await base.OnMessageDeleted(conversationId, messageId);
}
2024-07-23 22:44:39 +00:00
#region Private methods
2024-10-29 19:59:46 +00:00
private bool AllowSendingMessage()
{
2024-11-04 22:51:02 +00:00
var sidecar = _services.GetService<IConversationSideCar>();
return sidecar == null || !sidecar.IsEnabled();
2024-10-29 19:59:46 +00:00
}
2025-02-13 20:52:46 +00:00
private async Task InitClientConversation(string conversationId, ConversationViewModel conversation)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(INIT_CLIENT_CONVERSATION, conversation);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(INIT_CLIENT_CONVERSATION, conversation);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to init client conversation in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
}
private async Task ReceiveClientMessage(string conversationId, ChatResponseModel model)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(RECEIVE_CLIENT_MESSAGE, model);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(RECEIVE_CLIENT_MESSAGE, model);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to receive assistant message in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
}
private async Task ReceiveAssistantMessage(string conversationId, string? json)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(RECEIVE_ASSISTANT_MESSAGE, json);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(RECEIVE_ASSISTANT_MESSAGE, json);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to receive assistant message in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
2025-02-13 20:52:46 +00:00
}
private async Task GenerateSenderAction(string conversationId, ConversationSenderActionModel action)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(GENERATE_SENDER_ACTION, action);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(GENERATE_SENDER_ACTION, action);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to generate sender action in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
}
private async Task DeleteMessage(string conversationId, ChatResponseModel model)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(DELETE_MESSAGE, model);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(DELETE_MESSAGE, model);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to delete message in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
}
private async Task GenerateNotification(string conversationId, string? json)
{
2025-02-27 22:19:43 +00:00
try
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
if (_settings.EventDispatchBy == EventDispatchType.Group)
{
await _chatHub.Clients.Group(conversationId).SendAsync(GENERATE_NOTIFICATION, json);
}
else
{
await _chatHub.Clients.User(_user.Id).SendAsync(GENERATE_NOTIFICATION, json);
}
2025-02-13 20:52:46 +00:00
}
2025-02-27 22:19:43 +00:00
catch (Exception ex)
2025-02-13 20:52:46 +00:00
{
2025-02-27 22:19:43 +00:00
_logger.LogWarning($"Failed to generate notification in {nameof(ChatHubConversationHook)} (conversation id: {conversationId})" +
$"\r\n{ex.Message}\r\n{ex.InnerException}");
2025-02-13 20:52:46 +00:00
}
}
2024-07-23 22:44:39 +00:00
#endregion
2023-11-22 16:27:55 +00:00
}