BotSharp/src/Infrastructure/BotSharp.Core/Functions/RouteToAgentFn.cs

97 lines
3.1 KiB
C#
Raw Normal View History

using BotSharp.Abstraction.Agents.Models;
using BotSharp.Abstraction.Conversations.Models;
using BotSharp.Abstraction.Functions;
using System.IO;
namespace BotSharp.Core.Functions;
2023-08-23 03:08:14 +00:00
/// <summary>
/// Router calls this function to set the Active Agent according to the context
/// </summary>
public class RouteToAgentFn : IFunctionCallback
{
public string Name => "route_to_agent";
private readonly IServiceProvider _services;
public RouteToAgentFn(IServiceProvider services)
{
_services = services;
}
public async Task<bool> Execute(RoleDialogModel message)
{
var args = JsonSerializer.Deserialize<RoutingArgs>(message.FunctionArgs);
if (string.IsNullOrEmpty(args.AgentName))
{
2023-08-23 03:08:14 +00:00
message.ExecutionResult = $"missing agent name";
}
else
{
2023-08-23 18:32:13 +00:00
var missingfield = HasMissingRequiredField(message, out var agentId);
if (missingfield && message.CurrentAgentId != agentId)
{
message.CurrentAgentId = agentId;
}
else
{
2023-08-23 03:08:14 +00:00
message.CurrentAgentId = agentId;
message.ExecutionResult = $"Routed to {args.AgentName}";
}
2023-08-23 03:08:14 +00:00
}
return true;
}
/// <summary>
/// If the target agent needs some required fields but the
/// </summary>
/// <returns></returns>
private bool HasMissingRequiredField(RoleDialogModel message, out string agentId)
{
var args = JsonSerializer.Deserialize<RoutingArgs>(message.FunctionArgs);
var router = _services.GetRequiredService<IAgentRouting>();
var records = router.GetRoutingRecords();
var routingRule = records.FirstOrDefault(x => x.Name.ToLower() == args.AgentName.ToLower());
2023-08-23 03:08:14 +00:00
2023-08-23 18:32:13 +00:00
if (routingRule == null)
2023-08-23 03:08:14 +00:00
{
agentId = message.CurrentAgentId;
message.ExecutionResult = $"Can't find agent {args.AgentName}";
return true;
}
2023-08-23 18:32:13 +00:00
agentId = routingRule.AgentId;
2023-08-23 03:08:14 +00:00
// Check required fields
var jo = JsonSerializer.Deserialize<object>(message.FunctionArgs);
bool hasMissingField = false;
2023-08-23 18:32:13 +00:00
foreach (var field in routingRule.RequiredFields)
2023-08-23 03:08:14 +00:00
{
if (jo is JsonElement root)
{
if (!root.EnumerateObject().Any(x => x.Name == field))
{
2023-08-23 03:08:14 +00:00
message.ExecutionResult = $"missing {field}.";
hasMissingField = true;
break;
}
2023-08-23 18:32:13 +00:00
else if (root.EnumerateObject().Any(x => x.Name == field) &&
string.IsNullOrEmpty(root.EnumerateObject().FirstOrDefault(x => x.Name == field).Value.ToString()))
{
message.ExecutionResult = $"missing {field}.";
hasMissingField = true;
break;
}
}
}
2023-08-23 18:32:13 +00:00
if (hasMissingField && !string.IsNullOrEmpty(routingRule.RedirectTo))
{
agentId = routingRule.RedirectTo;
}
2023-08-23 03:08:14 +00:00
return hasMissingField;
}
}