上篇文章我們大概講了一下向量模型的知識,本篇文章,我們將會通過RAG實戰的形式,來感受一下RAG。
項目準備
pom.xml
這里我們需要引入向量庫和pdf相關的包
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-vector-store-redis</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-pdf-document-reader</artifactId></dependency>
application.yaml
spring:ai:vectorstore:redis:index-name: spring_ai_index ##向量庫索引名稱initialize-schema: true ##是否初始化向量索引結構prefix: "doc:" ##向量庫前綴data:redis:host: 127.0.0.1 ##redis地址,我這里使用的Docker安裝的Redis-stack的向量庫
EmbeddingController類
@RestController
@RequestMapping(value = "/api/embedding")
public class EmbeddingController {@Autowiredprivate VectorStore vectorStore;@GetMapping("/vector/store")public List<Document> vectoreStore() {List<Document> documents = List.of(new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),new Document("The World is Big and Salvation Lurks Around the Corner"),new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));vectorStore.add(documents);List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());return results;}@GetMapping("/vector/store/pdf")public List<Document> vectorStorePdf() throws MalformedURLException {org.springframework.core.io.Resource resource = new FileUrlResource("funcationCall.pdf");PdfDocumentReaderConfig pdfDocumentReaderConfig = PdfDocumentReaderConfig.builder().withPageExtractedTextFormatter(ExtractedTextFormatter.defaults()).withPagesPerDocument(1).build();PagePdfDocumentReader pagePdfDocumentReader = new PagePdfDocumentReader(resource, pdfDocumentReaderConfig);List<Document> documents = pagePdfDocumentReader.read();vectorStore.add(documents);List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("FunctionTool").topK(5).build());return results;}}
向量庫我是使用的redis-stack:7.2.0-v18。建議使用docker-desktop安裝。
方法里面的查詢方法是比較簡單的用法,詳細復雜的查詢可以查看SpringAi的官網
https://docs.spring.io/spring-ai/reference/api/vectordbs/redis.html
以上就是本次分享的主要內容。