简介:本文详细阐述了如何通过Spring AI与Ollama的协同工作,快速构建并调用deepseek-r1模型的API服务,助力开发者高效集成AI能力。
随着AI技术的快速发展,企业对大模型的应用需求日益增长。deepseek-r1作为一款高性能的语言模型,具备强大的文本生成与理解能力,但直接调用其原生API可能面临以下问题:
在此背景下,Spring AI(Spring生态的AI抽象层)与Ollama(轻量级本地模型运行框架)的结合提供了理想解决方案:通过Ollama简化模型部署,利用Spring AI快速构建RESTful API,实现deepseek-r1的高效服务化。
Spring AI是Spring生态中用于简化AI模型集成的工具,核心特性包括:
AiClient接口统一调用。Ollama是一个开源工具,专注于在本地运行大语言模型,优势包括:
deepseek-r1是深度求索公司推出的开源模型,特点如下:
# Linux/macOScurl -fsSL https://ollama.com/install.sh | sh# Windows(PowerShell)irm https://ollama.com/install.ps1 | iex
ollama pull deepseek-r1:7b # 7B参数版本# 或ollama pull deepseek-r1:13b # 13B参数版本
ollama run deepseek-r1:7b --port 11434 # 默认端口为11434
通过Spring Initializr生成项目,添加以下依赖:
在application.properties中配置Ollama地址:
spring.ai.ollama.base-url=http://localhost:11434
创建DeepSeekService类,注入OllamaAiClient:
import org.springframework.ai.client.AiClient;import org.springframework.ai.prompt.Prompt;import org.springframework.ai.prompt.PromptTemplate;import org.springframework.stereotype.Service;@Servicepublic class DeepSeekService {private final AiClient aiClient;public DeepSeekService(AiClient aiClient) {this.aiClient = aiClient;}public String generateText(String prompt) {PromptTemplate template = PromptTemplate.builder().template("{prompt}").build();Prompt aiPrompt = template.createPrompt(Map.of("prompt", prompt));return aiClient.generate(aiPrompt).getGeneratedText();}}
import org.springframework.web.bind.annotation.*;@RestController@RequestMapping("/api/deepseek")public class DeepSeekController {private final DeepSeekService deepSeekService;public DeepSeekController(DeepSeekService deepSeekService) {this.deepSeekService = deepSeekService;}@PostMapping("/generate")public String generate(@RequestBody String prompt) {return deepSeekService.generateText(prompt);}}
使用curl或Postman发送请求:
curl -X POST http://localhost:8080/api/deepseek/generate \-H "Content-Type: text/plain" \-d "解释量子计算的基本原理"
实现类似ChatGPT的逐字输出效果:
public Flux<String> streamGenerate(String prompt) {PromptTemplate template = PromptTemplate.builder().template("{prompt}").build();Prompt aiPrompt = template.createPrompt(Map.of("prompt", prompt));return aiClient.streamGenerate(aiPrompt).map(AiMessage::getText);}
通过配置动态切换模型:
@Configurationpublic class AiClientConfig {@Bean@ConditionalOnProperty(name = "spring.ai.model", havingValue = "deepseek")public AiClient deepseekAiClient() {return OllamaAiClient.builder().baseUrl("http://localhost:11434").build();}@Bean@ConditionalOnProperty(name = "spring.ai.model", havingValue = "llama2")public AiClient llamaAiClient() {return OllamaAiClient.builder().baseUrl("http://localhost:11435") # 另一端口.build();}}
spring-ai-ollama的版本与Spring Boot的兼容性。通过Spring AI与Ollama的组合,开发者可以快速实现deepseek-r1的API服务化,兼顾性能与灵活性。未来方向包括:
此方案不仅降低了AI落地的技术门槛,更为企业提供了可控、高效的AI基础设施。