在一些垂直領域以及公司內部信息相關或者實時性相關的大模型應用,就無法直接使用chatGPT。
這個時候,向量知識庫就進入了。
通過坐標向量最接近的即為匹配相關答案。
向量模型定義:將文檔向量化,保證內容越相似的文本,在向量空間中距離越近;
第一步:引入依賴
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-model-openai</artifactId></dependency>
測試輸入一段文本,被存儲在里面的坐標
float[] textFlot = openAiEmbeddingModel.embed("我是中國人");System.out.println("輸出"+ Arrays.toString(textFlot));
第二步,配置:
embedding:options:model: text-embedding-v3dimensions: 1024
存儲文檔的可以用redis, es等;
對于API調用層,都是如下的調用方法
本次案例使用自帶的SimpleVectorStore
@Beanpublic VectorStore vectorStore(OpenAiEmbeddingModel embeddingModel) {return SimpleVectorStore.builder(embeddingModel).build();}
第三步:實現測試
我們需要先將文檔轉為Document,存入向量庫
// 1.創建PDF的讀取器PagePdfDocumentReader reader = new PagePdfDocumentReader(resource, // 文件源PdfDocumentReaderConfig.builder().withPageExtractedTextFormatter(ExtractedTextFormatter.defaults()).withPagesPerDocument(1) // 每1頁PDF作為一個Document.build());// 2.讀取PDF文檔,拆分為DocumentList<Document> documents = reader.read();// 3.寫入向量庫vectorStore.add(documents);
然后進行組裝搜索
SearchRequest request = SearchRequest.builder().query("論語中教育的目的是什么").topK(1).similarityThreshold(0.6).filterExpression("file_name == '知識筆記.pdf'").build();
最后通過調用接口搜索
List<Document> docs = vectorStore.similaritySearch(request);
以上就實現了一個簡單的自帶存儲PDF,然后進行向量接口搜索的demo