@@ -51,41 +51,18 @@ public async Task<bool> SendMessage(string agentId,
5151 }
5252
5353 // Routing with reasoning
54+ var routing = _services . GetRequiredService < IRoutingService > ( ) ;
5455 var settings = _services . GetRequiredService < RoutingSettings > ( ) ;
55- if ( settings . RouterId == agent . Id )
56- {
57- var routing = _services . GetRequiredService < IRoutingService > ( ) ;
58- var reasonedContext = await routing . Enter ( agent , wholeDialogs ) ;
59-
60- if ( reasonedContext . StopCompletion )
61- {
62- await HandleAssistantMessage ( reasonedContext , onMessageReceived ) ;
63- return true ;
64- }
6556
66- // Switch agent
67- if ( reasonedContext . CurrentAgentId != agent . Id )
68- {
69- agent = await agentService . LoadAgent ( reasonedContext . CurrentAgentId ) ;
70- }
57+ routing . SetDialogs ( wholeDialogs ) ;
7158
72- routing . Dialogs . ForEach ( x =>
73- {
74- wholeDialogs . Add ( x ) ;
75- if ( x . Content != null )
76- {
77- _storage . Append ( _conversationId , x ) ;
78- }
79- } ) ;
80- }
59+ var response = settings . RouterId == agent . Id ?
60+ await routing . InstructLoop ( agent ) :
61+ await routing . ExecuteOnce ( agent ) ;
8162
82- var result = await GetChatCompletionsAsyncRecursively ( agent ,
83- wholeDialogs ,
84- onMessageReceived ,
85- onFunctionExecuting ,
86- onFunctionExecuted ) ;
63+ await HandleAssistantMessage ( response , onMessageReceived ) ;
8764
88- return result ;
65+ return true ;
8966 }
9067
9168 private async Task < Conversation > GetConversationRecord ( string agentId )
@@ -106,19 +83,23 @@ private async Task<Conversation> GetConversationRecord(string agentId)
10683 return converation ;
10784 }
10885
109- private void SaveStateByArgs ( string args )
86+ private async Task HandleAssistantMessage ( RoleDialogModel message , Func < RoleDialogModel , Task > onMessageReceived )
11087 {
111- var stateService = _services . GetRequiredService < IConversationStateService > ( ) ;
112- var jo = JsonSerializer . Deserialize < object > ( args ) ;
113- if ( jo is JsonElement root )
88+ var hooks = _services . GetServices < IConversationHook > ( ) . ToList ( ) ;
89+
90+ // After chat completion hook
91+ foreach ( var hook in hooks )
11492 {
115- foreach ( JsonProperty property in root . EnumerateObject ( ) )
116- {
117- if ( ! string . IsNullOrEmpty ( property . Value . ToString ( ) ) )
118- {
119- stateService . SetState ( property . Name , property . Value ) ;
120- }
121- }
93+ await hook . AfterCompletion ( message ) ;
12294 }
95+
96+ var agent = await _services . GetRequiredService < IAgentService > ( ) . GetAgent ( message . CurrentAgentId ) ;
97+
98+ _logger . LogInformation ( $ "[{ agent ? . Name ?? "Router" } ] { message . Role } : { message . Content } ") ;
99+
100+ await onMessageReceived ( message ) ;
101+
102+ // Add to dialog history
103+ _storage . Append ( _conversationId , message ) ;
123104 }
124105}
0 commit comments