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

118 lines
2.9 KiB
C#
Raw Normal View History

2024-01-26 04:32:48 +00:00
using BotSharp.Abstraction.Repositories.Filters;
using BotSharp.Abstraction.Routing.Settings;
2024-02-28 16:21:14 +00:00
namespace BotSharp.Core.Routing;
2024-02-28 16:21:14 +00:00
public class RoutingContext : IRoutingContext
{
2024-01-26 04:32:48 +00:00
private readonly IServiceProvider _services;
private readonly RoutingSettings _setting;
2024-01-26 04:32:48 +00:00
private string[] _routerAgentIds;
public RoutingContext(IServiceProvider services, RoutingSettings setting)
{
2024-01-26 04:32:48 +00:00
_services = services;
_setting = setting;
}
private Stack<string> _stack { get; set; }
= new Stack<string>();
/// <summary>
/// Intent name
/// </summary>
public string IntentName { get; set; }
2023-10-27 01:23:06 +00:00
/// <summary>
2024-01-13 21:17:40 +00:00
/// Agent that can handle user original goal.
2023-10-27 01:23:06 +00:00
/// </summary>
public string OriginAgentId
2024-01-26 04:32:48 +00:00
{
get
{
if (_routerAgentIds == null)
{
var agentService = _services.GetRequiredService<IAgentService>();
_routerAgentIds = agentService.GetAgents(new AgentFilter
{
Type = AgentType.Routing
}).Result.Items
.Select(x => x.Id).ToArray();
}
return _stack.Where(x => !_routerAgentIds.Contains(x)).Last();
}
}
2023-10-29 01:54:10 +00:00
public bool IsEmpty => !_stack.Any();
public string GetCurrentAgentId()
{
return _stack.Peek();
}
public void Push(string agentId)
{
if (_stack.Count == 0 || _stack.Peek() != agentId)
{
2024-02-28 16:21:14 +00:00
var preAgentId = _stack.Count == 0 ? agentId : _stack.Peek();
_stack.Push(agentId);
2024-02-28 16:21:14 +00:00
HookEmitter.Emit<IRoutingHook>(_services, async hook =>
await hook.OnAgentEnqueued(agentId, preAgentId)
).Wait();
}
}
/// <summary>
/// Pop current agent
/// </summary>
2023-10-29 01:54:10 +00:00
public void Pop()
{
2024-02-28 16:21:14 +00:00
if (_stack.Count == 0)
{
return;
}
var agentId = _stack.Pop();
HookEmitter.Emit<IRoutingHook>(_services, async hook =>
await hook.OnAgentDequeued(agentId, _stack.Peek())
).Wait();
2023-10-29 01:54:10 +00:00
}
public void Replace(string agentId)
{
2024-02-28 16:21:14 +00:00
var fromAgent = agentId;
var toAgent = agentId;
if (_stack.Count == 0)
{
_stack.Push(agentId);
}
else if (_stack.Peek() != agentId)
{
2024-02-28 16:21:14 +00:00
fromAgent = _stack.Peek();
_stack.Pop();
_stack.Push(agentId);
2024-02-28 16:21:14 +00:00
HookEmitter.Emit<IRoutingHook>(_services, async hook =>
await hook.OnAgentReplaced(fromAgent, toAgent)
).Wait();
}
}
2023-10-29 01:54:10 +00:00
public void Empty()
{
2024-02-28 16:21:14 +00:00
if (_stack.Count == 0)
{
return;
}
var agentId = GetCurrentAgentId();
2023-10-29 01:54:10 +00:00
_stack.Clear();
2024-02-28 16:21:14 +00:00
HookEmitter.Emit<IRoutingHook>(_services, async hook =>
await hook.OnAgentQueueEmptied(agentId)
).Wait();
}
}