using BotSharp.Abstraction.Agents.Models; using BotSharp.Abstraction.Routing; using BotSharp.Abstraction.Routing.Settings; using System.Drawing; namespace BotSharp.Core.Conversations.Services; public partial class ConversationService { public async Task SendMessage(string agentId, RoleDialogModel incoming, Func onMessageReceived, Func onFunctionExecuting, Func onFunctionExecuted) { var conversation = await GetConversationRecord(agentId); var agentService = _services.GetRequiredService(); Agent agent = await agentService.LoadAgent(agentId); _logger.LogInformation($"[{agent.Name}] {incoming.Role}: {incoming.Content}"); incoming.CurrentAgentId = agent.Id; _storage.Append(_conversationId, incoming); var hooks = _services.GetServices().ToList(); // Before chat completion hook foreach (var hook in hooks) { hook.SetAgent(agent) .SetConversation(conversation); await hook.OnMessageReceived(incoming); // Interrupted by hook if (incoming.StopCompletion) { await onMessageReceived(incoming); _storage.Append(_conversationId, incoming); return true; } } // Routing with reasoning var routing = _services.GetRequiredService(); var settings = _services.GetRequiredService(); var response = agentId == settings.RouterId ? await routing.InstructLoop() : await routing.ExecuteOnce(agent); await HandleAssistantMessage(response, onMessageReceived); var statistics = _services.GetRequiredService(); statistics.PrintStatistics(); return true; } private async Task GetConversationRecord(string agentId) { var converation = await GetConversation(_conversationId); // Create conversation if this conversation not exists if (converation == null) { var sess = new Conversation { Id = _conversationId, AgentId = agentId }; converation = await NewConversation(sess); } return converation; } private async Task HandleAssistantMessage(RoleDialogModel message, Func onMessageReceived) { var routingSetting = _services.GetRequiredService(); var agentName = routingSetting.RouterId == message.CurrentAgentId ? "Router" : (await _services.GetRequiredService().GetAgent(message.CurrentAgentId)).Name; var text = message.Role == AgentRole.Function ? $"[{agentName}] {message.FunctionName}: {message.Content}" : $"[{agentName}] {message.Role}: {message.Content}"; #if DEBUG Console.WriteLine(text, Color.Pink); #else _logger.LogInformation(text); #endif var hooks = _services.GetServices().ToList(); foreach (var hook in hooks) { await hook.OnResponseGenerated(message); } await onMessageReceived(message); // Add to dialog history _storage.Append(_conversationId, message); } }