Skip to content

Commit c4c9754

Browse files
committed
Refactor ChatResponse processing with Optional API
- Replace if-else null checks with Optional chain - Improve code readability and maintain functional style Signed-off-by: eeaters <[email protected]>
1 parent 1dd686b commit c4c9754

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

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

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,13 @@
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;
2526
import org.slf4j.LoggerFactory;
27+
import org.springframework.ai.chat.model.ChatResponse;
28+
import org.springframework.ai.chat.model.Generation;
2629
import reactor.core.publisher.Flux;
2730
import reactor.core.publisher.Mono;
2831
import reactor.core.scheduler.Scheduler;
@@ -142,17 +145,11 @@ public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChai
142145
public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
143146
List<Message> assistantMessages = new ArrayList<>();
144147
// 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()
152-
.stream()
153-
.map(g -> (Message) g.getOutput())
154-
.toList();
155-
}
148+
Optional.of(chatClientResponse)
149+
.map(ChatClientResponse::chatResponse)
150+
.map(ChatResponse::getResult)
151+
.map(Generation::getOutput)
152+
.ifPresent(assistantMessages::add);
156153

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

0 commit comments

Comments
 (0)