开发者

Spring AI与DeepSeek实战一之快速打造智能对话应用

目录
  • 一、概述
  • 二、申请DeepSeek的API-KEY
  • 三、项目搭建
    • 3.1. 开发环境要求
    • 3.2. maven配置
    • 3.3. 配置 API-KEY
    • 3.5. 创建对话接口
    • 3.6. 切换模型
    • 3.7. 使用prompt模板
    • 3.8. 使用流式对话
  • 四、总结
    • 五、完整代码

      一、概述

      在 AI 技术蓬勃发展的今天,国产大模型 DeepSeek 凭借其 低成本高性能 的特点,成为企业智能化转型的热门选择。而 Spring AI 作为 Java 生态的 AI 集成框架,通过统一API、简化配置等特性,让开发者无需深入底层即可快速调用编程各类 AI 服务。本文将手把手教你通过 spring-ai 集成 DeepSeek 接口实现普通对话与流式对话功能,助力你的 Java 应用轻松接入 AI 能力!

      二、申请DeepSeek的API-KEY

      相较于直接调用 DeepSeek 官方的 API,阿里云百炼基于阿里云强大的云计算基础设施,提供了高可用性和稳定性的服务,并且支持程序运行时动态切换 模型广场 中的任意大模型。

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      登录阿里云,进入 阿里云百炼 的页面:

      https://bailian.console.aliyun.com/?apiKey=1#/api-key

      创建自己的 API-KEY

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      三、项目搭建

      3.1. 开发环境要求

      • JDK 17+
      • Spring Boot 3.2.x及以上

      3.2. maven配置

      Spring Boot 项目的 pom.XML 中添加 spring-ai 依赖

      <dependency>
          <groupId>com.alibaba.cloud.ai</groupId>
          <artifactId>spring-ai-alibaba-starter</artifactId>
      </dependency>

      增加仓库的配置

      <repositories>
          <repository>
              <id>alimaven</id>
              <url>https://maven.aliyun.com/repository/public</url>
          </repository>
          <repository>
              <id>spring-milestones</id>
              <url>https://repo.spring.io/milestone</url>
              <snapshots>
                  <enabled>false</enabled>
              </snapshots>
          </repository>
          <repository>
              <id>spring-snapshots</id>
              <url>https://repo.spring.io/snapshot</url>
              <snapshots>
                  <enabled>false</enabled>
              </snapshots>
          </repository>
      </repositories>

      3.3. 配置 API-KEY

      application.yml 中添加以下配置:

      spring:
        ai:
          dashscope:
            api-key: sk-xxxxxx

      api-key 配置在阿里云百炼里申请的api-key 3.4. 创建ChatClient对象

      private final ChatClient chatClient;
      public ChatController(ChatClient.Builder builder) {
          String sysPrompt = """
              你是一个博学的智能聊天助手,请根据用户提问回答。
              请讲中文。
              今天的日期是 {current_date}。
              """;
          this.chatClient = builder
                  .defaultSystem(sysPrompt)
                  .defaultOptions(
                          DashScopeChatOptions.builder()
                                  /**
                                   * 值范围:[0, 2),系统默认值0.85。不建议取值为0,无意义
                                   */
                          编程        .withTemperature(1.3)
                                  .withModel("deepseek-v3")
                                  .build()
                  )
                  .build();
      }
      • defaultSystem 指定系统 prompt 来约束大模型的行为或者提供一些上下文信息,如这里告诉大模型今天的日期是多少,支持占位符python
      • defaultOptions 配置模型的参数
        • withTemperature 用于控制随机性和多样性的程度,值越高大模型回复的内容越丰富越天马行空
        • withModel 配置模型广场中的模型名称,这里填写 deepseek-v3

      模型广场的模型名称清单:https://help.aliyun.com/zh/model-studio/getting-started/models

      3.5. 创建对话接口

      @GetMapping(value = "/chat")
      public String chat(@RequestParam String input, HttpServletResponse re编程客栈sponse) {
          // 设置字符编码,避免乱码
          response.setCharacterEncoding("UTF-8");
          return chatClient.prompt().user(input)
                  .system(s -> s.param("current_date", LocalDate.now().toString()))
                  .call()
                  .content();
      }

      每次调用接口时,通过 system 来给 current_date 占位符动态赋值。

      调用示例

      问身份

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      问日期

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      3.6. 切换模型

      @GetMapping(value = "/chat")
      public String chat(@RequestParam String input, @RequestParam(required = false) String model, HttpServletResponse response) {
          response.setCharacterEncoding("UTF-8");
          if (StrUtil.isEmpty(model)) {
              model = "deepseek-v3";
          }
          return chatClient.prompt().user(input)
                  .system(s -> s.param("current_date", LocalDate.now().toString()))
                  .options(DashScopeChatOptions.builder().withModel(model).build())
                  .call()
                  .content();
      }

      使用 withModel 来配置模型名称

      调用示例

      切换deepseek-r1模型

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      切换通义千问模型

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      3.7. 使用prompt模板

      通过 PromptTemplate 可以编辑复杂的提示词,并且也支持占位符

      @GetMapping(value = "/chatTemp")
      public String chatTemp(@RequestParam String input, HttpServletResponse response) {
          response.setCharacterEncoding("UTF-8");
          // 使用PromptTemplate定义提示词模板
          PromptTemplate promptTemplate = new PromptTemplate("请逐步解释你的思考过程: {input}");
          Prompt prompt = promptTemplate.create(Map.of("input", input));
          return chatClient.prompt(prompt)
                  .system(s -> s.param("current_date", LocalDate.now().toString()))
                  .call()
                  .content();
      }

      这里提出让 deepseek-v3 进行逐步拆分思考,并把思考过程返回。

      调用示例

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      可以看到大模型会拆分多步来进行推论结果。

      3.8. 使用流式对话

      当前接口需等待大模型完全生成回复内容才能返回,这用户体验并不好。为实现类似 ChatGPT 的逐句实时输出效果,可采用流式传输技术(Streaming Response)。

      @GetMapping(value = "/streamChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
      public Flux<String> streamChat(@RequestParam String input, HttpServletResponse response) {
          response.setCharacterEncoding("UTF-8");
          // 使用PromptTemplate定义提示词模板
          PromptTemplate promptTemplate = new PromptTemplate("请逐步解释你的思考过程: {input}");
          Prompt prompt = promptTemplate.create(Map.of("input", input));
          return chatClient.prompt(prompt)
                  .system(s -> s.param("current_date", LocalDate.now().toString()))
                  .stream()
                  .content()
                  .concatWith(Flux.just("[DONE]"))
                  .onErrorResume(e -> Flux.just("ERROR: " + e.getMessage(), "[DONE]"));
      }
      • 调用时把 call() 改成 stream()
      • 并且遵循SSE协议最后发送[DONE]终止标识

      调用示例

      Spring AI与DeepSeek实战一之快速打造智能对话应用

      • data: xxx 这种是 Server-Sent Events 的格式要求;
      • 需要前端搭配 EventSource 或 WebSocket 等方式来接收流式数据,并结合 marked.js 来正确显示 markdown 语法。

      四、总结

      虽然通过 Spring AI 能够快速完成 DeepSeek 大模型与 Spring Boot 项目的对接,实现基础的对话接口开发,但这仅是智能化转型的初级阶段。要将大模型能力真正落地为生产级应用,还是需实现以下技术:

      • 能力扩展层:通过 智能体 实现意图理解与任务调度,结合 FunctionCall 实现结构化数据交互,实现AI与业务系统的无缝对接;
      • 知识增强层:应用 RAG(检索增强生成)技术构建领域知识库,解决大模型幻觉问题,支撑专业场景的精准问答;
      • 流程编排层:设计 Agent 工作流实现复杂业务逻辑拆解,支持多步骤推理与自动化决策;
      • 模型优化层:基于业务数据实施模型微调 Fine-tuning 提升垂直场景的响应质量和可控性。

      五、完整代码

      Gitee地址:

      https://gitee.http://www.devze.comcom/zlt2000/zlt-spring-ai-app

      github地址:

      https://github.com/zlt2000/zlt-spring-ai-app

      到此这篇关于Spring AI与DeepSeek实战一:快速打造智能对话应用的文章就介绍到这了,更多相关Spring AI DeepSeek智能对话内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜