Retrieve an Alibaba Cloud Model Studio knowledge base using Spring AI Alibaba
Scope
- JDK version: JDK 17 or later
- Spring Boot version: Spring Boot 3 GA or later
- Spring AI Alibaba version: The nested SearchFilters example in this topic was verified with version 1.1.2.3
Choose an invocation method
In a Spring AI Alibaba application, you can use the SDK retriever or call the RAG API directly through a Spring HTTP client. Both support _operator with nested _conditions, but their endpoints and parameters differ:
| Method | Retrieval endpoint | Knowledge base parameter | Use case |
|---|---|---|---|
| SAA DashScope SDK | /api/v1/indices/pipeline/{pipeline_id}/retrieve | Set indexName in DashScopeDocumentRetrieverOptions. The SDK looks up the knowledge base and resolves the retrieval path. | Use an existing retriever in an Advisor-based Q&A flow |
| RAG API (direct HTTP) | https://{workspace_id}.cn-beijing.maas.aliyuncs.com/api/v1/indices/rag/index/retrieve | Pass the knowledge base ID as index_id in the request body. | Control HTTP requests, retrieval parameters, and result handling |
With direct HTTP retrieval, you can still use the SAA ChatClient to generate answers without changing frameworks. Do not set DashScopeApi.baseUrl to the full RAG API retrieval URL: the SDK appends its own Pipeline path, so these addresses are not interchangeable.
Procedure
The following steps use the SAA DashScope SDK. For direct HTTP retrieval, see Call the RAG API directly over HTTP.
1. Get the project code
For the complete sample code, see the bailian-rag-knowledge project in the Spring AI Alibaba project examples. Download the entire examples folder to your local machine to ensure the project structure and dependencies are complete.
2. Configure the environment
Obtain the API key for Alibaba Cloud Model Studio and configure it as an environment variable named AI_DASHSCOPE_API_KEY. Using an environment variable helps you avoid the security risks of hard coding.
To perform operations on a knowledge base in a sub-workspace, you also need to obtain the workspace ID and configure it as an environment variable named
AI_DASHSCOPE_WORKSPACE_ID.
# Configuration file path for bailian-rag-knowledge: bailian-rag-knowledge/src/main/resources/application.yml
spring:
ai:
dashscope:
api-key: ${AI_DASHSCOPE_API_KEY} # API key for Alibaba Cloud Model Studio
# workspace-id: ${AI_DASHSCOPE_WORKSPACE_ID} # Workspace ID (optional). You do not need to configure this when retrieving the default workspace's knowledge base.
3. Sample code
Use DashScopeApi to retrieve an Alibaba Cloud Model Studio knowledge base. The Spring AI Alibaba DashScope SDK sends retrieval requests to this path:
/api/v1/indices/pipeline/{pipeline_id}/retrieve
This path and the RAG API path /api/v1/indices/rag/index/retrieve are separate retrieval endpoints. Both support _operator with nested _conditions to express multiple OR conditions on the same field.
Controller sample code
import org.springframework.web.bind.annotation.*;
import com.alibaba.cloud.ai.example.rag.knowledge.service.RagService;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("/ai")
public class CloudRagController {
/** Inject CloudRagService */
private final RagService cloudRagService;
public CloudRagController(RagService cloudRagService) {
this.cloudRagService = cloudRagService;
}
@GetMapping(value="/bailian/knowledge/generate", produces="text/event-stream")
public Flux<String> generate(@RequestParam(value = "message",
defaultValue = "Hello, what are the main topics of your knowledge base documents?") String message) {
return cloudRagService.retrieve(message).map(x -> x.getResult().getOutput().getText());
}
}
When a user asks a question, DashScopeDocumentRetriever retrieves the most relevant text segments. It then submits these segments along with the original question to the large language model (LLM), which is qwen-max by default, to generate an answer.
Service sample code
import com.alibaba.cloud.ai.advisor.DocumentRetrievalAdvisor;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.*;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.document.Document;
import org.springframework.ai.document.DocumentReader;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
@Service()
public class CloudRagService implements RagService {
/** The value of INDEX_NAME here is the name of the knowledge base to retrieve. The knowledge base must be created in advance. */
private static final String INDEX_NAME = "TestKnowledgeBase";
/** Prompt template */
private static final String retrievalSystemTemplate = """
{query}
Here is some context information.
---------------------
{question_answer_context}
---------------------
Use only the context provided, not your prior knowledge, to answer the user's question. If the context does not contain the answer, state that you cannot answer the question.
""";
private final ChatClient chatClient;
private final DashScopeApi dashscopeApi;
public CloudRagService(ChatClient.Builder builder, DashScopeApi dashscopeApi) {
// These fields and values are examples. Replace them with searchable fields and values from your knowledge base.
Map<String, Object> orGroup = Map.of(
"_operator", "OR",
"_conditions", List.of(
Map.of("department", "Corporate"),
Map.of("department", Map.of("like", "%Research%")),
Map.of("document_type", Map.of("like", "%Policy%"))
)
);
DashScopeDocumentRetrieverOptions retrieverOptions =
DashScopeDocumentRetrieverOptions.builder()
.indexName(INDEX_NAME)
.searchFilters(List.of(orGroup))
.build();
DocumentRetriever retriever = new DashScopeDocumentRetriever(
dashscopeApi,
retrieverOptions
);
this.dashscopeApi = dashscopeApi;
// Initialize ChatClient. Set the knowledge base to retrieve and the model to call.
this.chatClient = builder
.defaultAdvisors(new DocumentRetrievalAdvisor(retriever, new SystemPromptTemplate(retrievalSystemTemplate)))
// The model defaults to qwen-max. You can set a different model using the following code.
//.defaultOptions(DashScopeChatOptions.builder().withModel("qwen-plus").build())
.build();
}
@Override
public Flux<ChatResponse> retrieve(String message) {
return chatClient.prompt().user(message).stream().chatResponse();
}
}
The searchFilters example matches records whose department equals Corporate, whose department contains Research, or whose document_type contains Policy. Omit searchFilters if filtering is not required. For the complete syntax and differences between invocation methods, see SearchFilters for a knowledge base.
Best practice: Call the RAG API directly over HTTP
The following example uses RestClient in the preceding SAA project to call the RAG API, convert the results to Document objects, and use the same DocumentRetrievalAdvisor. It implements a separate HTTP retriever rather than changing the SAA SDK endpoint.
Before running the example:
- Ensure the project includes Spring Web and Jackson, for example through
spring-boot-starter-web.RestClientrequires Spring Framework 6.1 or later, available in Spring Boot 3.2 or later. Also meet the dependency requirements of your SAA version. - Set the
AI_DASHSCOPE_API_KEY,AI_DASHSCOPE_WORKSPACE_ID, andBAILIAN_INDEX_IDenvironment variables to the API key, target workspace ID, and knowledge base ID. Direct HTTP calls require an explicit workspace ID, even for the default workspace. For authentication and permissions, see RAG API authentication. - Complete data import into the knowledge base. Reuse the preceding
orGroupand replace its example fields and values with searchable fields and values from your knowledge base. The HTTP request body usesindex_idandsearch_filters, not the OpenAPI parametersIndexIdandSearchFilters.
1. Implement the HTTP retriever. Place the following RagApiDocumentRetriever.java in the same package as CloudRagService, and use the same package declaration at the top of the file.
RagApiDocumentRetriever.java
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.ai.document.Document;
import org.springframework.ai.rag.Query;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
import java.util.List;
import java.util.Map;
public class RagApiDocumentRetriever implements DocumentRetriever {
private final RestClient client;
private final String indexId;
private final List<Map<String, Object>> searchFilters;
public RagApiDocumentRetriever(RestClient client, String indexId,
List<Map<String, Object>> searchFilters) {
this.client = client;
this.indexId = indexId;
this.searchFilters = searchFilters;
}
@Override
public List<Document> retrieve(Query query) {
Map<String, Object> body = Map.of(
"index_id", indexId,
"query", query.text(),
"search_filters", searchFilters
);
RetrievalResponse response = client.post()
.uri("/api/v1/indices/rag/index/retrieve")
.contentType(MediaType.APPLICATION_JSON)
.body(body)
.retrieve()
.body(RetrievalResponse.class);
if (response == null || !response.success() || response.data() == null
|| response.data().nodes() == null) {
String requestId = response == null ? null : response.requestId();
throw new IllegalStateException("Knowledge base retrieval failed; request_id=" + requestId);
}
return response.data().nodes().stream()
.map(node -> Document.builder()
.text(node.text())
.metadata(node.metadata())
.score(node.score())
.build())
.toList();
}
@JsonIgnoreProperties(ignoreUnknown = true)
public record RetrievalResponse(boolean success, RetrievalData data,
@JsonProperty("request_id") String requestId) {}
@JsonIgnoreProperties(ignoreUnknown = true)
public record RetrievalData(List<RetrievalNode> nodes) {}
@JsonIgnoreProperties(ignoreUnknown = true)
public record RetrievalNode(String text, Map<String, Object> metadata, Double score) {}
}
2. Integrate with the existing Q&A flow. Add the following imports to the top of CloudRagService. In its constructor, replace the initialization of retrieverOptions and DashScopeDocumentRetriever with the remaining code. Keep orGroup, the prompt template, and the ChatClient initialization. Do not register a second Service:
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import java.net.http.HttpClient;
import java.time.Duration;
JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()
);
requestFactory.setReadTimeout(Duration.ofSeconds(30));
RestClient client = RestClient.builder()
.baseUrl("https://" + System.getenv("AI_DASHSCOPE_WORKSPACE_ID")
+ ".cn-beijing.maas.aliyuncs.com")
.defaultHeaders(headers -> headers.setBearerAuth(System.getenv("AI_DASHSCOPE_API_KEY")))
.requestFactory(requestFactory)
.build();
DocumentRetriever retriever = new RagApiDocumentRetriever(
client,
System.getenv("BAILIAN_INDEX_ID"),
List.of(orGroup)
);
The HTTP client is created once during service initialization and reused. The example uses a 10-second connection timeout and a 30-second read timeout; adjust these to your application's requirements. Requests use a Bearer API key and a JSON body. Nested maps and lists are sent as JSON objects and arrays. Do not serialize _conditions to a string first.
The response's data.nodes are mapped to Document objects containing text, metadata, and similarity scores. An empty list means that no chunks matched. RestClient.retrieve() throws on HTTP errors; business failures or missing node lists also cause an exception rather than an empty result. Calls to the preceding Controller still generate an answer from the original question and retrieved context. Retain the response's request_id for troubleshooting, but do not log the API key.
Reactive applications: RestClient is synchronous, so the preceding flow includes blocking retrieval. For end-to-end nonblocking processing, call the same RAG API through WebClient with the same authentication and JSON body, and compose retrieval and model calls through Mono/Flux. Do not call .block() on reactive event-loop threads. Using WebClient does not turn RAG Retrieve into an SSE endpoint: retrieval still returns a single JSON response.
Learn more
- Spring AI Alibaba: Provides documentation, tutorials, hands-on blogs, and a developer community to help you quickly develop generative AI applications in Java.
- Create and use a knowledge base: Learn more about the core features and best practices of Alibaba Cloud Model Studio knowledge bases.