BotSharp/src/Infrastructure/BotSharp.Core/Routing/Hooks/RoutingAgentHook.cs

77 lines
2.7 KiB
C#
Raw Normal View History

2023-09-28 03:31:58 +00:00
using BotSharp.Abstraction.Functions.Models;
2023-10-12 11:30:13 +00:00
using BotSharp.Abstraction.Routing;
using BotSharp.Abstraction.Routing.Enums;
2023-10-24 21:38:34 +00:00
using BotSharp.Abstraction.Routing.Settings;
using System.Diagnostics.Metrics;
2023-09-28 03:31:58 +00:00
namespace BotSharp.Core.Routing.Hooks;
public class RoutingAgentHook : AgentHookBase
{
2023-10-24 21:38:34 +00:00
private readonly RoutingSettings _routingSetting;
2024-01-13 21:17:40 +00:00
public override string SelfId => string.Empty;
2023-10-24 21:38:34 +00:00
public RoutingAgentHook(IServiceProvider services, AgentSettings settings, RoutingSettings routingSetting)
2023-09-28 03:31:58 +00:00
: base(services, settings)
{
2023-10-24 21:38:34 +00:00
_routingSetting = routingSetting;
2023-09-28 03:31:58 +00:00
}
2023-10-12 11:30:13 +00:00
public override bool OnInstructionLoaded(string template, Dictionary<string, object> dict)
{
2024-01-26 04:32:48 +00:00
if (_agent.Type != AgentType.Routing)
2024-01-13 21:17:40 +00:00
{
return base.OnInstructionLoaded(template, dict);
}
2023-10-12 11:30:13 +00:00
dict["router"] = _agent;
2023-11-01 01:48:12 +00:00
var routing = _services.GetRequiredService<IRoutingService>();
var agents = routing.GetRoutableAgents(_agent.Profiles);
dict["routing_agents"] = agents;
2023-11-01 01:48:12 +00:00
dict["routing_handlers"] = routing.GetHandlers();
2023-10-12 11:30:13 +00:00
return base.OnInstructionLoaded(template, dict);
}
public override bool OnFunctionsLoaded(List<FunctionDef> functions)
2023-09-28 03:31:58 +00:00
{
if (_agent.Type == AgentType.Task)
2023-09-28 03:31:58 +00:00
{
// check if enabled the routing rule
var routing = _services.GetRequiredService<IRoutingService>();
var rule = routing.GetRulesByAgentId(_agent.Id)
.FirstOrDefault(x => x.Type == RuleType.Fallback);
if (rule != null)
{
var agentService = _services.GetRequiredService<IAgentService>();
var redirectAgent = agentService.GetAgent(rule.RedirectTo).Result;
var json = JsonSerializer.Serialize(new
{
user_goal_agent = new
{
type = "string",
description = $"the fixed value is: {_agent.Name}"
},
next_action_agent = new
{
type = "string",
description = $"the fixed value is: {redirectAgent.Name}"
}
});
functions.Add(new FunctionDef
{
Name = "fallback_to_router",
Description = $"If the user's request is beyond your capabilities, you can call this function to handle by other agent ({redirectAgent.Name}).",
Parameters =
{
Properties = JsonSerializer.Deserialize<JsonDocument>(json)
}
});
}
}
return base.OnFunctionsLoaded(functions);
2023-09-28 03:31:58 +00:00
}
}