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

70 lines
2.6 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
var states = _services.GetRequiredService<IConversationStateService>();
states.SaveStateByArgs(message.FunctionArgs?.JsonContent<JsonDocument>() ?? JsonDocument.Parse("{}"));
}
public async Task OnFunctionExecuted(RoleDialogModel message)
{
var hub = _services.GetRequiredService<IRealtimeHub>();
if (hub.HubConn == null)
{
return;
}
2025-04-04 19:00:15 +00:00
// Clear cache to force to rebuild the agent instruction
Utilities.ClearCache();
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
{
// 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
}
}
}