Spring AI 快速接入 DeepSeek 大模型

#AIcoding·八月创作之星挑战赛#

Spring AI 快速接入 DeepSeek 大模型

Spring AI 框架概述

在经历了八个里程碑式的版本之后(M1~M8),Spring AI 1.0 正式版本,终于在 2025 年 5 月 20 日正式发布了,这是另一个新高度的里程碑式的版本,标志着 Spring 生态系统正式全面拥抱人工智能技术,并且意味着 Spring AI 将会给企业带来稳定 API 支持。

Spring AI 是 Spring 官方推出的一个人工智能集成框架,旨在简化 AI 功能在 Spring 应用中的整合。它提供了一套标准化的 API 和工具,让开发者能够轻松接入多种主流 AI 服务(如 OpenAI、Azure AI、Hugging Face 等),同时保持 Spring 生态的简洁性和灵活性。

核心特性

  1. 统一 API 设计

通过抽象层屏蔽不同 AI 提供商(如 OpenAI、Gemini、Ollama 等)的接口差异,开发者只需使用 Spring AI 的通用接口(如 ChatModel),即可切换底层 AI 服务。

同理就类似于,我们 JDBC 连接数据库的被统一的连接接口,这里我们的 Spring AI 就类似于我们这里的 JDBC,不同的是 这个 Spring AI 是连接操作其他 LLM(大模型)的被统一的接口。

  1. 开箱即用的功能支持
  2. 支持对话模型(Chat)类的大模型:与 ChatGPT 类似的交互。
  3. 支持嵌入模型(Embedding)类的大模型:嵌入模型是将文本、图像或其他数据转换为数值向量(即嵌入向量)的技术。
  4. 支持图像生成(Image Generation)类的大模型:图像生成是指AI根据文本描述或其他输入创建新图像的能力。
  5. 支持函数调用(Function Calling):函数调用功能使AI模型能够与外部API和服务交互。也就是说,你写一个函数,AI 也能调用你写的函数。
  6. 与 Spring 生态无缝集成
  7. 支持 Spring Boot 自动配置、依赖注入、Actuator 监控等,与 Spring Security、Spring Data 等组件协同工作。
  8. Prompt 工程支持
  9. 提供 PromptTemplate 等工具,方便动态生成提示词(Prompts),支持上下文管理。
  10. 模块化设计
  11. 开发者可以根据项目需求选择特定的AI服务模块
  12. 例如只需OpenAI功能就只引入spring-ai-openai
  13. 如需Google Vertex AI则引入spring-ai-vertexai
  14. 每个AI供应商/服务有独立的Spring Starter模块

适用场景

  • 快速构建 AI 驱动的应用(如智能客服、内容生成工具)。
  • 需要灵活切换 AI 后端(如从本地模型切换到云服务)。
  • 结合 Spring 生态实现企业级 AI 功能(如权限控制、数据持久化)。

官网与资源

AI 提供商与模型类型

在SpringAI中,模型类型AI提供商是两个不同维度的概念,但它们又相互关联。让我用更清晰的方式帮你区分和理解:

模型类型(Model Type)

指的是AI模型的功能类别,即它能完成什么任务。
特点:与具体厂商无关,是通用的能力分类。

常见模型类型

模型类型功能说明典型应用场景
Chat(对话型)对话交互(如ChatGPT)客服机器人、聊天助手
Embedding(嵌入型)将文本转换为向量(数值数组)语义搜索、RAG + 传统搜索基于关键词匹配(如Google早期的搜索),而语义搜索通过理解查询的语义(含义)来返回更相关的结果。 + 它利用深度学习模型(如BERT、Embedding模型)将文本转换为向量(vector),通过向量相似度匹配内容,即使查询词和文档没有直接的关键词重叠。
Image(文生图型)生成/处理图像(如Stable Diffusion)设计辅助、内容生成
Text-to-Speech(文转语音型)将文本转为语音语音助手、有声内容
Function Calling(函数回调型)让AI调用外部函数/API实时数据查询、工作流自动化

AI提供商(Provider)

提供具体AI模型服务的公司或平台。
特点: 同一提供商可能支持多种模型类型

常见提供商

提供商支持的模型类型具体模型示例
OpenAIChat, Embedding, ImageGPT-4o、text-embedding-3、DALL-E
Google Vertex AIChat, Embedding, ImagePaLM 2、Imagen
Azure OpenAIChat, Embedding微软托管的OpenAI服务
Hugging FaceChat, Embedding, Image开源模型(如BLOOM、Stable Diffusion)
Stability AIImageStable Diffusion系列
DeepSeekChat,代码专用模型、Embedding、数学专用模型DeepSeek-V3、DeepSeek-Coder、DeepSeek-Embedding、DeepSeek-Math

两者的关系

  • 一个提供商支持多种模型类型
    例如:OpenAI同时提供Chat模型(GPT-4)、Embedding模型(text-embedding-3)、Image模型(DALL-E)。
  • 一种模型类型可由多个提供商实现
    例如:Chat模型既可以用OpenAI的GPT-4,也可以用Google的PaLM 2。

Spring AI 框架支持哪些 AI 提供商的哪些模型

Spring AI 框架支持主流的 AI 提供商的主流模型,并且会随着 Spring AI 版本的升级而变化。

以下是截至 2024年6月Spring AI 框架官方及社区支持的 AI 提供商及其对应的 模型类型的详细列表,包含国内和国外主流厂商。

AI 提供商支持的模型类型具体模型示例是否国内厂商Spring AI 模块名
OpenAIChat, Embedding, Image Generation, Function CallingGPT-4, GPT-3.5, text-embedding-3, DALL-E 3spring-ai-openai
Azure OpenAIChat, Embedding, Image GenerationGPT-4, GPT-3.5, text-embedding-ada-002spring-ai-azure-openai
Google Vertex AIChat, Embedding, Code GenerationGemini 1.5, PaLM 2, textembedding-geckospring-ai-vertexai
Hugging FaceChat, Embedding, Text Generation, Image GenerationBLOOM, Llama 2, Stable Diffusion, BERTspring-ai-huggingface
Stability AIImage GenerationStable Diffusion XL, Stable Diffusion 3spring-ai-stabilityai
AnthropicChatClaude 3, Claude 2spring-ai-anthropic (社区支持)
OllamaChat, Embedding (本地运行开源模型)Llama 3, Mistral, Gemmaspring-ai-ollama
DeepSeek❌ (尚未官方支持,但未来可能集成)DeepSeek-V3, DeepSeek-Coder暂无,虽然没有给 deepseek 提供专门的 starter,但是由于 deepseek API 接口规范与 OpenAI 保持一致,因此也可以使用 openai 的 starter。
百度文心大模型❌ (尚未官方支持)ERNIE-Bot 4.0, ERNIE-Embedding暂无
阿里云通义千问❌ (尚未官方支持)Qwen-72B, Qwen-Embedding暂无
智谱AI (GLM)❌ (尚未官方支持)ChatGLM3, GLM-Embedding暂无
讯飞星火❌ (尚未官方支持)SparkDesk 3.0暂无
MiniMax❌ (尚未官方支持)ABAB 5.5暂无

Spring AI 接入 DeepSeek

DeepSeek 的 API 设计兼容 OpenAI:DeepSeek 的 API 接口规范(如请求/响应格式、鉴权方式)与 OpenAI 保持一致,因此可以直接使用 OpenAI 的客户端库调用 DeepSeek。

引入依赖

<dependencies>
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--
        DeepSeek 的 API 设计兼容 OpenAI:
        DeepSeek 的 API 接口规范(如请求/响应格式、鉴权方式)与 OpenAI 保持一致,
        因此可以直接使用 OpenAI 的客户端库调用 DeepSeek。
    -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        <version>1.0.0-M6</version>
    </dependency>
    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
<repositories>
    <!--指向 Spring 官方提供的快照仓库,为了尝试 Spring 的最新功能-->
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

编写配置文件

# Spring AI OpenAI/DeepSeek 配置
spring:
  ai:
    openai:
      api-key: sk-b768607df6cd4xxx0f5aa38 # 设置 DeepSeek API 的访问密钥,永远不要将密钥提交到代码仓库,建议通过环境变量注入。搞不好要花钱的。
      base-url: https://api.deepseek.com           # 指定 DeepSeek API 的基础地址,格式与OpenAI相同。
      chat:
        options:
          model: deepseek-chat                     # 选择要调用的 DeepSeek 模型名称,必须与 DeepSeek 支持的模型列表匹配(如 deepseek-chat、deepseek-coder 等),不同模型可能有不同的计费标准和能力。
          temperature: 1.3                         # temperature 值越高,AI 回答越随机和创意;值越低,回答越确定和保守。1.3 属于高值,适合需要发散性输出的场景,但可能牺牲准确性。

编写 service

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@RequiredArgsConstructor
@Service
public class AiService {

    private final ChatModel chatModel;

    // 简单的直接调用
    public String generate(String message) {
        return chatModel.call(message);
    }

    // 使用系统提示模板
    public String generateWithSystemPrompt(String userMessage) {

        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("""
                你是一个资深{domain}专家,回答需满足以下要求:
                1. 语言风格:{tone}
                2. 回答长度:{length}
                3. 用户问题:{userMessage}
                """);

        Prompt prompt = new Prompt(
                systemPromptTemplate.createMessage(Map.of(
                        "domain", "科技",
                        "tone", "幽默",
                        "length", "不超过100字",
                        "userMessage", userMessage
                ))
        );

        return chatModel.call(prompt).getResult().getOutput().getText();
    }
}

编写 controller

import com.example.demo.service.AiService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {

    private final AiService aiService;

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return aiService.generate(message);
    }

    @GetMapping("/chat-with-prompt")
    public String chatWithPrompt(@RequestParam String message) {
        return aiService.generateWithSystemPrompt(message);
    }
}

启动服务,在浏览器地址栏上访问:

到此,Spring AI 接入 DeepSeek 就完成了。

最后:

“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”

在这里插入图片描述

### 如何在Spring AI项目中接入DeepSeek模型或服务 要在Spring AI项目中集成DeepSeek模型或服务,可以遵循以下方法来实现这一目标: #### 1. **理解DeepSeek API** DeepSeek 提供了一系列预训练的语言模型和服务接口。这些API允许开发者通过HTTP请求调用来访问其功能[^3]。为了成功集成到Spring项目中,首先需要熟悉DeepSeek官方文档中的API说明以及支持的功能列表。 对于AI项目的开发人员来说,通常会关注以下几个方面: - 文本生成能力 - 对话处理机制 - 自然语言理解和分类任务的支持程度 因此,在实际操作前应仔细阅读并测试所提供的RESTful APIs或者SDKs是否满足当前业务需求。 ```java // Example of making a REST call using RestTemplate in Spring Boot RestTemplate restTemplate = new RestTemplate(); String deepSeekUrl = "https://api.deepseek.com/v1/generate"; // Hypothetical URL example HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> requestBody = Map.of( "prompt", "Write me a short story about space exploration.", "max_tokens", 50, "temperature", 0.7f ); HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers); ResponseEntity<String> response = restTemplate.postForEntity(deepSeekUrl, request, String.class); System.out.println(response.getBody()); ``` 上述代码片段展示了如何利用 `RestTemplate` 向DeepSeek的服务端发送POST请求,并获取返回的结果数据。需要注意的是具体URL路径和参数结构需参照最新版的DeepSeek API指南调整。 #### 2. **配置依赖项** 如果计划长期维护此模块,则建议引入第三方库简化网络通信流程管理。例如Feign客户端能够更方便地定义接口声明式Web服务消费者角色;而OpenFeign作为Netflix开源工具之一已被纳入Spring Cloud生态体系当中成为推荐选项之一[^4]。 添加如下Maven坐标至pom.xml文件完成基础环境搭建工作: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>3.1.4</version> <!-- Ensure compatibility --> </dependency> <!-- Optional: JSON processing libraries like Jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.0</version> </dependency> ``` 接着启用@EnableFeignClients注解开启扫描指定包下的候选类加载过程即可自动装配相应组件实例对象用于后续逻辑编写环节之中去。 #### 3. **错误处理与性能优化策略** 考虑到远程调用过程中可能出现的各种异常情况(比如超时、连接失败等问题),应当设计合理的重试机制及断路器保护措施防止级联效应影响整体系统的稳定性表现水平下降太多以至于不可接受的地步为止才行啊亲~ 可以考虑采用Hystrix框架或者是Resilience4j这样的现代替代方案来进行防护设置哦~ 另外关于效率方面的考量因素也有很多值得注意的地方呢比如说批量提交任务减少单独交互次数从而提升吞吐量等等都是不错的思路方向哈! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值