Java 如何调用本地部署的deepseek

1,758 阅读5分钟

写在前面

经常逛Spring官网(docs.spring.io/spring-ai/r…)的小伙伴会发现,

Spring 已经支持接入DeepSeek了。

官宣接入deepseek

DeepSeek AI provides the open-source DeepSeek V3 model, renowned for its cutting-edge reasoning and problem-solving capabilities.

Spring AI integrates with DeepSeek AI by reusing the existing OpenAI client. To get started, you’ll need to obtain a DeepSeek API Key, configure the base URL, and select one of the supported models.

翻译过来就是

DeepSeek AI提供了开源的DeepSeek V3模型,该模型以其先进的推理和解决问题的能力而闻名。

Spring AI通过与现有OpenAI客户端复用的方式与DeepSeek AI集成。

要接入DeepSeek,您需要获取一个DeepSeekAPI的API KEY,配置接入地址,并选择一种模型即可

一、调用效果

调用效果展示

二、Spring AI 与 DeepSeek 的集成背景

不管是Spring 官网还是DeepSeek API 文档(api-docs.deepseek.com/zh-cn/)中都提到 DeepSeek API 使用与 OpenAI 兼容的 API格式。

与OpenAPI兼容的API格式

所以,我们只需要照抄接入ChatGpt的就可以了~ 而与ChatGPT 或者其他大模型对接是通过Spring AI 来完成的。

Spring AI 是什么呢?

Spring AI 是 Spring生态中的一个新兴项目,旨在为 Java集成各类 AI模型提供统一的抽象层。

它通过隐藏底层模型的实现细节,让开发者能够以最少的代码调用各种 AI 服务。

目前,Spring AI已经支持OpenAI、Azure AI、Hugging Face 等多个 AI 平台,而 DeepSeek 的加入进一步丰富了其功能

三、Java 接入DeepSeek步骤

3.1 获取API KEY

首先,我们需要到DeepSeek 开发平台(platform.deepseek.com/api_keys)申请API KEY

申请api key

这是使用 DeepSeek 服务的关键凭证,必须妥善保管。不要与他人共享你的 API key,或将其暴露在浏览器或其他客户端代码中

3.2 创建spring boot 项目

通过 Spring Initializr 创建一个新的项目

创建springboot 项目

3.3 添加依赖

在 pom.xml 文件中,添加 Spring AI 的依赖。目前,Spring AI 通过 OpenAI 客户端与 DeepSeek 集成,因此需要引入以下依赖:

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

3.4 配置 DeepSeek API

在 application.properties 或 application.yml 文件中,配置 DeepSeek 的 API密钥和请求 URL

  • deepseek-chat 模型已全面升级为 DeepSeek-V3,接口不变。 通过指定 model='deepseek-chat' 即可调用 DeepSeek-V3。
  • deepseek-reasoner 是 DeepSeek 最新推出的推理模型 DeepSeek-R1。通过指定 model='deepseek-reasoner',即可调用 DeepSeek-R1。
spring:
  ai:
    openai:
      api-key: sk-your-deepseek-key-here
      base-url: https://api.deepseek.com
      chat:
        options:
          model: deepseek-reasoner

3.5 编写接口

@RestController
@RequestMapping("/ai")
public class DeepSeekController {
​
    private final ChatClient chatclient;
​
    // 构造方法,用于构造chatclient 实列
    public DeepSeekController (ChatClient.Builder chatClientBuilder){
        this.chatclient =chatClientBuilder.build();
    }
​
​
    @GetMapping("/chat")
    public String chat(@RequestParam(value = "message") String message) {
        return chatclient.prompt(message).call().content();
    }
}

3.6 测试一下

启动项目,浏览器中 http://localhost:8080/ai/chat?message=对话内容 按照这个格式即可与deepseek对话

① 讲一个笑话

讲一个笑话

② 请用Java写一段线程安全的单例模式,并故意埋三个常见错误

请用Java写一段线程安全的单例模式,并故意埋三个常见错误

③ 简单介绍下程序员晓凡是谁?

程序员晓凡是谁

四、调用本地部署的DeepSeek

在之前的文章中,已经手把手教小伙伴如何使用ollama将DeepSeek 部署到自己电脑上。

使用该方法部署算是最简单的一种部署方式了,忘记了的小伙伴,可以点击下面链接复习一下~

4.1 ollama 常用命令

我们需要简单知道下ollama 的常用命令,方便我们启停本地大模型

① 查看ollama 版本信息

ollama -v

② 启动ollama服务

ollama serve

③ 查看正在运行的大模型

ollama ps

④ 查看本地大模型列表

ollama list

⑤ 运行大模型

# deepseek-r1:8b 为大模型版本号
# 如果本地不存在该模型,会先拉取
ollama run deepseek-r1:8b

⑥ 删除模型

ollama rm 模型名称

⑦ 停止运行模型

ollama stop

4.2 启动大模型

首先,按照上面的命令启动本地安装的大模型,ollama ps 确认大模型正在运行中

查看正在运行的大模型列表

大模型启动之后会占用11434 端口,开放的接口地址是:http://localhost:11434/api/chat

我们可以先通过postman 调用试试

入参如下:

{
   "model": "deepseek-r1:8b",
   "messages": [
       {"role": "user", "content": "用中文解释量子计算原理"}
   ],
   "stream": false,
   "options": {
       "temperature": 0.7,
       "num_ctx": 4096 
   }
}

postman 调用本地大模型

4.3 Java项目中调用本地大模型

① 添加依赖

我们这里是同过ollama部署的deepseek ,所以要添加如下依赖

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>

② 配置 DeepSeek API

在 application.properties 或 application.yml 文件中,配置 DeepSeek 的请求 URL及模型

spring:
  ai:
    ollama:
      base-url: http://localhost:11434
      chat:
        model: deepseek-r1:8b  # 本地部署的大模型

③编写接口

为了模仿官方deepseek对话模型,这里接口书写方式我们采用流式输出方式

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*")
public class DeepSeekController {
    private static final Logger logger = LoggerFactory.getLogger(DeepSeekController.class);

    private final ChatClient chatclient;

    public DeepSeekController(ChatClient.Builder chatClientBuilder) {
        this.chatclient = chatClientBuilder.build();
    }

    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
    public ResponseEntity<Flux<String>> chat(@RequestParam(value="message") String message) {
        try {
            Flux<String> response = chatclient.prompt(message).stream().content();
            // 打印响应数据
            response.subscribe(data -> logger.info("Response data: {}", data));
            return ResponseEntity.ok()
                    .contentType(MediaType.TEXT_EVENT_STREAM) // 设置内容类型为文本事件流
                    .header(HttpHeaders.CONTENT_ENCODING, "utf-8") // 设置字符编码
                    .body(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}

④ 测试

为了演示流式数据输出调用,晓凡用element-ui+vue仿照微信聊天界面写了一个简单调用页面,效果如下所示

流式输出效果

五、代码下载

以上涉及到的demo 晓凡已经将代码上传到gitee,感兴趣的小伙伴可以

gitee: gitee.com/xiezhr/deep…

gitee地址

考虑到部分小伙伴可能没有注册gitee,晓凡把代码也传到网盘了「deepseek-chat-demo.zip」 链接:pan.quark.cn/s/2bf88a3ac…

本期内容到这儿就结束了,希望对您有所帮助!

我们下期再见 ヾ(•ω•`)o (●'◡'●)