BotSharp/src/Infrastructure/BotSharp.Core/Routing/Handlers/RouteToAgentRoutingHandler.cs

87 lines
2.8 KiB
C#
Raw Normal View History

2023-09-22 20:38:58 +00:00
using BotSharp.Abstraction.Routing.Settings;
namespace BotSharp.Core.Routing.Handlers;
public class RouteToAgentRoutingHandler : RoutingHandlerBase, IRoutingHandler
{
public string Name => "route_to_agent";
public string Description => "Route request to appropriate agent.";
2023-10-28 20:59:26 +00:00
public List<ParameterPropertyDef> Parameters => new List<ParameterPropertyDef>
2023-09-22 20:38:58 +00:00
{
new ParameterPropertyDef("next_action_reason", "the reason why route to this agent")
2024-02-28 03:15:21 +00:00
{
Required = true
},
new ParameterPropertyDef("next_action_agent", "agent for next action based on user latest response")
{
Required = true
},
new ParameterPropertyDef("user_goal_description", "user original goal")
{
Required = true
},
2024-02-28 03:15:21 +00:00
new ParameterPropertyDef("user_goal_agent", "agent who can achieve user original goal")
{
Required = true
},
2023-10-28 20:59:26 +00:00
new ParameterPropertyDef("args", "useful parameters of next action agent, format: { }")
{
Type = "object"
}
2023-09-22 20:38:58 +00:00
};
public RouteToAgentRoutingHandler(IServiceProvider services, ILogger<RouteToAgentRoutingHandler> logger, RoutingSettings settings)
: base(services, logger, settings)
{
}
public async Task<bool> Handle(IRoutingService routing, FunctionCallFromLlm inst, RoleDialogModel message)
2023-09-22 20:38:58 +00:00
{
message.FunctionArgs = JsonSerializer.Serialize(inst);
2024-03-01 05:44:57 +00:00
var ret = await routing.InvokeFunction(message.FunctionName, message);
2023-09-22 20:38:58 +00:00
var states = _services.GetRequiredService<IConversationStateService>();
var goalAgent = states.GetState("user_goal_agent");
if (!string.IsNullOrEmpty(goalAgent))
{
inst.OriginalAgent = goalAgent;
}
await HookEmitter.Emit<IRoutingHook>(_services, async hook =>
await hook.OnRoutingInstructionRevised(inst, message)
);
2024-03-01 05:44:57 +00:00
var agentId = routing.Context.GetCurrentAgentId();
2023-11-14 20:56:51 +00:00
// Update next action agent's name
var agentService = _services.GetRequiredService<IAgentService>();
var agent = await agentService.LoadAgent(agentId);
inst.AgentName = agent.Name;
if (inst.ExecutingDirectly)
2023-11-08 22:27:42 +00:00
{
message.Content = inst.Question;
}
2024-01-13 21:17:40 +00:00
if (agent.Disabled)
{
var content = $"This agent ({agent.Name}) is disabled, please install the corresponding plugin ({agent.Plugin.Name}) to activate this agent.";
message = RoleDialogModel.From(message,
role: AgentRole.Assistant,
content: content);
_dialogs.Add(message);
}
else
{
ret = await routing.InvokeAgent(agentId, _dialogs);
}
2023-10-30 16:48:18 +00:00
var response = _dialogs.Last();
inst.Response = response.Content;
2023-10-27 15:18:48 +00:00
return true;
2023-09-22 20:38:58 +00:00
}
}