BotSharp/src/Infrastructure/BotSharp.Core/Conversations/Services/ConversationService.SendMessage.cs

192 lines
6.6 KiB
C#
Raw Normal View History

2023-11-24 23:26:33 +00:00
using BotSharp.Abstraction.Messaging;
2023-10-27 22:55:28 +00:00
using BotSharp.Abstraction.Messaging.Models.RichContent;
using BotSharp.Abstraction.Routing.Settings;
2023-09-24 16:20:02 +00:00
using System.Drawing;
namespace BotSharp.Core.Conversations.Services;
public partial class ConversationService
{
2023-11-27 03:04:48 +00:00
public async Task<bool> SendMessage(string agentId,
RoleDialogModel message,
2024-03-16 14:43:00 +00:00
PostbackMessageModel? replyMessage,
Func<RoleDialogModel, Task> onMessageReceived,
Func<RoleDialogModel, Task> onFunctionExecuting,
Func<RoleDialogModel, Task> onFunctionExecuted)
{
2023-11-27 03:44:17 +00:00
var conversation = await GetConversationRecord(agentId);
2024-06-19 16:58:27 +00:00
// Save message files
var fileService = _services.GetRequiredService<IBotSharpFileService>();
fileService.SaveMessageFiles(_conversationId, message.MessageId, FileSourceType.User, message.Files);
message.Files?.Clear();
var agentService = _services.GetRequiredService<IAgentService>();
Agent agent = await agentService.LoadAgent(agentId);
var content = $"Received [{agent.Name}] {message.Role}: {message.Content}";
#if DEBUG
2023-10-28 20:59:26 +00:00
Console.WriteLine(content, Color.GreenYellow);
#else
_logger.LogInformation(content);
#endif
message.CurrentAgentId = agent.Id;
2024-02-29 03:07:12 +00:00
if (string.IsNullOrEmpty(message.SenderId))
{
message.SenderId = _user.Id;
}
2023-08-20 22:53:53 +00:00
2024-03-24 17:33:41 +00:00
var conv = _services.GetRequiredService<IConversationService>();
var dialogs = conv.GetDialogHistory();
var statistics = _services.GetRequiredService<ITokenStatistics>();
var hooks = _services.GetServices<IConversationHook>().ToList();
RoleDialogModel response = message;
bool stopCompletion = false;
2024-02-28 20:40:59 +00:00
// Enqueue receiving agent first in case it stop completion by OnMessageReceived
var routing = _services.GetRequiredService<IRoutingService>();
routing.Context.SetMessageId(_conversationId, message.MessageId);
routing.Context.Push(agent.Id);
2024-05-07 22:16:07 +00:00
// Save payload
2024-05-10 23:27:41 +00:00
if (replyMessage != null && !string.IsNullOrEmpty(replyMessage.Payload))
{
2024-05-10 23:27:41 +00:00
message.Payload = replyMessage.Payload;
}
2024-05-07 22:16:07 +00:00
// Before chat completion hook
foreach (var hook in hooks)
{
hook.SetAgent(agent)
2023-09-06 03:19:36 +00:00
.SetConversation(conversation);
if (replyMessage == null || string.IsNullOrEmpty(replyMessage.FunctionName))
2024-03-16 14:43:00 +00:00
{
await hook.OnMessageReceived(message);
}
else
{
await hook.OnPostbackMessageReceived(message, replyMessage);
}
2023-08-31 02:09:38 +00:00
// Interrupted by hook
if (message.StopCompletion)
2023-08-31 02:09:38 +00:00
{
stopCompletion = true;
2024-02-28 20:40:59 +00:00
routing.Context.Pop();
break;
2023-08-31 02:09:38 +00:00
}
}
if (!stopCompletion)
{
// Routing with reasoning
var settings = _services.GetRequiredService<RoutingSettings>();
2023-09-09 20:13:19 +00:00
2024-01-26 04:32:48 +00:00
response = agent.Type == AgentType.Routing ?
2024-04-30 21:25:58 +00:00
await routing.InstructLoop(message, dialogs, onFunctionExecuting) :
await routing.InstructDirect(agent, message);
2023-08-24 12:18:41 +00:00
routing.ResetRecursiveCounter();
}
await HandleAssistantMessage(response, onMessageReceived);
2023-09-24 21:32:58 +00:00
statistics.PrintStatistics();
2023-10-30 16:48:18 +00:00
return true;
}
2023-09-06 03:19:36 +00:00
2023-11-27 03:44:17 +00:00
private async Task<Conversation> GetConversationRecord(string agentId)
2023-09-06 03:19:36 +00:00
{
var converation = await GetConversation(_conversationId);
2023-11-27 03:04:48 +00:00
// Create conversation if this conversation does not exist
2023-09-06 03:19:36 +00:00
if (converation == null)
{
2023-11-27 03:44:17 +00:00
var state = _services.GetRequiredService<IConversationStateService>();
var channel = state.GetState("channel");
2023-09-06 03:19:36 +00:00
var sess = new Conversation
{
Id = _conversationId,
2023-11-27 03:04:48 +00:00
Channel = channel,
2023-09-06 03:19:36 +00:00
AgentId = agentId
};
converation = await NewConversation(sess);
}
return converation;
}
2024-02-28 20:40:59 +00:00
private async Task HandleAssistantMessage(RoleDialogModel response, Func<RoleDialogModel, Task> onResponseReceived)
{
var agentService = _services.GetRequiredService<IAgentService>();
2023-10-30 16:48:18 +00:00
var agent = await agentService.GetAgent(response.CurrentAgentId);
var agentName = agent.Name;
2023-09-23 21:33:05 +00:00
2023-12-12 15:06:39 +00:00
// Send message always in assistant role
response.Role = AgentRole.Assistant;
var text = $"Sending [{agentName}] {response.Role}: {response.Content}";
2023-09-24 16:20:02 +00:00
#if DEBUG
Console.WriteLine(text, Color.Yellow);
2023-09-24 16:20:02 +00:00
#else
_logger.LogInformation(text);
2023-09-24 16:20:02 +00:00
#endif
2023-09-23 21:33:05 +00:00
// Process rich content
if (response.RichContent != null &&
2023-11-24 23:26:33 +00:00
response.RichContent is RichContent<IRichMessage> template &&
string.IsNullOrEmpty(template.Message.Text))
{
2024-04-23 19:48:30 +00:00
template.Message.Text = response.SecondaryContent ?? response.Content;
}
2023-10-27 22:55:28 +00:00
// Only read content from RichContent for UI rendering. When richContent is null, create a basic text message for richContent.
var state = _services.GetRequiredService<IConversationStateService>();
2023-11-24 23:26:33 +00:00
response.RichContent = response.RichContent ?? new RichContent<IRichMessage>
2023-10-27 22:55:28 +00:00
{
Recipient = new Recipient { Id = state.GetConversationId() },
2024-04-23 19:48:30 +00:00
Message = new TextMessage(response.SecondaryContent ?? response.Content)
2023-10-27 22:55:28 +00:00
};
2024-04-06 23:33:49 +00:00
// Patch return function name
if (response.PostbackFunctionName != null)
{
response.FunctionName = response.PostbackFunctionName;
}
if (response.Instruction != null)
{
var conversation = _services.GetRequiredService<IConversationService>();
2024-03-22 19:06:20 +00:00
var updatedConversation = await conversation.UpdateConversationTitle(_conversationId, response.Instruction.NextActionReason);
2024-04-08 03:15:51 +00:00
// Emit conversation task completed hook
if (response.Instruction.TaskCompleted)
{
await HookEmitter.Emit<IConversationHook>(_services, async hook =>
await hook.OnTaskCompleted(response)
);
}
2024-03-22 19:06:20 +00:00
// Emit conversation ending hook
if (response.Instruction.ConversationEnd)
{
2024-04-08 03:15:51 +00:00
await HookEmitter.Emit<IConversationHook>(_services, async hook =>
await hook.OnConversationEnding(response)
);
2024-03-22 19:06:20 +00:00
}
}
2024-03-30 00:51:22 +00:00
2024-04-08 03:15:51 +00:00
await HookEmitter.Emit<IConversationHook>(_services, async hook =>
await hook.OnResponseGenerated(response)
);
2024-03-30 00:51:22 +00:00
await onResponseReceived(response);
// Add to dialog history
_storage.Append(_conversationId, response);
}
}