2023-09-27 12:51:15 +00:00
|
|
|
using BotSharp.Abstraction.Templating;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Routing;
|
|
|
|
|
|
|
|
|
|
public partial class RoutingService
|
|
|
|
|
{
|
|
|
|
|
const int MAXIMUM_RECURSION_DEPTH = 2;
|
|
|
|
|
int CurrentRecursionDepth = 0;
|
|
|
|
|
public async Task<RoleDialogModel> InvokeAgent(string agentId)
|
|
|
|
|
{
|
|
|
|
|
CurrentRecursionDepth++;
|
|
|
|
|
if (CurrentRecursionDepth > MAXIMUM_RECURSION_DEPTH)
|
|
|
|
|
{
|
|
|
|
|
return Dialogs.Last();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var agentService = _services.GetRequiredService<IAgentService>();
|
|
|
|
|
var agent = await agentService.LoadAgent(agentId);
|
|
|
|
|
|
|
|
|
|
var chatCompletion = CompletionProvider.GetChatCompletion(_services);
|
2023-09-27 20:49:44 +00:00
|
|
|
RoleDialogModel response = chatCompletion.GetChatCompletions(agent, Dialogs);
|
2023-09-27 12:51:15 +00:00
|
|
|
|
2023-09-27 20:49:44 +00:00
|
|
|
if (response.Role == AgentRole.Function)
|
|
|
|
|
{
|
|
|
|
|
var fn = response;
|
|
|
|
|
// execute function
|
|
|
|
|
// Save states
|
|
|
|
|
SaveStateByArgs(JsonSerializer.Deserialize<JsonDocument>(fn.FunctionArgs));
|
2023-09-27 12:51:15 +00:00
|
|
|
|
2023-09-27 20:49:44 +00:00
|
|
|
var conversationService = _services.GetRequiredService<IConversationService>();
|
|
|
|
|
// Call functions
|
|
|
|
|
await conversationService.CallFunctions(fn);
|
2023-09-27 12:51:15 +00:00
|
|
|
|
2023-09-27 20:49:44 +00:00
|
|
|
if (string.IsNullOrEmpty(fn.Content))
|
|
|
|
|
{
|
|
|
|
|
fn.Content = fn.ExecutionResult;
|
|
|
|
|
}
|
2023-09-27 12:51:15 +00:00
|
|
|
|
2023-09-27 20:49:44 +00:00
|
|
|
Dialogs.Add(fn);
|
2023-09-27 12:51:15 +00:00
|
|
|
|
2023-09-27 20:49:44 +00:00
|
|
|
if (!fn.StopCompletion)
|
|
|
|
|
{
|
|
|
|
|
// Find response template
|
|
|
|
|
var templateService = _services.GetRequiredService<IResponseTemplateService>();
|
|
|
|
|
var quickResponse = await templateService.RenderFunctionResponse(agent.Id, fn);
|
|
|
|
|
if (!string.IsNullOrEmpty(quickResponse))
|
2023-09-27 12:51:15 +00:00
|
|
|
{
|
2023-09-27 20:49:44 +00:00
|
|
|
response = new RoleDialogModel(AgentRole.Assistant, quickResponse)
|
2023-09-27 12:51:15 +00:00
|
|
|
{
|
2023-09-27 20:49:44 +00:00
|
|
|
CurrentAgentId = agent.Id
|
|
|
|
|
};
|
2023-09-27 12:51:15 +00:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2023-09-27 20:49:44 +00:00
|
|
|
response = await InvokeAgent(fn.CurrentAgentId);
|
2023-09-27 12:51:15 +00:00
|
|
|
}
|
2023-09-27 20:49:44 +00:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
response = fn;
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-09-27 12:51:15 +00:00
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
|
|
|
|
}
|