2023-12-07 03:06:09 +00:00
|
|
|
using BotSharp.Abstraction.Functions;
|
|
|
|
|
|
|
|
|
|
namespace BotSharp.Core.Routing;
|
|
|
|
|
|
|
|
|
|
public partial class RoutingService
|
|
|
|
|
{
|
2024-03-11 18:26:49 +00:00
|
|
|
public async Task<bool> InvokeFunction(string name, RoleDialogModel message, bool restoreOriginalFunctionName = true)
|
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
|
|
|
|
2024-02-27 20:59:08 +00:00
|
|
|
var originalFunctionName = message.FunctionName;
|
2023-12-11 23:15:37 +00:00
|
|
|
message.FunctionName = name;
|
2023-12-12 14:16:34 +00:00
|
|
|
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);
|
|
|
|
|
}
|
2024-02-27 20:59:08 +00:00
|
|
|
|
|
|
|
|
// restore original function name
|
2024-03-11 18:26:49 +00:00
|
|
|
if (!message.StopCompletion &&
|
|
|
|
|
message.FunctionName != originalFunctionName &&
|
|
|
|
|
restoreOriginalFunctionName)
|
2024-02-27 20:59:08 +00:00
|
|
|
{
|
|
|
|
|
message.FunctionName = originalFunctionName;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
2023-12-07 03:06:09 +00:00
|
|
|
}
|
|
|
|
|
}
|