Skip to content

Commit a6bd11c

Browse files
committed
refactor: simplify assistant message extraction using Optional chaining
Replace nested null checks and redundant branching with streamlined Optional-based approach. Since getResult() == getResults().get(0), processing all results handles both single and multiple result cases. Fixes spring-projects#4292 Signed-off-by: Soby Chacko <[email protected]>
1 parent 31423e9 commit a6bd11c

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

spring-ai-client-chat/src/main/java/org/springframework/ai/chat/client/advisor/PromptChatMemoryAdvisor.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.util.ArrayList;
2020
import java.util.List;
2121
import java.util.Map;
22+
import java.util.Optional;
2223
import java.util.stream.Collectors;
2324

2425
import org.slf4j.Logger;
@@ -141,18 +142,20 @@ public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChai
141142
@Override
142143
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
143144
List<Message> assistantMessages = new ArrayList<>();
144-
// Handle streaming case where we have a single result
145-
if (chatClientResponse.chatResponse() != null && chatClientResponse.chatResponse().getResult() != null
146-
&& chatClientResponse.chatResponse().getResult().getOutput() != null) {
147-
assistantMessages = List.of((Message) chatClientResponse.chatResponse().getResult().getOutput());
148-
}
149-
else if (chatClientResponse.chatResponse() != null) {
150-
assistantMessages = chatClientResponse.chatResponse()
151-
.getResults()
145+
// Extract assistant messages from chat client response.
146+
// Processes all results from getResults() which automatically handles both single
147+
// and multiple
148+
// result scenarios (since getResult() == getResults().get(0)). Uses Optional
149+
// chaining for
150+
// null safety and returns empty list if no results are available.
151+
assistantMessages = Optional.ofNullable(chatClientResponse)
152+
.map(ChatClientResponse::chatResponse)
153+
.filter(response -> response.getResults() != null && !response.getResults().isEmpty())
154+
.map(response -> response.getResults()
152155
.stream()
153156
.map(g -> (Message) g.getOutput())
154-
.toList();
155-
}
157+
.collect(Collectors.toList()))
158+
.orElse(List.of());
156159

157160
if (!assistantMessages.isEmpty()) {
158161
this.chatMemory.add(this.getConversationId(chatClientResponse.context(), this.defaultConversationId),

0 commit comments

Comments
 (0)