BotSharp/src/Infrastructure/BotSharp.Core.Realtime/Hooks/RealtimeConversationHook.cs

73 lines
2.7 KiB
C#
Raw Normal View History

2025-03-06 21:10:17 +00:00
using BotSharp.Abstraction.Utilities;
2025-04-04 19:00:15 +00:00
using BotSharp.Core.Infrastructures;
2025-03-06 21:10:17 +00:00
namespace BotSharp.Core.Realtime.Hooks;
public class RealtimeConversationHook : ConversationHookBase, IConversationHook
{
private readonly IServiceProvider _services;
public RealtimeConversationHook(IServiceProvider services)
{
_services = services;
}
public async Task OnFunctionExecuting(RoleDialogModel message)
{
var hub = _services.GetRequiredService<IRealtimeHub>();
if (hub.HubConn == null)
{
return;
}
// Save states
2025-04-11 20:09:39 +00:00
if (message.FunctionArgs != null && message.FunctionArgs.Length > 3)
{
var states = _services.GetRequiredService<IConversationStateService>();
states.SaveStateByArgs(message.FunctionArgs?.JsonContent<JsonDocument>());
}
2025-03-06 21:10:17 +00:00
}
public async Task OnFunctionExecuted(RoleDialogModel message)
{
var hub = _services.GetRequiredService<IRealtimeHub>();
if (hub.HubConn == null)
{
return;
}
2025-04-04 19:00:15 +00:00
2025-03-06 21:10:17 +00:00
var routing = _services.GetRequiredService<IRoutingService>();
message.Role = AgentRole.Function;
if (message.FunctionName == "route_to_agent")
{
var inst = JsonSerializer.Deserialize<RoutingArgs>(message.FunctionArgs ?? "{}") ?? new();
message.Content = $"I'm your AI assistant '{inst.AgentName}' to help with: '{inst.NextActionReason}'";
2025-03-06 21:10:17 +00:00
hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId();
var instruction = await hub.Completer.UpdateSession(hub.HubConn);
2025-03-06 21:10:17 +00:00
await hub.Completer.InsertConversationItem(message);
await hub.Completer.TriggerModelInference($"{instruction}\r\n\r\nAssist user task: {inst.NextActionReason}");
2025-03-06 21:10:17 +00:00
}
else if (message.FunctionName == "util-routing-fallback_to_router")
{
var inst = JsonSerializer.Deserialize<FallbackArgs>(message.FunctionArgs ?? "{}") ?? new();
message.Content = $"Returned to Router due to {inst.Reason}";
hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId();
var instruction = await hub.Completer.UpdateSession(hub.HubConn);
2025-03-06 21:10:17 +00:00
await hub.Completer.InsertConversationItem(message);
await hub.Completer.TriggerModelInference(instruction);
2025-03-06 21:10:17 +00:00
}
else
{
2025-04-05 20:59:30 +00:00
// Clear cache to force to rebuild the agent instruction
Utilities.ClearCache();
2025-03-06 21:10:17 +00:00
// Update session for changed states
var instruction = await hub.Completer.UpdateSession(hub.HubConn);
2025-03-06 21:10:17 +00:00
await hub.Completer.InsertConversationItem(message);
await hub.Completer.TriggerModelInference(instruction);
2025-03-06 21:10:17 +00:00
}
}
}