@@ -150,7 +150,12 @@ public AdvisedRequest updateContext(Function<Map<String, Object>, Map<String, Ob
150150 public Prompt toPrompt () {
151151 List <Message > promptMessages = new ArrayList <>();
152152
153- // 1. Always add the SystemMessage first (if present)
153+ // 1. Start with existing conversation messages, if present
154+ if (!CollectionUtils .isEmpty (this .messages ())) {
155+ promptMessages .addAll (this .messages ());
156+ }
157+
158+ // 2. Process the new SystemMessage, if present
154159 String processedSystemText = this .systemText ();
155160 if (StringUtils .hasText (processedSystemText )) {
156161 if (!CollectionUtils .isEmpty (this .systemParams ())) {
@@ -159,13 +164,7 @@ public Prompt toPrompt() {
159164 promptMessages .add (new SystemMessage (processedSystemText ));
160165 }
161166
162- // 2. Add any existing conversation messages
163- List <Message > existingMessages = this .messages ();
164- if (!CollectionUtils .isEmpty (existingMessages )) {
165- promptMessages .addAll (existingMessages );
166- }
167-
168- // 3. Process and append the UserMessage (if present)
167+ // 3. Process the new UserMessage, if present
169168 String formatParam = (String ) this .adviseContext ().get ("formatParam" );
170169 var processedUserText = StringUtils .hasText (formatParam )
171170 ? this .userText () + System .lineSeparator () + "{spring_ai_soc_format}" : this .userText ();
@@ -181,7 +180,7 @@ public Prompt toPrompt() {
181180 promptMessages .add (new UserMessage (processedUserText , this .media ()));
182181 }
183182
184- // 4. Configure function-calling options
183+ // 4. Configure function-calling options, if applicable
185184 if (this .chatOptions () instanceof FunctionCallingOptions functionCallingOptions ) {
186185 if (!this .functionNames ().isEmpty ()) {
187186 functionCallingOptions .setFunctions (new HashSet <>(this .functionNames ()));
0 commit comments