using BotSharp.Abstraction.Agents.Models; using BotSharp.Abstraction.Functions.Models; using BotSharp.Abstraction.Routing; using BotSharp.Abstraction.Routing.Settings; namespace BotSharp.Core.Routing; public partial class RoutingService : IRoutingService { private readonly IServiceProvider _services; private readonly RoutingSettings _settings; private readonly IRouterInstance _routerInstance; private readonly ILogger _logger; private List _dialogs; public List Dialogs { get { if (_dialogs == null) { var conv = _services.GetRequiredService(); _dialogs = conv.GetDialogHistory(); } return _dialogs; } } public void ResetRecursiveCounter() { _currentRecursionDepth = 0; } public void RefreshDialogs() { _dialogs = null; } public RoutingService(IServiceProvider services, RoutingSettings settings, ILogger logger, IRouterInstance routerInstance) { _services = services; _settings = settings; _logger = logger; _routerInstance = routerInstance; } public async Task ExecuteOnce(Agent agent) { var message = Dialogs.Last().Content; var handlers = _services.GetServices(); var handler = handlers.FirstOrDefault(x => x.Name == "route_to_agent"); handler.SetDialogs(Dialogs); var result = await handler.Handle(this, new FunctionCallFromLlm { Function = "route_to_agent", Question = message, Reason = message, AgentName = agent.Name }); return result; } public async Task InstructLoop() { _routerInstance.Load(); var router = _routerInstance.Router; var result = new RoleDialogModel(AgentRole.Assistant, "Can you repeat your request again?") { CurrentAgentId = router.Id }; var inputMsg = Dialogs.Last(); var handlers = _services.GetServices(); int loopCount = 0; var stop = false; while (!stop && loopCount < 5) { loopCount++; var inst = await GetNextInstruction(); inst.MessageId = inputMsg.MessageId; inst.Question = inst.Question ?? inputMsg.Content; var handler = handlers.FirstOrDefault(x => x.Name == inst.Function); if (handler == null) { handler = handlers.FirstOrDefault(x => x.Name == "get_next_instruction"); continue; } handler.SetRouter(router); handler.SetDialogs(Dialogs); result = await handler.Handle(this, inst); result.MessageId = inputMsg.MessageId; stop = !_settings.EnableReasoning; } return result; } protected void SaveStateByArgs(JsonDocument args) { if (args == null) { return; } var stateService = _services.GetRequiredService(); if (args.RootElement is JsonElement root) { foreach (JsonProperty property in root.EnumerateObject()) { if (!string.IsNullOrEmpty(property.Value.ToString())) { stateService.SetState(property.Name, property.Value); } } } } }