SpringAI-RAG

SpringAI-RAG

起男 49 2025-06-21

SpringAI-RAG

依赖

    <dependencies>
        <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>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>1.0.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

配置文件

spring:
  ai:
    openai:
      api-key: ${ALI_API_KEY}
      base-url: https://dashscope.aliyuncs.com/compatible-mode
      chat:
        options:
          model: qwen-plus
      embedding:
        api-key: ${ALI_API_KEY}
        base-url: https://dashscope.aliyuncs.com/compatible-mode
        options:
          model: text-embedding-v4

向量数据库

    @Bean
    public VectorStore vectorStore(@Qualifier("openAiEmbeddingModel") EmbeddingModel embeddingModel) {
        //使用内存
        return SimpleVectorStore.builder(embeddingModel).build();
    }

初始化数据

    @Bean
    public CommandLineRunner init(VectorStore vectorStore,
                                  @Value("classpath:rag/data.txt")Resource resource) {
        return args -> {
            //加载数据
            List<Document> documentList = new TextReader(resource).read();
            //拆分
            TextSplitter splitter = new TextSplitter() {
                @Override
                protected List<String> splitText(String text) {
                    //按照行拆分
                    return List.of(text.split("\\n"));
                }
            };
            List<Document> transform = splitter.transform(documentList);
            //存入向量数据库
            vectorStore.write(transform);
        };
    }

检索

@RestController
@RequestMapping("rag")
public class RAGController {

    @Autowired
    private ChatClient chatClient;
    @Autowired
    private VectorStore vectorStore;

    @GetMapping("{message}")
    public String chat(@PathVariable("message") String message){
        return chatClient.prompt()
                .user(message)
                .advisors(QuestionAnswerAdvisor.builder(vectorStore)
                                .searchRequest(SearchRequest.builder()
                                        .query(message)
                                        .topK(1)
                                        .build())
                        .build())
                .call()
                .content();
    }
}