BotSharp/src/Plugins/BotSharp.Plugin.AudioHandler/Hooks/AudioHandlerHook.cs

61 lines
1.9 KiB
C#
Raw Normal View History

2024-08-17 03:39:32 +00:00
using BotSharp.Abstraction.Agents.Settings;
using BotSharp.Abstraction.Functions.Models;
2024-08-26 22:24:07 +00:00
namespace BotSharp.Plugin.AudioHandler.Hooks;
public class AudioHandlerHook : AgentHookBase, IAgentHook
2024-08-17 03:39:32 +00:00
{
2024-08-26 22:24:07 +00:00
private const string HANDLER_AUDIO = "handle_audio_request";
public override string SelfId => string.Empty;
public AudioHandlerHook(IServiceProvider services, AgentSettings settings) : base(services, settings)
2024-08-17 03:39:32 +00:00
{
2024-08-26 22:24:07 +00:00
}
2024-08-17 03:39:32 +00:00
2024-08-26 22:24:07 +00:00
public override void OnAgentLoaded(Agent agent)
{
var conv = _services.GetRequiredService<IConversationService>();
var isConvMode = conv.IsConversationMode();
var isEnabled = !agent.Utilities.IsNullOrEmpty() && agent.Utilities.Contains(UtilityName.AudioHandler);
2024-08-17 03:39:32 +00:00
2024-08-26 22:24:07 +00:00
if (isEnabled && isConvMode)
2024-08-17 03:39:32 +00:00
{
2024-08-28 16:08:12 +00:00
AddUtility(agent, HANDLER_AUDIO);
2024-08-17 03:39:32 +00:00
}
2024-08-26 22:24:07 +00:00
base.OnAgentLoaded(agent);
}
2024-08-17 03:39:32 +00:00
2024-08-28 16:08:12 +00:00
private void AddUtility(Agent agent, string functionName)
2024-08-26 22:24:07 +00:00
{
var (prompt, fn) = GetPromptAndFunction(functionName);
2024-08-28 16:08:12 +00:00
2024-08-26 22:24:07 +00:00
if (fn != null)
2024-08-17 03:39:32 +00:00
{
2024-08-26 22:24:07 +00:00
if (!string.IsNullOrWhiteSpace(prompt))
2024-08-17 03:39:32 +00:00
{
2024-08-26 22:24:07 +00:00
agent.Instruction += $"\r\n\r\n{prompt}\r\n\r\n";
}
2024-08-17 03:39:32 +00:00
2024-08-26 22:24:07 +00:00
if (agent.Functions == null)
{
agent.Functions = new List<FunctionDef> { fn };
}
else
{
agent.Functions.Add(fn);
2024-08-17 03:39:32 +00:00
}
}
2024-08-26 22:24:07 +00:00
}
2024-08-17 03:39:32 +00:00
2024-08-26 22:24:07 +00:00
private (string, FunctionDef?) GetPromptAndFunction(string functionName)
{
var db = _services.GetRequiredService<IBotSharpRepository>();
var agent = db.GetAgent(BuiltInAgentId.UtilityAssistant);
var prompt = agent?.Templates?.FirstOrDefault(x => x.Name.IsEqualTo($"{functionName}.fn"))?.Content ?? string.Empty;
var loadAttachmentFn = agent?.Functions?.FirstOrDefault(x => x.Name.IsEqualTo(functionName));
return (prompt, loadAttachmentFn);
2024-08-17 03:39:32 +00:00
}
}