@@ -44,12 +44,17 @@ public function registerTool(string $name, callable $handler) : void
4444 /**
4545 * Run a flow
4646 */
47- public function runFlow (string $ userPrompt ) : array
47+ public function runFlow (string $ userPrompt, array & $ history = [] ) : array
4848 {
49- $ payload = $ this ->llm ->buildFlowInitialRequest ($ this ->flow , $ userPrompt );
49+ $ payload = $ this ->llm ->buildFlowInitialRequest ($ this ->flow , $ userPrompt, $ history );
5050
5151 // extract messages for history tracking
52- $ messages = $ payload ['messages ' ] ?? $ payload ['contents ' ] ?? [];
52+ $ initialMessages = $ payload ['messages ' ] ?? $ payload ['contents ' ] ?? [];
53+
54+ $ messages = [];
55+ foreach ($ initialMessages as $ msg ) {
56+ $ messages [] = $ msg ;
57+ }
5358
5459 $ response = $ this ->llm ->sendRaw ($ payload );
5560
@@ -97,6 +102,26 @@ public function runFlow(string $userPrompt) : array
97102 $ normalized = $ this ->llm ->normalizeCompletionsResponse ($ response );
98103 }
99104
105+ // as user prompt is already in initialMessages and is probably not reported into history, add it.
106+ $ history [] = $ this ->llm ->formatUserMessage ($ userPrompt );
107+
108+ // save flow messages to history, we can skip technical messages and previous history
109+ $ history = array_merge ($ history , array_slice ($ this ->filterTechMessages ($ messages ), count ($ initialMessages )));
110+
111+ // add assistant final message to history
112+ $ history [] = $ this ->llm ->formatAssistantMessage ($ normalized ['assistantText ' ] ?? '' );
113+
100114 return $ normalized ;
101115 }
116+
117+ protected function filterTechMessages (array $ messages ) : array
118+ {
119+ return array_filter ($ messages , function ($ msg ) {
120+ $ msg = json_decode (json_encode ($ msg ), true ); // force array
121+ if ($ msg ['role ' ] == 'model ' && isset ($ msg ['parts ' ][0 ]['functionCall ' ])) {
122+ return false ;
123+ }
124+ return !in_array ($ msg ['role ' ] ?? '' , ['system ' , 'tool ' ]);
125+ });
126+ }
102127}
0 commit comments