Spring AI 调用本地部署的大模型主要通过集成 Ollama(本地大模型运行框架)实现,结合 Spring Boot 的模块化设计提供企业级调用支持。以下是详细步骤和实现原理:
ollama pull llama3
或 ollama pull deepseek-r1:7b
)。http://localhost:11434
,确认接口响应正常。通过 Docker 简化环境配置,例如:
docker run -d -p 11434:11434 --name ollama ollama/ollama:0.6.2
docker exec -it ollama ollama pull deepseek-r1:7b # 拉取模型
此方式适合需要隔离环境或使用 GPU 加速的场景。
在 pom.xml
中引入 Spring AI 的 Ollama 模块:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
同时需依赖 Spring Boot 3.2.x 或更高版本。
在 application.yml
中指定模型服务地址和默认模型:
spring:
ai:
ollama:
base-url: http://localhost:11434 # Ollama 服务地址
chat:
model: deepseek-r1:7b # 默认调用的模型名称
此配置使 Spring AI 自动注入 OllamaChatClient
。
创建 REST 接口接收请求并转发至大模型:
@RestController
public class OllamaController {
@Autowired
private OllamaChatClient chatClient;
// 普通文本调用
@GetMapping("/ai/chat")
public String chat(@RequestParam String message) {
Prompt prompt = new Prompt(message);
return chatClient.call(prompt).getResult().getOutput().getContent();
}
// 流式调用(适用于实时对话)
@GetMapping("/ai/chat/stream")
public Flux<String> streamChat(@RequestParam String message) {
Prompt prompt = new Prompt(message);
return chatClient.stream(prompt)
.map(response -> response.getResult().getOutput().getContent());
}
}
流式调用通过 Flux
返回逐句生成的文本,适合需要实时响应的场景。
通过 Prompt
对象支持复杂交互:
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("你是一个专业的助手");
Message systemMessage = systemPromptTemplate.createMessage(Map.of("prompt", "请用中文回答"));
Prompt prompt = new Prompt(List.of(new UserMessage(message), systemMessage));
可结合 SystemPromptTemplate
控制模型输出格式。
使用 Redis 缓存上下文信息,实现多轮对话:
@Autowired
private RedisTemplate<String, String> redisTemplate;
public String chatWithContext(String sessionId, String message) {
String history = redisTemplate.opsForValue().get(sessionId);
String fullMessage = history + "\nUser: " + message;
// 调用模型并更新缓存
redisTemplate.opsForValue().set(sessionId, fullMessage);
return chatClient.call(new Prompt(fullMessage)).getResult().getOutput().getContent();
}
此方案适合企业内部知识库等场景。
OllamaApi
直接调用低层 API,减少框架开销。application.yml
中添加 spring.ai.ollama.timeout=60s
防止长请求阻塞。访问 http://localhost:8080/ai/chat?message=你好
,返回模型生成的文本。
流式接口可通过 SSE(Server-Sent Events)在前端实时展示生成过程。
~/.ollama/models
)。base-url
为 Docker 容器 IP。ollama run <模型> --num-gpu-layers 20
启用 GPU 卸载。通过 Spring AI + Ollama,开发者能以 低代码 方式快速集成本地大模型,同时享受 Spring 生态的高并发、安全性和企业级维护能力。此方案适用于数据隐私敏感、需要离线部署或定制化微调的场景,如金融风控、医疗咨询等。
版权说明:如非注明,本站文章均为 扬州驻场服务-网络设备调试-监控维修-南京泽同信息科技有限公司 原创,转载请注明出处和附带本文链接。
请在这里放置你的在线分享代码