|
| 1 | +using BotSharp.Abstraction.Utilities; |
| 2 | + |
| 3 | +namespace BotSharp.Core.Realtime.Hooks; |
| 4 | + |
| 5 | +public class RealtimeConversationHook : ConversationHookBase, IConversationHook |
| 6 | +{ |
| 7 | + private readonly IServiceProvider _services; |
| 8 | + public RealtimeConversationHook(IServiceProvider services) |
| 9 | + { |
| 10 | + _services = services; |
| 11 | + } |
| 12 | + |
| 13 | + public async Task OnFunctionExecuting(RoleDialogModel message) |
| 14 | + { |
| 15 | + var hub = _services.GetRequiredService<IRealtimeHub>(); |
| 16 | + if (hub.HubConn == null) |
| 17 | + { |
| 18 | + return; |
| 19 | + } |
| 20 | + // Save states |
| 21 | + var states = _services.GetRequiredService<IConversationStateService>(); |
| 22 | + states.SaveStateByArgs(message.FunctionArgs?.JsonContent<JsonDocument>() ?? JsonDocument.Parse("{}")); |
| 23 | + } |
| 24 | + |
| 25 | + public async Task OnFunctionExecuted(RoleDialogModel message) |
| 26 | + { |
| 27 | + var hub = _services.GetRequiredService<IRealtimeHub>(); |
| 28 | + if (hub.HubConn == null) |
| 29 | + { |
| 30 | + return; |
| 31 | + } |
| 32 | + var routing = _services.GetRequiredService<IRoutingService>(); |
| 33 | + |
| 34 | + message.Role = AgentRole.Function; |
| 35 | + |
| 36 | + if (message.FunctionName == "route_to_agent") |
| 37 | + { |
| 38 | + var inst = JsonSerializer.Deserialize<RoutingArgs>(message.FunctionArgs ?? "{}") ?? new(); |
| 39 | + message.Content = $"Connected to agent of {inst.AgentName}"; |
| 40 | + hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId(); |
| 41 | + |
| 42 | + await hub.Completer.UpdateSession(hub.HubConn); |
| 43 | + await hub.Completer.InsertConversationItem(message); |
| 44 | + await hub.Completer.TriggerModelInference($"Guide the user through the next steps of the process as this Agent ({inst.AgentName}), following its instructions and operational procedures."); |
| 45 | + } |
| 46 | + else if (message.FunctionName == "util-routing-fallback_to_router") |
| 47 | + { |
| 48 | + var inst = JsonSerializer.Deserialize<FallbackArgs>(message.FunctionArgs ?? "{}") ?? new(); |
| 49 | + message.Content = $"Returned to Router due to {inst.Reason}"; |
| 50 | + hub.HubConn.CurrentAgentId = routing.Context.GetCurrentAgentId(); |
| 51 | + |
| 52 | + await hub.Completer.UpdateSession(hub.HubConn); |
| 53 | + await hub.Completer.InsertConversationItem(message); |
| 54 | + await hub.Completer.TriggerModelInference($"Check with user whether to proceed the new request: {inst.Reason}"); |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + // Update session for changed states |
| 59 | + await hub.Completer.UpdateSession(hub.HubConn); |
| 60 | + await hub.Completer.InsertConversationItem(message); |
| 61 | + await hub.Completer.TriggerModelInference("Reply based on the function's output."); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments