Spring AI
The Spring AI 项目旨在成为 Java 世界中类似 LangChain 的工具。
将 Spring AI 与 Spring Data Neo4j 结合,可在现有领域模型的基础上构建图形,并通过向量嵌入进行丰富。
安装
如果你使用 Spring Initializr,可以将你选择的 Spring AI 模型和 Neo4j Vector Database 作为依赖添加到项目中,系统会自动拉取所有相关组件。
如果手动添加依赖,Spring AI 仍未正式发布为通用库,因此需要在 pom.xml 中加入依赖以及快照和里程碑仓库,具体做法参见 Getting Started 文档。
接下来需要添加 Neo4j 向量数据库的配置,同时还要配置自定义驱动和嵌入客户端。最简便的方式是在主应用类中为这些组件分别创建 Spring Bean。文档 中有提及,但未提供完整代码。下面示例展示了如何配置 Neo4j 向量数据库(请根据实际情况修改 vectorStore Bean)。
@SpringBootApplication
public class SpringAiStarterKitApplication {
public static void main(String[] args) {
SpringApplication.run(SpringAiStarterKitApplication.class, args);
}
}
现在向量存储已配置完毕,我们可以通过三步流程使用 Spring AI 实现检索增强生成(RAG)。
-
调用向量相似度搜索方法,检索最相似的文档。
-
将相似文档作为输入,执行检索查询,从图中拉取相关实体。
-
把相似文档(以及它们关联的图实体)作为提示输入,交给 LLM 生成响应。
下面的代码片段演示了如何使用 Spring AI 与 Neo4j 向量存储进行 RAG。
@GetMapping("/chat")
String getGeneratedResponse(@RequestParam String question) {
List<Document> results = vectorStore.similaritySearch(question);
System.out.println("Id list to graph: " + results.stream()
.map(Document::getId)
.collect(Collectors.toList()));
List<Chunk> docList = repo.getRelatedEntitiesForSimilarChunks(results.stream()
.map(Document::getId)
.collect(Collectors.toList()));
var template = new PromptTemplate("""
You are a helpful question-answering agent. Your task is to analyze
and synthesize information from the top result from a similarity search
and relevant data from a graph database.
Given the user's query: {question}, provide a meaningful and efficient answer based
on the insights derived from the following data:
{graph_result}
""").create(Map.of("question", question,
"graph_result", docList.stream().map(chunk -> chunk.toString()).collect(Collectors.joining("\n"))));
System.out.println("----- PROMPT -----");
System.out.println(template);
return client.prompt(template).call().content();
文档
Neo4j 向量集成文档可在 Spring AI Reference Guide 中查阅。
入门套件
在任何新技术领域入门都可能让人感到畏惧。Neo4j 正在推出一些面向 GenAI 与 Neo4j 的预包装解决方案,旨在通过提供包含 Spring AI 在内的关键技术入门套件项目,让上手过程更加容易。你可以在 Github 上找到 Spring AI 入门套件代码,以及一篇包含更多信息的博客文章。