|
19 | 19 | import java.util.ArrayList; |
20 | 20 | import java.util.List; |
21 | 21 | import java.util.Map; |
| 22 | +import java.util.Optional; |
22 | 23 | import java.util.stream.Collectors; |
23 | 24 |
|
24 | 25 | import org.slf4j.Logger; |
@@ -141,18 +142,20 @@ public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChai |
141 | 142 | @Override |
142 | 143 | public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) { |
143 | 144 | 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() |
152 | 155 | .stream() |
153 | 156 | .map(g -> (Message) g.getOutput()) |
154 | | - .toList(); |
155 | | - } |
| 157 | + .collect(Collectors.toList())) |
| 158 | + .orElse(List.of()); |
156 | 159 |
|
157 | 160 | if (!assistantMessages.isEmpty()) { |
158 | 161 | this.chatMemory.add(this.getConversationId(chatClientResponse.context(), this.defaultConversationId), |
|
0 commit comments