BotSharp/src/Infrastructure/BotSharp.Core/Routing/RoutingService.cs

188 lines
5.8 KiB
C#
Raw Normal View History

2023-09-19 12:17:50 +00:00
using BotSharp.Abstraction.Agents.Models;
2023-09-23 21:33:05 +00:00
using BotSharp.Abstraction.Functions.Models;
2023-09-19 12:17:50 +00:00
using BotSharp.Abstraction.Repositories;
using BotSharp.Abstraction.Routing;
using BotSharp.Abstraction.Routing.Models;
2023-09-20 10:31:50 +00:00
using BotSharp.Abstraction.Routing.Settings;
using BotSharp.Abstraction.Templating;
2023-09-19 12:17:50 +00:00
namespace BotSharp.Core.Routing;
public class RoutingService : IRoutingService
{
private readonly IServiceProvider _services;
2023-09-20 10:31:50 +00:00
private readonly RoutingSettings _settings;
2023-09-19 12:17:50 +00:00
private readonly ILogger _logger;
private List<RoleDialogModel> _dialogs;
public List<RoleDialogModel> Dialogs => _dialogs;
2023-09-20 10:31:50 +00:00
public RoutingService(IServiceProvider services,
RoutingSettings settings,
ILogger<RoutingService> logger)
2023-09-19 12:17:50 +00:00
{
_services = services;
2023-09-20 10:31:50 +00:00
_settings = settings;
2023-09-19 12:17:50 +00:00
_logger = logger;
}
2023-09-23 21:33:05 +00:00
public void SetDialogs(List<RoleDialogModel> dialogs)
{
_dialogs = dialogs;
}
public async Task<RoleDialogModel> ExecuteOnce(Agent agent)
{
var message = _dialogs.Last().Content;
var handlers = _services.GetServices<IRoutingHandler>();
var handler = handlers.FirstOrDefault(x => x.Name == "route_to_agent");
handler.SetDialogs(_dialogs);
var result = await handler.Handle(new FunctionCallFromLlm
{
Function = "route_to_agent",
Question = message,
Route = new RoutingArgs
{
Reason = message,
AgentName = agent.Name,
}
});
return result;
}
public async Task<RoleDialogModel> InstructLoop(Agent router)
2023-09-19 12:17:50 +00:00
{
2023-09-22 20:38:58 +00:00
var result = new RoleDialogModel(AgentRole.Assistant, "Can you repeat your request again?")
{
CurrentAgentId = router.Id
};
2023-09-19 12:17:50 +00:00
2023-09-23 21:33:05 +00:00
var message = _dialogs.Last().Content;
foreach (var dialog in _dialogs.TakeLast(20))
2023-09-19 12:17:50 +00:00
{
2023-09-21 13:08:27 +00:00
router.Instruction += $"\r\n{dialog.Role}: {dialog.Content}";
2023-09-19 12:17:50 +00:00
}
2023-09-22 20:38:58 +00:00
var handlers = _services.GetServices<IRoutingHandler>();
var handler = handlers.FirstOrDefault(x => x.Name == "get_next_instruction");
handler.SetRouter(router);
2023-09-23 21:33:05 +00:00
handler.SetDialogs(_dialogs);
2023-09-22 20:38:58 +00:00
2023-09-19 12:17:50 +00:00
int loopCount = 0;
2023-09-23 21:33:05 +00:00
var stop = false;
while (!stop && loopCount < 5)
2023-09-19 12:17:50 +00:00
{
loopCount++;
2023-09-23 21:33:05 +00:00
var inst = await handler.GetNextInstructionFromReasoner($"You are the Router, tell me the next step?");
2023-09-22 20:38:58 +00:00
inst.Question = inst.Question ?? message;
2023-09-19 12:17:50 +00:00
2023-09-22 20:38:58 +00:00
handler = handlers.FirstOrDefault(x => x.Name == inst.Function);
if (handler == null)
{
handler = handlers.FirstOrDefault(x => x.Name == "get_next_instruction");
2023-09-23 21:33:05 +00:00
router.Instruction += $"\r\n{AgentRole.System}: the function must be one of {string.Join(",", GetHandlers().Select(x => x.Name))}.";
2023-09-22 20:38:58 +00:00
continue;
}
handler.SetRouter(router);
2023-09-23 21:33:05 +00:00
handler.SetDialogs(_dialogs);
2023-09-19 12:17:50 +00:00
2023-09-22 20:38:58 +00:00
result = await handler.Handle(inst);
2023-09-19 12:17:50 +00:00
2023-09-22 20:38:58 +00:00
message = result.Content.Replace("\r\n", " ");
router.Instruction += $"\r\n{result.Role}: {message}";
2023-09-19 12:17:50 +00:00
2023-09-23 21:33:05 +00:00
stop = !_settings.EnableReasoning;
2023-09-19 12:17:50 +00:00
}
2023-09-22 20:38:58 +00:00
return result;
2023-09-19 12:17:50 +00:00
}
2023-09-20 10:31:50 +00:00
public Agent LoadRouter()
{
var db = _services.GetRequiredService<IBotSharpRepository>();
var router = new Agent()
{
Id = _settings.RouterId,
2023-09-21 16:40:54 +00:00
Name = _settings.RouterName,
Description = _settings.Description
2023-09-20 10:31:50 +00:00
};
var agents = db.Agents.Where(x => !x.Disabled && x.AllowRouting).ToArray();
2023-09-24 16:20:02 +00:00
// Assemble prompt
var prompt = @"You're a Router with reasoning. Follow these steps to handle user's request:
1. Read the CONVERSATION context.
2. Select a appropriate function from FUNCTIONS.
3. Determine which agent from AGENTS is suitable for the current task.";
// Append function
prompt += "\r\n";
prompt += "\r\nFUNCTIONS";
GetHandlers().Select((handler, i) =>
{
prompt += "\r\n";
prompt += $"\r\n{i + 1}. {handler.Name}";
prompt += $"\r\n{handler.Description}";
// Append parameters
if (handler.Parameters.Any())
{
prompt += "\r\nParameters:";
handler.Parameters.Select((p, i) =>
{
prompt += $"\r\n{i + 1}. {p.Name}: {p.Description}";
return p;
}).ToList();
}
return handler;
}).ToList();
prompt += "\r\n";
prompt += "\r\nAGENTS";
agents.Select(x => new RoutingItem
2023-09-20 10:31:50 +00:00
{
AgentId = x.Id,
Description = x.Description,
Name = x.Name,
RequiredFields = x.RoutingRules.Where(x => x.Required)
.Select(x => x.Field)
.ToArray()
2023-09-24 16:20:02 +00:00
}).Select((agent, i) =>
{
prompt += "\r\n";
prompt += $"\r\n{i + 1}. {agent.Name}";
prompt += $"\r\n{agent.Description}";
2023-09-20 10:31:50 +00:00
2023-09-24 16:20:02 +00:00
// Append parameters
if (agent.RequiredFields.Any())
{
prompt += $"\r\nRequired: {string.Join(',', agent.RequiredFields)}.";
}
return agent;
}).ToList();
2023-09-20 10:31:50 +00:00
2023-09-24 16:20:02 +00:00
prompt += "\r\n";
prompt += "\r\nCONVERSATION";
router.Instruction = prompt;
2023-09-20 10:31:50 +00:00
return router;
}
2023-09-22 20:38:58 +00:00
private List<RoutingHandlerDef> GetHandlers()
{
return _services.GetServices<IRoutingHandler>()
.Where(x => x.IsReasoning == _settings.EnableReasoning)
.Where(x => !string.IsNullOrEmpty(x.Description))
.Select(x => new RoutingHandlerDef
{
Name = x.Name,
Description = x.Description,
Parameters = x.Parameters
}).ToList();
}
2023-09-19 12:17:50 +00:00
}