BotSharp/src/Infrastructure/BotSharp.Core/Routing/RoutingService.InvokeFunction.cs

68 lines
1.9 KiB
C#
Raw Normal View History

2023-12-07 03:06:09 +00:00
using BotSharp.Abstraction.Functions;
namespace BotSharp.Core.Routing;
public partial class RoutingService
{
2024-03-15 00:52:58 +00:00
public async Task<bool> InvokeFunction(string name, RoleDialogModel message)
2023-12-07 03:06:09 +00:00
{
var function = _services.GetServices<IFunctionCallback>().FirstOrDefault(x => x.Name == name);
2024-03-01 05:44:57 +00:00
if (function == null)
{
message.StopCompletion = true;
message.Content = $"Can't find function implementation of {message.FunctionName}.";
_logger.LogError(message.Content);
return false;
}
2023-12-07 03:06:09 +00:00
var originalFunctionName = message.FunctionName;
2023-12-11 23:15:37 +00:00
message.FunctionName = name;
message.Role = AgentRole.Function;
2024-02-28 03:15:21 +00:00
message.FunctionArgs = message.FunctionArgs;
2024-03-01 05:44:57 +00:00
var hooks = _services.GetServices<IConversationHook>()
.OrderBy(x => x.Priority)
.ToList();
// Before executing functions
foreach (var hook in hooks)
{
await hook.OnFunctionExecuting(message);
}
bool result = false;
try
{
result = await function.Execute(message);
}
catch (Exception ex)
{
message.StopCompletion = true;
message.Content = ex.Message;
_logger.LogError(ex.ToString());
}
// Make sure content has been populated
if (string.IsNullOrEmpty(message.Content) && message.Data != null)
{
message.Content = JsonSerializer.Serialize(message.Data);
}
// After functions have been executed
foreach (var hook in hooks)
{
await hook.OnFunctionExecuted(message);
}
// restore original function name
if (!message.StopCompletion &&
2024-03-15 00:52:58 +00:00
message.FunctionName != originalFunctionName)
{
message.FunctionName = originalFunctionName;
}
return result;
2023-12-07 03:06:09 +00:00
}
}