2025-03-06 21:10:17 +00:00
|
|
|
using BotSharp.Abstraction.Utilities;
|
|
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
{
|
|
|
|
|
hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId();
|
|
|
|
|
|
2025-04-20 13:05:20 +00:00
|
|
|
await hub.Completer.UpdateSession(hub.HubConn);
|
|
|
|
|
await hub.Completer.TriggerModelInference();
|
2025-03-06 21:10:17 +00:00
|
|
|
}
|
|
|
|
|
else if (message.FunctionName == "util-routing-fallback_to_router")
|
|
|
|
|
{
|
|
|
|
|
hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId();
|
|
|
|
|
|
2025-04-20 13:05:20 +00:00
|
|
|
await hub.Completer.UpdateSession(hub.HubConn);
|
|
|
|
|
await hub.Completer.TriggerModelInference();
|
2025-03-06 21:10:17 +00:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
// Update session for changed states
|
2025-03-08 00:40:28 +00:00
|
|
|
var instruction = await hub.Completer.UpdateSession(hub.HubConn);
|
2025-03-06 21:10:17 +00:00
|
|
|
await hub.Completer.InsertConversationItem(message);
|
2025-04-20 13:05:20 +00:00
|
|
|
|
|
|
|
|
if (message.StopCompletion)
|
|
|
|
|
{
|
|
|
|
|
await hub.Completer.TriggerModelInference($"Say to user: \"{message.Content}\"");
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
2025-04-20 23:24:13 +00:00
|
|
|
await hub.Completer.TriggerModelInference(instruction);
|
2025-04-20 13:05:20 +00:00
|
|
|
}
|
2025-03-06 21:10:17 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|