本地大模型(DeepSeek / 千问)接入 Spring AI 详解

随着大语言模型(LLM)的普及,越来越多的开发者希望在本地部署模型(如 DeepSeek、通义千问 Qwen)并将其集成到 Spring 应用中。Spring AI 是 Spring 生态推出的 AI 开发框架,它提供了统一的 API 来对接各种 AI 模型。本文将详细讲解如何将本地运行的 DeepSeek 或千问模型接入 Spring AI。


1. Spring AI 简介

Spring AI 是 Spring 官方提供的 AI 工程化框架,它抽象了与 AI 模型交互的常见模式,支持:

  • 聊天模型(Chat Model):如 OpenAI ChatGPT、Azure OpenAI、Hugging Face 等。
  • 嵌入模型(Embedding Model):用于向量化文本。
  • 提示词模板(Prompt Template)和输出解析器。
  • 向量数据库集成等。

Spring AI 通过 ChatClientEmbeddingClient 等接口与具体模型解耦,我们可以通过配置来切换不同的模型提供商。


2. 本地大模型部署方案

要将 DeepSeek 或千问模型接入 Spring AI,首先需要在本地运行这些模型。常见的本地部署工具有:

  • Ollama:支持多种模型(包括 qwen、deepseek-r1 等),提供 REST API,兼容 OpenAI 格式。
  • vLLM:高性能推理引擎,支持 Qwen、DeepSeek 等,提供 OpenAI 兼容 API。
  • LocalAI:模拟 OpenAI API 的本地推理服务。
  • llama.cpp 及其衍生项目(如 llama-server)。

本文以 Ollama 为例,因为它简单易用,且广泛支持各类模型。

2.1 使用 Ollama 运行 DeepSeek / Qwen
  1. 安装 Ollama
    访问 ollama.com 下载并安装。

  2. 拉取模型

    # 拉取 DeepSeek-R1(例如 1.5B 版本)
    ollama pull deepseek-r1:1.5b
    
    # 拉取通义千问(例如 7B 版本)
    ollama pull qwen2.5:7b
    
  3. 启动模型服务
    Ollama 默认在后台运行,提供 REST API 端点 http://localhost:11434

  4. 验证服务

    curl http://localhost:11434/api/generate -d '{
      "model": "deepseek-r1:1.5b",
      "prompt": "Hello",
      "stream": false
    }'
    

    返回正常即表示服务可用。

注意:Ollama 的 API 格式与 OpenAI 略有不同,但 Spring AI 的 OpenAI 适配器可以通过配置 base-url 直接对接 Ollama(因为 Ollama 也提供了部分 OpenAI 兼容端点,如 /v1/chat/completions)。


3. Spring Boot 项目集成 Spring AI

3.1 创建 Spring Boot 项目

使用 Spring Initializr(或 IDE)创建项目,并添加以下依赖:

  • Spring Web(用于测试)
  • Spring AI(目前最新稳定版为 0.8.1)

pom.xml 中添加 Spring AI 的 BOM 和依赖:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-bom</artifactId>
            <version>0.8.1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    </dependency>
</dependencies>

注意:Spring AI 的 OpenAI Starter 默认用于连接 OpenAI 服务,但我们可以通过配置覆盖 base-url,使其指向本地 Ollama 服务。

3.2 配置文件 application.yml
spring:
  ai:
    openai:
      base-url: http://localhost:11434  # Ollama 的地址
      api-key: dummy                     # Ollama 不需要真实 key,但必须非空
      chat:
        options:
          model: deepseek-r1:1.5b        # 指定模型名称,根据实际情况修改
          temperature: 0.7
3.3 编写 Chat 服务
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        Prompt prompt = new Prompt(message);
        ChatResponse response = chatClient.call(prompt);
        return response.getResult().getOutput().getContent();
    }
}
3.4 启动测试

启动 Spring Boot 应用,访问 http://localhost:8080/chat?message=你好,即可看到本地模型返回的响应。


4. 高级配置与自定义

4.1 使用不同的模型

在配置文件中修改 spring.ai.openai.chat.options.model 即可切换模型,例如 qwen2.5:7b

4.2 配置超时和重试
spring:
  ai:
    openai:
      base-url: http://localhost:11434
      api-key: dummy
      chat:
        options:
          model: qwen2.5:7b
      client:
        connect-timeout: 10s
        read-timeout: 60s
4.3 多模型配置(Spring AI 1.0.0+)

Spring AI 1.0.0 支持多模型配置,可以同时连接多个端点。但当前 0.8.1 版本可通过自定义 ChatClient Bean 实现。

4.4 使用流式响应

Spring AI 支持流式输出,只需将接口改为返回 Flux<String>

import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.StreamingChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
public class StreamingController {

    private final StreamingChatClient streamingChatClient;

    public StreamingController(StreamingChatClient streamingChatClient) {
        this.streamingChatClient = streamingChatClient;
    }

    @GetMapping(value = "/stream", produces = "text/event-stream")
    public Flux<String> stream(@RequestParam String message) {
        Prompt prompt = new Prompt(message);
        return streamingChatClient.stream(prompt)
                .map(chatResponse -> chatResponse.getResult().getOutput().getContent());
    }
}

5. 其他本地推理引擎的配置

5.1 vLLM 方案

vLLM 启动时默认提供 OpenAI 兼容 API(端口 8000)。假设你已部署了 Qwen 模型:

python -m vllm.entrypoints.openai.api_server \
    --model Qwen/Qwen2.5-7B-Instruct \
    --port 8000

Spring AI 配置只需修改 base-url:

spring:
  ai:
    openai:
      base-url: http://localhost:8000
      api-key: EMPTY
      chat:
        options:
          model: Qwen/Qwen2.5-7B-Instruct
5.2 LocalAI

LocalAI 同样兼容 OpenAI API,配置方式类似。


6. 常见问题与解决

6.1 API Key 必须填写

Spring AI OpenAI Starter 要求提供 api-key,即使本地服务不需要验证,也需填写任意非空字符串(如 dummy)。

6.2 模型名称必须正确

确保配置的模型名称与 Ollama 中拉取的名称完全一致(可通过 ollama list 查看)。

6.3 流式响应不工作

检查 Ollama 是否支持流式(默认支持),Spring AI 的 StreamingChatClient 会自动处理。

6.4 请求超时

对于长文本生成,可能需要增加 read-timeout

6.5 无法连接

确认 Ollama 服务已启动:ollama serve(通常作为系统服务运行)。


7. 总结

通过 Spring AI 的 OpenAI 适配器,我们可以轻松地将本地部署的 DeepSeek、通义千问等模型接入 Spring Boot 应用,只需修改 base-url 指向本地推理端点。这种方式充分利用了 Spring AI 的统一抽象,使代码与具体模型解耦,便于后期切换云服务或本地模型。

关键步骤:

  1. 使用 Ollama/vLLM 等工具本地运行模型。
  2. 在 Spring Boot 项目中引入 spring-ai-openai-spring-boot-starter
  3. 配置 base-url 和模型名称。
  4. 注入 ChatClientStreamingChatClient 进行调用。

现在,你可以将强大的本地大模型能力无缝集成到你的 Spring 应用中,打造私有化、低延迟的 AI 服务。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐