使用 Ollama 本地模型和 Spring AI Alibaba 构建 RAG 应用
· 阅读需 8 分钟
RAG 应用架构概述
核心组件
- Spring AI:Spring 生态的 Java AI 开发框架,提供统一 API 接入大模型、向量数据库等 AI 基础设施。
- Ollama:本地大模型运行引擎(类似于 Docker),支持快速部署开源模型。
- Spring AI Alibaba:对 Spring AI 的增强,集成 DashScope 模型平台。
- Elasticsearch:向量数据库,存储文本向量化数据,支撑语义检索。
模型选型
- Embedding 模型:nomic-embed-text:latest,用于将文本数据向量化。
- Ollama Chat 模型:deepseek-r1:8b,生成最终答案。
环境准备
启动 Ollama 服务
Docker Compose 启动 Ollama:(同时启动一个模型前端系统,和 Ollama 模型交互。)
services:
ollama:
container_name: ollama
image: ollama/ollama:latest
ports:
- 11434:11434
open-webui:
image: ghcr.io/open-webui/open-webui:main
container_name: open-webui
ports:
- 3005:8080
environment:
- 'OLLAMA_BASE_URL=http://host.docker.internal:11434'
# 允许容器访问宿主机网络
extra_hosts:
- host.docker.internal:host-gateway
下载模型
执行以下命令:
docker exec -it ollama ollama pull deepseek-r1:8b
docker exec -it ollama ollama pull nomic-embed-text:latest
在 open-webui 中调用 deepseek-r1:8b 模型:

部署 Elasticsearch
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:8.16.1
container_name: elasticsearch
privileged: true
environment:
- "cluster.name=elasticsearch"
- "discovery.type=single-node"
- "ES_JAVA_OPTS=-Xms512m -Xmx1096m"
- bootstrap.memory_lock=true
volumes:
- ./config/es.yaml:/usr/share/elasticsearch/config/elasticsearch.yml
ports:
- "9200:9200"
- "9300:9300"
deploy:
resources:
limits:
cpus: "2"
memory: 1000M
reservations:
memory: 200M
准备 es 启动的配置文件:
cluster.name: docker-es
node.name: es-node-1
network.host: 0.0.0.0
network.publish_host: 0.0.0.0
http.port: 9200
http.cors.enabled: true
http.cors.allow-origin: "*"
bootstrap.memory_lock: true
# 关闭认证授权 es 8.x 默认开启
xpack.security.enabled: false
至此,便完成搭建一个简单 RAG 应用的所有环境准备步骤。下面开始搭建项目。
项目配置
依赖引入
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.3.4</version>
</dependency>
<!-- Spring AI Ollama Starter -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
<version>1.0.0-M5</version>
</dependency>
<!-- 向量存储 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-elasticsearch-store</artifactId>
<version>1.0.0-M5</version>
</dependency>
<!-- PDF 解析 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-pdf-document-reader</artifactId>
<version>1.0.0-M5</version>
</dependency>
核心配置
spring:
ai:
# ollama 配置
ollama:
base-url: http://127.0.0.1:11434
chat:
model: deepseek-r1:8b
embedding:
model: nomic-embed-text:latest
# 向量数据库配置
vectorstore:
elasticsearch:
index-name: ollama-rag-embedding-index
similarity: cosine
dimensions: 768
elasticsearch:
uris: http://127.0.0.1:9200
其中:
- index-name 为 es 向量索引名;
- dimensions 为向量模型生成的向量维度(需要和向量模型生成的向量维度一致,默认值为 1576);
- similarity 定义了用于衡量向量之间相似度的算法或度量方式,这里使用余弦相似度,使用高维稀疏向量。
如果您想自定义 es 的实例化配置,需要引入 spring-ai-elasticsearch-store:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-elasticsearch-store</artifactId>
<version>1.0.0-M5</version>
</dependency>
�在项目中通过自定义配置 bean 实现。
Prompt Template
你是一个MacOS专家,请基于以下上下文回答:
---------------------
{question_answer_context}
---------------------
请结合给定上下文和提供的历史信息,用中文 Markdown 格式回答,若答案不在上下文中请明确告知。
核心实现
文本向量化
在 Spring AI 和 Spring AI Alibaba 中,几乎可以将任意数据源作为知识库来源。此例中使用 PDF 作为知识库文档。
Spring AI Alibaba 提供了 40+ 的 document-reader 和 parser 插件。用来将数据加载到 RAG 应用中。
public class KnowledgeInitializer implements ApplicationRunner {
// 注入 VectorStore 实例,负责向量化数据的增查操作
private final VectorStore vectorStore;
// 向量数据库客户端,此处使用 es
private final ElasticsearchClient elasticsearchClient;
// .....
@Override
public void run(ApplicationArguments args) {
// 1. load pdf resources.
List<Resource> pdfResources = loadPdfResources();
// 2. parse pdf resources to Documents.
List<Document> documents = parsePdfResource(pdfResources);
// 3. import to ES.
importToES(documents);
}
private List<Document> parsePdfResource(List<Resource> pdfResources) {
// 按照指定策略切分文本并转为 Document 资源对象
for (Resource springAiResource : pdfResources) {
// 1. parse document
DocumentReader reader = new PagePdfDocumentReader(springAiResource);
List<Document> documents = reader.get();
logger.info("{} documents loaded", documents.size());
// 2. split trunks
List<Document> splitDocuments = new TokenTextSplitter().apply(documents);
logger.info("{} documents split", splitDocuments.size());
// 3. add res list
resList.addAll(splitDocuments);
}
}
// ......
}
�至此,便完成了将文本数据转为向量数据的过程。
RAG 服务层
接下来,将使用 Spring AI 中的 Ollama Starter 来完成和模型交互。构建 RAG 应用。
�AIRagService.java
@Service
public class AIRagService {
// 引入 system prompt tmpl
@Value("classpath:/prompts/system-qa.st")
private Resource systemResource;
// 注入相关 bean 实例
private final ChatModel ragChatModel;
private final VectorStore vectorStore;
// 文本过滤,增强向量检索精度
private static final String textField = "content";
// ......
public Flux<String> retrieve(String prompt) {
// 加载 prompt tmpl
String promptTemplate = getPromptTemplate(systemResource);
// 启用混合搜索,包括嵌入和全文搜索
SearchRequest searchRequest = SearchRequest.builder().
topK(4)
.similarityThresholdAll()
.build();
// build chatClient,发起大模型服务调用。
return ChatClient.builder(ragChatModel)
.build().prompt()
.advisors(new QuestionAnswerAdvisor(
vectorStore,
searchRequest,
promptTemplate)
).user(prompt)
.stream()
.content();
}
}
RAG 服务接口层
编写用户请求接口,处理用户请求,调用 service 获得大模型响应:
@RestController
@RequestMapping("/rag/ai")
public class AIRagController {
@Resource
public AIRagService aiRagService;
@GetMapping("/chat/{prompt}")
public Flux<String> chat(
@PathVariable("prompt") String prompt,
HttpServletResponse response
) {
// 设置响应编码,方式 stream 响应乱码。
response.setCharacterEncoding("UTF-8");
if (!StringUtils.hasText(prompt)) {
return Flux.just("prompt is null.");
}
return aiRagService.retrieve(prompt);
}
}
请求演示
这里以 我现在是一个mac新手,我想配置下 mac 的触控板,让他变得更好用,你有什么建议吗?问题为例,可以看到直接调用模型的回答是比较官方,实用性不高。
从 open-webui 直接调用

