|
| 1 | +/* |
| 2 | + * Copyright 2025 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.alibaba.cloud.ai.example.manus.dynamic.memory.advisor; |
| 17 | + |
| 18 | +import org.springframework.ai.chat.client.ChatClientMessageAggregator; |
| 19 | +import org.springframework.ai.chat.client.ChatClientRequest; |
| 20 | +import org.springframework.ai.chat.client.ChatClientResponse; |
| 21 | +import org.springframework.ai.chat.client.advisor.api.*; |
| 22 | +import org.springframework.ai.chat.memory.ChatMemory; |
| 23 | +import org.springframework.ai.chat.messages.Message; |
| 24 | +import org.springframework.ai.chat.messages.UserMessage; |
| 25 | +import org.springframework.util.Assert; |
| 26 | +import reactor.core.publisher.Flux; |
| 27 | +import reactor.core.publisher.Mono; |
| 28 | +import reactor.core.scheduler.Scheduler; |
| 29 | + |
| 30 | +import java.util.ArrayList; |
| 31 | +import java.util.List; |
| 32 | + |
| 33 | +/** |
| 34 | + * 2025/8/7 auth: dahua |
| 35 | + */ |
| 36 | +public class CustomMessageChatMemoryAdvisor implements BaseChatMemoryAdvisor { |
| 37 | + |
| 38 | + private final ChatMemory chatMemory; |
| 39 | + |
| 40 | + private final String defaultConversationId; |
| 41 | + |
| 42 | + private final int order; |
| 43 | + |
| 44 | + private final Scheduler scheduler; |
| 45 | + |
| 46 | + private String userRequest; |
| 47 | + |
| 48 | + private AdvisorType advisorType; |
| 49 | + |
| 50 | + private CustomMessageChatMemoryAdvisor(ChatMemory chatMemory, String defaultConversationId, int order, |
| 51 | + Scheduler scheduler, String userRequest, AdvisorType advisorType) { |
| 52 | + Assert.notNull(chatMemory, "chatMemory cannot be null"); |
| 53 | + Assert.hasText(defaultConversationId, "defaultConversationId cannot be null or empty"); |
| 54 | + Assert.notNull(scheduler, "scheduler cannot be null"); |
| 55 | + this.chatMemory = chatMemory; |
| 56 | + this.defaultConversationId = defaultConversationId; |
| 57 | + this.order = order; |
| 58 | + this.scheduler = scheduler; |
| 59 | + this.userRequest = userRequest; |
| 60 | + this.advisorType = advisorType; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public int getOrder() { |
| 65 | + return this.order; |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + public Scheduler getScheduler() { |
| 70 | + return this.scheduler; |
| 71 | + } |
| 72 | + |
| 73 | + @Override |
| 74 | + public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) { |
| 75 | + String conversationId = getConversationId(chatClientRequest.context(), this.defaultConversationId); |
| 76 | + |
| 77 | + // 1. Retrieve the chat memory for the current conversation. |
| 78 | + List<Message> memoryMessages = this.chatMemory.get(conversationId); |
| 79 | + |
| 80 | + // 2. Advise the request messages list. |
| 81 | + List<Message> processedMessages = new ArrayList<>(memoryMessages); |
| 82 | + processedMessages.addAll(chatClientRequest.prompt().getInstructions()); |
| 83 | + |
| 84 | + // 3. Create a new request with the advised messages. |
| 85 | + ChatClientRequest processedChatClientRequest = chatClientRequest.mutate() |
| 86 | + .prompt(chatClientRequest.prompt().mutate().messages(processedMessages).build()) |
| 87 | + .build(); |
| 88 | + |
| 89 | + if (this.advisorType == AdvisorType.AFTER) { |
| 90 | + return processedChatClientRequest; |
| 91 | + } |
| 92 | + |
| 93 | + // 4. Add the new user message to the conversation memory. |
| 94 | + UserMessage userMessage = processedChatClientRequest.prompt().getUserMessage(); |
| 95 | + |
| 96 | + // 5. The user's question needs to be re-placed here because the default message |
| 97 | + // body contains template information, |
| 98 | + // which can be misleading when displayed on the front end. |
| 99 | + // Re-placement of the user's actual question does not affect the model's ability |
| 100 | + // to process new requests after loading memory and can also reduce token |
| 101 | + // consumption in the model. |
| 102 | + UserMessage customMessage = UserMessage.builder() |
| 103 | + .text(userRequest) |
| 104 | + .media(userMessage.getMedia()) |
| 105 | + .metadata(userMessage.getMetadata()) |
| 106 | + .build(); |
| 107 | + this.chatMemory.add(conversationId, customMessage); |
| 108 | + |
| 109 | + return processedChatClientRequest; |
| 110 | + } |
| 111 | + |
| 112 | + @Override |
| 113 | + public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) { |
| 114 | + if (this.advisorType == AdvisorType.BEFORE) { |
| 115 | + return chatClientResponse; |
| 116 | + } |
| 117 | + List<Message> assistantMessages = new ArrayList<>(); |
| 118 | + if (chatClientResponse.chatResponse() != null) { |
| 119 | + assistantMessages = chatClientResponse.chatResponse() |
| 120 | + .getResults() |
| 121 | + .stream() |
| 122 | + .map(g -> (Message) g.getOutput()) |
| 123 | + .toList(); |
| 124 | + } |
| 125 | + this.chatMemory.add(this.getConversationId(chatClientResponse.context(), this.defaultConversationId), |
| 126 | + assistantMessages); |
| 127 | + return chatClientResponse; |
| 128 | + } |
| 129 | + |
| 130 | + @Override |
| 131 | + public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest, |
| 132 | + StreamAdvisorChain streamAdvisorChain) { |
| 133 | + // Get the scheduler from BaseAdvisor |
| 134 | + Scheduler scheduler = this.getScheduler(); |
| 135 | + |
| 136 | + // Process the request with the before method |
| 137 | + return Mono.just(chatClientRequest) |
| 138 | + .publishOn(scheduler) |
| 139 | + .map(request -> this.before(request, streamAdvisorChain)) |
| 140 | + .flatMapMany(streamAdvisorChain::nextStream) |
| 141 | + .transform(flux -> new ChatClientMessageAggregator().aggregateChatClientResponse(flux, |
| 142 | + response -> this.after(response, streamAdvisorChain))); |
| 143 | + } |
| 144 | + |
| 145 | + public static CustomMessageChatMemoryAdvisor.Builder builder(ChatMemory chatMemory, String userRequest, |
| 146 | + AdvisorType advisorType) { |
| 147 | + return new CustomMessageChatMemoryAdvisor.Builder(chatMemory, userRequest, advisorType); |
| 148 | + } |
| 149 | + |
| 150 | + public static final class Builder { |
| 151 | + |
| 152 | + private String conversationId = ChatMemory.DEFAULT_CONVERSATION_ID; |
| 153 | + |
| 154 | + private int order = Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER; |
| 155 | + |
| 156 | + private Scheduler scheduler = BaseAdvisor.DEFAULT_SCHEDULER; |
| 157 | + |
| 158 | + private ChatMemory chatMemory; |
| 159 | + |
| 160 | + private String userRequest; |
| 161 | + |
| 162 | + private AdvisorType advisorType; |
| 163 | + |
| 164 | + private Builder(ChatMemory chatMemory, String userRequest, AdvisorType advisorType) { |
| 165 | + this.chatMemory = chatMemory; |
| 166 | + this.userRequest = userRequest; |
| 167 | + this.advisorType = advisorType; |
| 168 | + } |
| 169 | + |
| 170 | + /** |
| 171 | + * Set the conversation id. |
| 172 | + * @param conversationId the conversation id |
| 173 | + * @return the builder |
| 174 | + */ |
| 175 | + public CustomMessageChatMemoryAdvisor.Builder conversationId(String conversationId) { |
| 176 | + this.conversationId = conversationId; |
| 177 | + return this; |
| 178 | + } |
| 179 | + |
| 180 | + /** |
| 181 | + * Set the order. |
| 182 | + * @param order the order |
| 183 | + * @return the builder |
| 184 | + */ |
| 185 | + public CustomMessageChatMemoryAdvisor.Builder order(int order) { |
| 186 | + this.order = order; |
| 187 | + return this; |
| 188 | + } |
| 189 | + |
| 190 | + public CustomMessageChatMemoryAdvisor.Builder scheduler(Scheduler scheduler) { |
| 191 | + this.scheduler = scheduler; |
| 192 | + return this; |
| 193 | + } |
| 194 | + |
| 195 | + /** |
| 196 | + * Build the advisor. |
| 197 | + * @return the advisor |
| 198 | + */ |
| 199 | + public CustomMessageChatMemoryAdvisor build() { |
| 200 | + return new CustomMessageChatMemoryAdvisor(this.chatMemory, this.conversationId, this.order, this.scheduler, |
| 201 | + this.userRequest, this.advisorType); |
| 202 | + } |
| 203 | + |
| 204 | + } |
| 205 | + |
| 206 | + public enum AdvisorType { |
| 207 | + |
| 208 | + BEFORE, AFTER, ALL |
| 209 | + |
| 210 | + } |
| 211 | + |
| 212 | +} |
0 commit comments