
你是否遇到过:Chat AI 回答行业问题时总说车轱辘话?内部知识库更新后,AI仍然给出过期答案?

Spring AI的RAG技术正是为解决这些问题而生,结合信息检索和文本生成的技术,通过先查资料后回答的机制,让AI摆脱传统模型的”知识遗忘”困境。
|
|
|
|
|
|
|
|
|
|
|
|
快速开始
1.接入Sping Ai 、向量vector redis、检索 advisors-vector-store 框架。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-advisors-vector-store</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-redis</artifactId>
</dependency>
2.配置Ai模型和 api-key 、 向量模型。
spring.ai.openai.base-url=https://dashscope.aliyuncs.com/compatible-mode/
spring.ai.openai.chat.options.model=qwen-max
spring.ai.openai.api-key=${OPEN_API_KEY}
spring.ai.openai.embedding.options.model=text-embedding-v4
3.配置 redis 连接、key前缀。
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.ai.vectorstore.redis.initialize-schema=true
spring.ai.vectorstore.redis.index-name=custom-index
spring.ai.vectorstore.redis.prefix=custom-prefix
4.注入向量vector redis、增强检索QuestionAnswerAdvisor。
public VectoreRedisService(ChatClient.Builder builder,VectorStore vectorStore ) {
this.vectorStore = vectorStore;
this.chatClient = builder.defaultAdvisors(new QuestionAnswerAdvisor(vectorStore)) .build();
}
5.初始化知识库。
public void storeVector() {
List<Document> documents = List.of(
new Document("有范编程笔记公众号是记录和分享技术笔记,及个人的所见所闻。"),
new Document("有范是一个技术博主" ));
this.vectorStore.add(documents);
}
6.实现检索增强生成。
public String generateAsString(String message) {
return this.chatClient.prompt()
.user(promptUserSpec -> promptUserSpec.text(message))
.call() .content();
}