using BotSharp.Abstraction.Functions;
using BotSharp.Abstraction.Routing.Models;
namespace BotSharp.Core.Functions;
///
/// Router calls this function to set the Active Agent according to the context
///
public class RouteToAgentFn : IFunctionCallback
{
public string Name => "route_to_agent";
private readonly IServiceProvider _services;
public RouteToAgentFn(IServiceProvider services)
{
_services = services;
}
public async Task Execute(RoleDialogModel message)
{
var args = JsonSerializer.Deserialize(message.FunctionArgs);
if (string.IsNullOrEmpty(args.AgentName))
{
message.ExecutionResult = $"missing agent name";
}
else
{
var missingfield = HasMissingRequiredField(message, out var agentId);
if (missingfield && message.CurrentAgentId != agentId)
{
message.CurrentAgentId = agentId;
}
else
{
message.CurrentAgentId = agentId;
message.ExecutionResult = $"Routed to {args.AgentName}";
}
}
return true;
}
///
/// If the target agent needs some required fields but the
///
///
private bool HasMissingRequiredField(RoleDialogModel message, out string agentId)
{
var args = JsonSerializer.Deserialize(message.FunctionArgs);
var router = _services.GetRequiredService();
var routingRule = router.GetRecordByName(args.AgentName);
if (routingRule == null)
{
agentId = message.CurrentAgentId;
message.ExecutionResult = $"Can't find agent {args.AgentName}";
return true;
}
agentId = routingRule.AgentId;
// Check required fields
var root = JsonSerializer.Deserialize(message.FunctionArgs);
bool hasMissingField = false;
string missingFieldName = "";
foreach (var field in routingRule.RequiredFields)
{
if (!root.EnumerateObject().Any(x => x.Name == field))
{
message.ExecutionResult = $"missing {field}.";
hasMissingField = true;
missingFieldName = field;
break;
}
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;
missingFieldName = field;
break;
}
}
// Check if states contains the field according conversation context.
var states = _services.GetRequiredService();
if (!string.IsNullOrEmpty(states.GetState(missingFieldName)))
{
var value = states.GetState(missingFieldName);
message.FunctionArgs = message.FunctionArgs.Substring(0, message.FunctionArgs.Length - 1) + $", \"{missingFieldName}\": \"{value}\"" + "}";
hasMissingField = false;
missingFieldName = "";
}
if (hasMissingField && !string.IsNullOrEmpty(routingRule.RedirectTo))
{
agentId = routingRule.RedirectTo;
}
return hasMissingField;
}
}