SpringAI接入DeepSeek大模型喂饭教程

作者:技术拾光

时间:2026-07-31

浏览:296

基于SpringBoot3.4.4与JDK21,通过OpenAI兼容接口接入DeepSeek大模型。配置APIKey及base-url,创建ChatClientBean与对话服务,实现基于内存会话记忆的多轮智能对话,并整合Hutool工具库与Knife4j接口文档,支持流式响应与高效开发。

文章目录

Spring AI接入DeepSeek大模型

先说几个关键点:Spring AI 官方对 DeepSeek 的支持,走的其实是 OpenAI 兼容接口这条路。因此,接入方式与连接 OpenAI 几乎相同,但模型本身使用的是 DeepSeek 自有的能力。下面将从零开始,一步一步把整个流程走通,实现 Spring AI 接入 DeepSeek 大模型。

一、基础环境准备

JDK 版本必须选择 17 或 21,不能选其他版本。原因是项目要基于最新版 Spring Boot 3 和 Spring AI 框架,这两个都对 JDK 版本有明确要求。不要为了省事使用旧版本,否则编译不过去会更麻烦。

二、新建项目

在 IDEA 中新建项目,选择 Spring Initializr 模板即可。Server URL 注意要填写 start.spring.io/,不要填错。

Java 版本选择 21,Spring Boot 选择 3.4.4。依赖方面,可以先加上 Spring Web 和 Lombok,后续通过 Maven 配置调整即可。

点击创建后,项目骨架就生成了,等待 Maven 把依赖下载完成。

 复制代码<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <version>1.18.36version>
    <optional>trueoptional>
dependency>

三、整合依赖

项目运行起来后,还缺少一些顺手工具。这里整合两个常用库:Hutool 工具库和 Knife4j 接口文档。

Hutool 工具库

这个库在 Java 开发圈中很常见,字符串处理、日期操作、文件处理、加解密、反射、正则匹配等几乎无所不包。参照官方文档引入即可,在 pom.xml 中添加一行依赖:

 复制代码<dependency>
    <groupId>cn.hutoolgroupId>
    <artifactId>hutool-allartifactId>
    <version>5.8.37version>
dependency>

Knife4j 接口文档

Knife4j 是 Swagger 的增强版,界面更友好,支持动态参数调试、分组文档等功能。注意这里要使用 Spring Boot 3.x 版本,因此坐标要选对。

第一步,在 pom.xml 中添加依赖:

 复制代码<dependency>
    <groupId>com.github.xiaoymingroupId>
    <artifactId>knife4j-openapi3-jakarta-spring-boot-starterartifactId>
    <version>4.4.0version>
dependency>

第二步,新建一个 controller 包,编写一个健康检查接口,用于验证接口文档是否正常引入:

 复制代码@RestController
@RequestMapping("/health")
public class HealthController {  @GetMapping("/check")
  public String checkHealth(){
    return "OK";
  }
}

第三步,在 application.yml 中配置接口文档,使其扫描 controller 包:

 复制代码server:
  port: 8080
  servlet:
    context-path: /api######################################################
############          接口文档配置           #####################
######################################################
# 访问地址   ${server.servlet.context-path}/doc.html
springdoc:
  swagger-ui:
    path: /swagger-ui.html
    tags-sorter: alpha
    operations-sorter: alpha
  api-docs:
    path: /v3/api-docs
  group-configs:
    - group: 'default'
      paths-to-match: '/**'
      packages-to-scan: com.qianliuliang.love.controller # 配置扫描哪些包的接口要加入到文档
# knife4j config
knife4j:
  enable: true
  setting:
    language: zh_cn

第四步,启动项目,访问 http://localhost:8080/api/doc.html 即可看到接口文档页面。


第五步,验证项目是否正常,直接在接口文档中发起调试请求,返回 "OK" 就说明项目初始化成功。

SpringAI接入DeepSeek大模型喂饭教程

四、大模型接入

环境配置完成后,接下来就是核心环节——接入 DeepSeek 大模型,实现 Spring AI 与 DeepSeek 的集成。

第一步,在 pom.xml 中引入 Spring AI 的 OpenAI 依赖(再次强调,DeepSeek 兼容 OpenAI 接口):

 复制代码 
<dependency>
    <groupId>org.springframework.aigroupId>
    <artifactId>spring-ai-openai-spring-boot-starterartifactId>
dependency>

第二步,前往 DeepSeek 官网申请 API Key。官网地址为 www.deepseek.com/,操作步骤并不复杂:

  • 点击首页的“API开放平台”入口
  • 进入后依次点击“创建 API key”

SpringAI接入DeepSeek大模型喂饭教程

SpringAI接入DeepSeek大模型喂饭教程

第三步,在 application.yaml 中配置模型信息:

 复制代码spring:
  application:
    name: AI_LOVE
  #ds模型配置
  ai:
    openai:
      api-key: 你的apikey
      base-url: https://api.deepseek.com
      chat:
        options:
          model: deepseek-chat

第四步,配置 ChatClient Bean。先创建一个 config 包,然后新建一个配置类:

 复制代码package com.qianliuliang.love.config;import com.qianliuliang.love.advisor.MyLoggerAdvisor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/**
 * chatClient bean
 */
@Configuration
public class Client {
    /**
     * 基于内存会话记忆的  client
     *
     * @param openAiChatModel
     * @return
     */
    @Bean
    public ChatClient chatClientWithChatMemory(OpenAiChatModel openAiChatModel) {
        // 基于内存的会话记忆,可实现上下文记忆会话
        ChatMemory chatMemory = new InMemoryChatMemory();
        return ChatClient.builder(openAiChatModel)
                .defaultSystem("你是一个智能恋爱助手!名字叫LoveDD") // 系统提示词
                .defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory),
                        new MyLoggerAdvisor()) // 自定义日志
                .build();
    }}

然后,创建一个对话服务类,实现与大模型的交互:

 复制代码import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;/**
 * 简单会话
 */
@Slf4j
@Component
public class SimpleChat {    @Autowired
    private ChatClient chatClient;     /**
     * 普通文本会话
     *
     * @param msg 用户消息
     * @param chatId 会话id
     * @return
     */
    public String doChatWithString(@RequestParam String msg, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .advisors(advisorSpec ->
                        advisorSpec.param("chat_memory_conversation_id", chatId) //会话id/聊天室id
                        .param("chat_memory_response_size", 10))// 支持10轮会话
                .user(msg)
                //.advisors(new SimpleLoggerAdvisor())//日志打印
                .call()
                .chatResponse();
        return chatResponse.getResult().getOutput().getText();// 返回与大模型的对话内容
    }
}

接着,创建 Controller 暴露接口:

 复制代码import com.qianliuliang.love.chat.SimpleChat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private SimpleChat simpleChat;    /**
     * 普通文本会话
     *
     * @param msg
     * @param chatId
     * @return
     */
    @PostMapping("/doChatWithString")
    public String doChatWithString( String msg, String chatId) {
        return simpleChat.doChatWithString(msg, chatId);
    }
}

最后,重启项目,用接口文档测试一下效果。

SpringAI接入DeepSeek大模型喂饭教程

SpringAI接入DeepSeek大模型喂饭教程

SpringAI接入DeepSeek大模型喂饭教程

至此,基本功能已跑通,实现了 Spring AI 接入 DeepSeek 大模型。后续还会分享基于 Redis 的会话记忆、自定义 Advisor、RAG 知识库(文档切割、Embedding 向量化、向量存储)、Tool Calling 以及 MCP 等进阶内容。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›