-
-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathRoutingContext.cs
More file actions
308 lines (259 loc) · 8.28 KB
/
RoutingContext.cs
File metadata and controls
308 lines (259 loc) · 8.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
using BotSharp.Abstraction.Infrastructures.Enums;
using BotSharp.Abstraction.Routing.Enums;
using BotSharp.Abstraction.Routing.Settings;
namespace BotSharp.Core.Routing;
public class RoutingContext : IRoutingContext
{
private readonly IServiceProvider _services;
private readonly RoutingSettings _setting;
private string[] _routerAgentIds;
private string _conversationId;
private string _messageId;
private int _currentRecursionDepth = 0;
private List<RoleDialogModel> _dialogs = [];
public RoutingContext(IServiceProvider services, RoutingSettings setting)
{
_services = services;
_setting = setting;
}
public int AgentCount => _stack.Count;
public string ConversationId => _conversationId;
public string MessageId => _messageId;
public int CurrentRecursionDepth => _currentRecursionDepth;
private Stack<string> _stack { get; set; } = new();
/// <summary>
/// Intent name
/// </summary>
public string IntentName { get; set; }
/// <summary>
/// Agent that can handle user original goal.
/// </summary>
public string OriginAgentId
{
get
{
if (_routerAgentIds == null)
{
var agentService = _services.GetRequiredService<IAgentService>();
_routerAgentIds = agentService.GetAgents(new AgentFilter
{
Types = [AgentType.Routing],
Pager = new Pagination { Size = 100 }
}).ConfigureAwait(false).GetAwaiter().GetResult().Items.Select(x => x.Id).ToArray();
}
return _stack.Where(x => !_routerAgentIds.Contains(x)).LastOrDefault() ?? string.Empty;
}
}
/// <summary>
/// Entry agent
/// </summary>
public string EntryAgentId
{
get
{
return _stack.LastOrDefault() ?? string.Empty;
}
}
public bool IsEmpty => !_stack.Any();
public string GetCurrentAgentId()
{
if (_stack.Count == 0)
{
return string.Empty;
}
return _stack.Peek();
}
/// <summary>
/// Push agent
/// </summary>
/// <param name="agentId">Id or Name</param>
/// <param name="reason"></param>
public async Task Push(string agentId, string? reason = null, bool updateLazyRouting = true)
{
// Convert id to name
if (!Guid.TryParse(agentId, out _))
{
var agentService = _services.GetRequiredService<IAgentService>();
var agents = await agentService.GetAgentOptions([agentId], byName: true);
if (agents.Count > 0)
{
agentId = agents.First().Id;
}
}
if (_stack.Count == 0 || _stack.Peek() != agentId)
{
var preAgentId = _stack.Count == 0 ? agentId : _stack.Peek();
_stack.Push(agentId);
await HookEmitter.Emit<IRoutingHook>(_services, async hook => await hook.OnAgentEnqueued(agentId, preAgentId, reason: reason),
agentId);
UpdateLazyRoutingAgent(updateLazyRouting);
}
}
/// <summary>
/// Pop current agent
/// </summary>
public async Task Pop(string? reason = null, bool updateLazyRouting = true)
{
if (_stack.Count == 0)
{
return;
}
var agentId = _stack.Pop();
var currentAgentId = GetCurrentAgentId();
await HookEmitter.Emit<IRoutingHook>(_services, async hook => await hook.OnAgentDequeued(agentId, currentAgentId, reason: reason),
agentId);
if (string.IsNullOrEmpty(currentAgentId))
{
return;
}
// Run the routing rule
var agentService = _services.GetRequiredService<IAgentService>();
var agent = await agentService.GetAgent(currentAgentId);
var message = new RoleDialogModel(AgentRole.User, $"Try to route to agent {agent.Name}")
{
CurrentAgentId = currentAgentId,
FunctionName = "route_to_agent",
FunctionArgs = JsonSerializer.Serialize(new FunctionCallFromLlm
{
Function = "route_to_agent",
AgentName = agent.Name,
NextActionReason = $"User manually route to agent {agent.Name}"
})
};
var routing = _services.GetRequiredService<IRoutingService>();
var (missingfield, _, redirectedAgentId) = await routing.HasMissingRequiredField(message);
if (missingfield)
{
if (currentAgentId != redirectedAgentId)
{
_stack.Push(redirectedAgentId);
}
}
UpdateLazyRoutingAgent(updateLazyRouting);
}
public async Task PopTo(string agentId, string reason, bool updateLazyRouting = true)
{
var currentAgentId = GetCurrentAgentId();
while (!string.IsNullOrEmpty(currentAgentId) &&
currentAgentId != agentId)
{
await Pop(reason, updateLazyRouting: updateLazyRouting);
currentAgentId = GetCurrentAgentId();
}
}
public string FirstGoalAgentId()
{
if (_stack.Count == 1)
{
return GetCurrentAgentId();
}
else if (_stack.Count > 1)
{
return _stack.ToArray()[_stack.Count - 2];
}
return string.Empty;
}
public bool ContainsAgentId(string agentId)
{
return _stack.ToArray().Contains(agentId);
}
public async Task Replace(string agentId, string? reason = null, bool updateLazyRouting = true)
{
var fromAgent = agentId;
var toAgent = agentId;
if (_stack.Count == 0)
{
_stack.Push(agentId);
}
else if (_stack.Peek() != agentId)
{
fromAgent = _stack.Peek();
_stack.Pop();
_stack.Push(agentId);
await HookEmitter.Emit<IRoutingHook>(_services, async hook => await hook.OnAgentReplaced(fromAgent, toAgent, reason: reason),
agentId);
}
UpdateLazyRoutingAgent(updateLazyRouting);
}
public async Task Empty(string? reason = null)
{
if (_stack.Count == 0)
{
return;
}
var agentId = GetCurrentAgentId();
_stack.Clear();
await HookEmitter.Emit<IRoutingHook>(_services, async hook => await hook.OnAgentQueueEmptied(agentId, reason: reason),
agentId);
}
public void SetMessageId(string conversationId, string messageId)
{
_conversationId = conversationId;
_messageId = messageId;
}
public int GetRecursiveCounter()
{
return _currentRecursionDepth;
}
public void IncreaseRecursiveCounter()
{
_currentRecursionDepth++;
}
public void SetRecursiveCounter(int counter)
{
_currentRecursionDepth = counter;
}
public void ResetRecursiveCounter()
{
_currentRecursionDepth = 0;
}
public Stack<string> GetAgentStack()
{
var copy = _stack.ToList();
copy.Reverse();
return new Stack<string>(copy);
}
public void SetAgentStack(Stack<string> stack)
{
var copy = stack.ToList();
copy.Reverse();
_stack = new Stack<string>(copy);
}
public void ResetAgentStack()
{
_stack.Clear();
}
public void SetDialogs(List<RoleDialogModel> dialogs)
{
_dialogs = new List<RoleDialogModel>(dialogs ?? []);
}
public void AddDialogs(List<RoleDialogModel> dialogs)
{
var items = new List<RoleDialogModel>(dialogs ?? []);
_dialogs ??= [];
_dialogs.AddRange(items);
}
public List<RoleDialogModel> GetDialogs()
{
_dialogs ??= [];
return new List<RoleDialogModel>(_dialogs);
}
public void ResetDialogs()
{
_dialogs = [];
}
private void UpdateLazyRoutingAgent(bool updateLazyRouting)
{
if (!updateLazyRouting)
{
return;
}
// Set next handling agent for lazy routing mode
var states = _services.GetRequiredService<IConversationStateService>();
var agentId = GetCurrentAgentId();
if (agentId != BuiltInAgentId.Fallback)
{
states.SetState(StateConst.LAZY_ROUTING_AGENT_ID, agentId);
}
}
}