|
| 1 | +/* |
| 2 | + * Copyright 2023-2024 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 | + |
| 17 | +package org.springframework.ai.chat.client.advisor; |
| 18 | + |
| 19 | +import java.util.HashMap; |
| 20 | +import java.util.List; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.function.Predicate; |
| 23 | +import java.util.stream.Collectors; |
| 24 | + |
| 25 | +import reactor.core.publisher.Flux; |
| 26 | +import reactor.core.publisher.Mono; |
| 27 | +import reactor.core.scheduler.Schedulers; |
| 28 | + |
| 29 | +import org.springframework.ai.chat.client.advisor.api.AdvisedRequest; |
| 30 | +import org.springframework.ai.chat.client.advisor.api.AdvisedResponse; |
| 31 | +import org.springframework.ai.chat.client.advisor.api.CallAroundAdvisor; |
| 32 | +import org.springframework.ai.chat.client.advisor.api.CallAroundAdvisorChain; |
| 33 | +import org.springframework.ai.chat.client.advisor.api.StreamAroundAdvisor; |
| 34 | +import org.springframework.ai.chat.client.advisor.api.StreamAroundAdvisorChain; |
| 35 | +import org.springframework.ai.chat.messages.UserMessage; |
| 36 | +import org.springframework.ai.chat.model.ChatResponse; |
| 37 | +import org.springframework.ai.chat.prompt.PromptTemplate; |
| 38 | +import org.springframework.ai.document.Document; |
| 39 | +import org.springframework.ai.model.Content; |
| 40 | +import org.springframework.ai.rag.Query; |
| 41 | +import org.springframework.ai.rag.retrieval.source.DocumentRetriever; |
| 42 | +import org.springframework.lang.Nullable; |
| 43 | +import org.springframework.util.Assert; |
| 44 | +import org.springframework.util.StringUtils; |
| 45 | + |
| 46 | +/** |
| 47 | + * This advisor implements common Retrieval Augmented Generation (RAG) flows using the |
| 48 | + * building blocks defined in the {@link org.springframework.ai.rag} package and following |
| 49 | + * the Modular RAG Architecture. |
| 50 | + * <p> |
| 51 | + * It's the successor of the {@link QuestionAnswerAdvisor}. |
| 52 | + * |
| 53 | + * @author Christian Tzolov |
| 54 | + * @author Thomas Vitale |
| 55 | + * @since 1.0.0 |
| 56 | + * @see <a href="http://export.arxiv.org/abs/2407.21059">arXiv:2407.21059</a> |
| 57 | + * @see <a href="https://export.arxiv.org/abs/2312.10997">arXiv:2312.10997</a> |
| 58 | + */ |
| 59 | +public class RetrievalAugmentationAdvisor implements CallAroundAdvisor, StreamAroundAdvisor { |
| 60 | + |
| 61 | + public static final String DOCUMENT_CONTEXT = "rag_document_context"; |
| 62 | + |
| 63 | + public static final PromptTemplate DEFAULT_PROMPT_TEMPLATE = new PromptTemplate(""" |
| 64 | + {query} |
| 65 | +
|
| 66 | + Context information is below. Use this information to answer the user query. |
| 67 | +
|
| 68 | + --------------------- |
| 69 | + {context} |
| 70 | + --------------------- |
| 71 | +
|
| 72 | + Given the context and provided history information and not prior knowledge, |
| 73 | + reply to the user query. If the answer is not in the context, inform |
| 74 | + the user that you can't answer the query. |
| 75 | + """); |
| 76 | + |
| 77 | + private final DocumentRetriever documentRetriever; |
| 78 | + |
| 79 | + private final PromptTemplate promptTemplate; |
| 80 | + |
| 81 | + private final boolean protectFromBlocking; |
| 82 | + |
| 83 | + private final int order; |
| 84 | + |
| 85 | + public RetrievalAugmentationAdvisor(DocumentRetriever documentRetriever, @Nullable PromptTemplate promptTemplate, |
| 86 | + @Nullable Boolean protectFromBlocking, @Nullable Integer order) { |
| 87 | + Assert.notNull(documentRetriever, "documentRetriever cannot be null"); |
| 88 | + this.documentRetriever = documentRetriever; |
| 89 | + this.promptTemplate = promptTemplate != null ? promptTemplate : DEFAULT_PROMPT_TEMPLATE; |
| 90 | + this.protectFromBlocking = protectFromBlocking != null ? protectFromBlocking : false; |
| 91 | + this.order = order != null ? order : 0; |
| 92 | + } |
| 93 | + |
| 94 | + public static Builder builder() { |
| 95 | + return new Builder(); |
| 96 | + } |
| 97 | + |
| 98 | + @Override |
| 99 | + public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) { |
| 100 | + Assert.notNull(advisedRequest, "advisedRequest cannot be null"); |
| 101 | + Assert.notNull(chain, "chain cannot be null"); |
| 102 | + |
| 103 | + AdvisedRequest processedAdvisedRequest = before(advisedRequest); |
| 104 | + AdvisedResponse advisedResponse = chain.nextAroundCall(processedAdvisedRequest); |
| 105 | + return after(advisedResponse); |
| 106 | + } |
| 107 | + |
| 108 | + @Override |
| 109 | + public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) { |
| 110 | + Assert.notNull(advisedRequest, "advisedRequest cannot be null"); |
| 111 | + Assert.notNull(chain, "chain cannot be null"); |
| 112 | + |
| 113 | + // This can be executed by both blocking and non-blocking Threads |
| 114 | + // E.g. a command line or Tomcat blocking Thread implementation |
| 115 | + // or by a WebFlux dispatch in a non-blocking manner. |
| 116 | + Flux<AdvisedResponse> advisedResponses = (this.protectFromBlocking) ? |
| 117 | + // @formatter:off |
| 118 | + Mono.just(advisedRequest) |
| 119 | + .publishOn(Schedulers.boundedElastic()) |
| 120 | + .map(this::before) |
| 121 | + .flatMapMany(chain::nextAroundStream) |
| 122 | + : chain.nextAroundStream(before(advisedRequest)); |
| 123 | + // @formatter:on |
| 124 | + |
| 125 | + return advisedResponses.map(ar -> { |
| 126 | + if (onFinishReason().test(ar)) { |
| 127 | + ar = after(ar); |
| 128 | + } |
| 129 | + return ar; |
| 130 | + }); |
| 131 | + } |
| 132 | + |
| 133 | + private AdvisedRequest before(AdvisedRequest request) { |
| 134 | + Map<String, Object> context = new HashMap<>(request.adviseContext()); |
| 135 | + |
| 136 | + // 0. Create a query from the user text and parameters. |
| 137 | + Query query = new Query(new PromptTemplate(request.userText(), request.userParams()).render()); |
| 138 | + |
| 139 | + // 1. Retrieve similar documents for the original query. |
| 140 | + List<Document> documents = this.documentRetriever.retrieve(query); |
| 141 | + context.put(DOCUMENT_CONTEXT, documents); |
| 142 | + |
| 143 | + // 2. Combine retrieved documents. |
| 144 | + String documentContext = documents.stream() |
| 145 | + .map(Content::getContent) |
| 146 | + .collect(Collectors.joining(System.lineSeparator())); |
| 147 | + |
| 148 | + // 3. Define augmentation prompt parameters. |
| 149 | + Map<String, Object> promptParameters = Map.of("query", query.text(), "context", documentContext); |
| 150 | + |
| 151 | + // 4. Augment user prompt with the context data. |
| 152 | + UserMessage augmentedUserMessage = (UserMessage) this.promptTemplate.createMessage(promptParameters); |
| 153 | + |
| 154 | + return AdvisedRequest.from(request) |
| 155 | + .withUserText(augmentedUserMessage.getContent()) |
| 156 | + .withAdviseContext(context) |
| 157 | + .build(); |
| 158 | + } |
| 159 | + |
| 160 | + private AdvisedResponse after(AdvisedResponse advisedResponse) { |
| 161 | + ChatResponse.Builder chatResponseBuilder = ChatResponse.builder().from(advisedResponse.response()); |
| 162 | + chatResponseBuilder.withMetadata(DOCUMENT_CONTEXT, advisedResponse.adviseContext().get(DOCUMENT_CONTEXT)); |
| 163 | + return new AdvisedResponse(chatResponseBuilder.build(), advisedResponse.adviseContext()); |
| 164 | + } |
| 165 | + |
| 166 | + private Predicate<AdvisedResponse> onFinishReason() { |
| 167 | + return advisedResponse -> advisedResponse.response() |
| 168 | + .getResults() |
| 169 | + .stream() |
| 170 | + .anyMatch(result -> result != null && result.getMetadata() != null |
| 171 | + && StringUtils.hasText(result.getMetadata().getFinishReason())); |
| 172 | + } |
| 173 | + |
| 174 | + @Override |
| 175 | + public String getName() { |
| 176 | + return this.getClass().getSimpleName(); |
| 177 | + } |
| 178 | + |
| 179 | + @Override |
| 180 | + public int getOrder() { |
| 181 | + return this.order; |
| 182 | + } |
| 183 | + |
| 184 | + public static final class Builder { |
| 185 | + |
| 186 | + private DocumentRetriever documentRetriever; |
| 187 | + |
| 188 | + private PromptTemplate promptTemplate; |
| 189 | + |
| 190 | + private Boolean protectFromBlocking; |
| 191 | + |
| 192 | + private Integer order; |
| 193 | + |
| 194 | + private Builder() { |
| 195 | + } |
| 196 | + |
| 197 | + public Builder documentRetriever(DocumentRetriever documentRetriever) { |
| 198 | + this.documentRetriever = documentRetriever; |
| 199 | + return this; |
| 200 | + } |
| 201 | + |
| 202 | + public Builder promptTemplate(PromptTemplate promptTemplate) { |
| 203 | + this.promptTemplate = promptTemplate; |
| 204 | + return this; |
| 205 | + } |
| 206 | + |
| 207 | + public Builder protectFromBlocking(Boolean protectFromBlocking) { |
| 208 | + this.protectFromBlocking = protectFromBlocking; |
| 209 | + return this; |
| 210 | + } |
| 211 | + |
| 212 | + public Builder order(Integer order) { |
| 213 | + this.order = order; |
| 214 | + return this; |
| 215 | + } |
| 216 | + |
| 217 | + public RetrievalAugmentationAdvisor build() { |
| 218 | + return new RetrievalAugmentationAdvisor(this.documentRetriever, this.promptTemplate, |
| 219 | + this.protectFromBlocking, this.order); |
| 220 | + } |
| 221 | + |
| 222 | + } |
| 223 | + |
| 224 | +} |
0 commit comments