Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

Spring AI框架的初步了解

Spring AI系列文章:

  • 一、前言
  • 二、前期准备
    • 2.1 运行环境
    • 2.2 maven配置
    • 2.3 api-key申请
  • 三、Chat Client API
    • 3.1 导入pom依赖
    • 3.2 配置application.properties文件
    • 3.3 创建 ChatClient
    • 3.3.1 使用自动配置的 ChatClient.Builder
    • 3.3.2 使用多个聊天模型
    • 3.4 ChatClient请求
    • 3.5 ChatClient 响应
    • 3.5.1 返回 ChatResponse
    • 3.5.2 返回实体
    • 3.5.3 流式响应
    • 3.6 提示模板
    • 3.6 call() 返回值
    • 3.7 stream() 返回值
    • 3.8 使用默认值
    • 3.8.1 默认系统文本
    • 3.8.2 带参数的默认系统文本
    • 3.8.3 其他默认值
    • 3.9 Advisors
    • 3.9.1 ChatClient 中的 Advisor 配置
    • 3.9.2 日志记录

Spring AI系列文章:

【Spring AI 1.0.0】Spring AI 1.0.0框架快速入门(1)——Chat Client
API

【Spring AI 1.0.0】Spring AI
1.0.0框架快速入门(2)——Prompt(提示词)

【Spring AI 1.0.0】Spring AI 1.0.0框架快速入门(3)——Structured Output
Converter(结构化输出转换器)

一、前言

前言概述:Spring AI历经八个版本迭代(从M1到M8)后,Spring AI 1.0.0正式版于2025年5月20日正式发布,这是具有里程碑意义的版本,标志着Spring生态全面拥抱人工智能技术,也意味着Spring AI能为企业提供稳定的API支持。

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

Spring AI项目旨在简化含人工智能功能应用的开发,避免不必要的复杂情况。

该项目受知名Python项目如LangChainLlamaIndex启发,但并非它们的直接移植。项目坚信,下一波生成式人工智能应用将不仅面向Python开发者,还会普及到多种编程语言。

注意:Spring AI解决了人工智能集成的基础难题:将企业数据和API与人工智能模型相连接。

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

Spring AI提供开发人工智能应用基础的抽象。这些抽象有多种实现方式,能轻松通过少量代码更改替换组件。

Spring AI具备以下功能:

  • 跨AI提供商的聊天、文本到图像和嵌入模型的便携式API支持,涵盖同步和流式API选项,还能访问模型特定功能。

  • 支持所有主要的AI 模型提供商,像Anthropic、OpenAI、Microsoft、Amazon、Google和Ollama等。支持的模型类型包括:

    • 聊天补全

    • 嵌入

    • 文本到图像

    • 音频转录

    • 文本到语音

    • 内容审核

  • 结构化输出——将AI模型输出映射到POJO。

  • 支持所有主要的向量数据库提供商,例如Apache Cassandra、Azure Cosmos DB、Azure Vector Search、Chroma、Elasticsearch、GemFire、MariaDB、Milvus、MongoDB Atlas、Neo4j、OpenSearch、Oracle、PostgreSQL/PGVector、PineCone、Qdrant、Redis、SAP Hana、Typesense和Weaviate。

  • 跨向量存储提供商的便携式API,包含新颖的类SQL元数据过滤API。

  • 工具/函数调用——允许模型请求执行客户端工具和函数,从而按需获取必要实时信息并采取行动。

  • 可观察性——提供对AI相关操作的洞察。

  • 用于数据工程的文档提取ETL 框架

  • AI 模型评估——助力评估生成内容并防止幻觉响应的工具。

  • AI模型和向量存储的Spring Boot自动配置和启动器。

  • ChatClient API——用于与AI聊天模型通信的流畅API,在惯用法上类似WebClient和RestClient API。

  • Advisors API——封装重复出现的生成式AI模式,转换进出语言模型(LLM)的数据,提供跨各种模型和用例的可移植性。

  • 支持聊天对话记忆检索增强生成 (RAG)

基于上述Spring AI特性,我将分多篇博客详细讲解Spring AI的用法,若有帮助请点赞、收藏、评论,给我些许鼓励!关注更是极好的

Spring AI 1.0.0源码:GitHub
本文代码:GitHub

二、前期准备

2.1 运行环境

Spring AI基于Sping Boot 3.x及以上版本,本文选用3.4.5(Spring AI 1.0.0源码为3.4.5),需JDK 17及以上,若JDK 8需升级,也可配置双jdk环境,具体配置如图,Path环境中靠前的优先级高

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />
在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

2.2 maven配置

maven的setting.xml文件中需添加快照仓库

<profile>
       <id>spring-snapshots</id>
       <repositories>
           <repository>
               <id>spring-snapshots</id>
               <url>https://repo.spring.io/snapshot</url>
               <snapshots>
                   <enabled>true</enabled>
               </snapshots>
               <releases>
                   <enabled>false</enabled>
               </releases>
           </repository>
       </repositories>
   </profile>
 </profiles>

 <activeProfiles>
   <activeProfile>spring-snapshots</activeProfile>
 </activeProfiles>

2.3 api-key申请

Spring AI提供多种类型模型,包括聊天模型、嵌入模型、图像模型、音频模型、内容审核模型等。提供多家AI提供商的便携式Model API,如Claude、OpenAI、DeepSeek、ZhiPu等

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

例如聊天模型,有多种实现

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

聊天模型对比

此表格对比Spring AI支持的各种聊天模型的功能:

  • 多模态: 模型能处理的输入类型(如文本、图像、音频、视频)。

  • 工具/函数调用: 模型是否支持函数调用或工具使用。

  • 流式响应: 模型是否提供流式响应。

  • 重试: 是否支持重试机制。

  • 可观测性: 用于监控和调试的功能。

  • 内置 JSON: 原生支持JSON输出。

  • 本地部署: 模型能否在本地运行。

  • OpenAI API 兼容性: 模型是否兼容OpenAI的API。

提供商 多模态 工具/函数 流式响应 重试 可观测性 内置 JSON 本地 OpenAI API 兼容
Anthropic Claude 文本、PDF、图像
Azure OpenAI 文本、图像
DeepSeek (OpenAI-proxy) 文本
Google VertexAI Gemini 文本、PDF、图像、音频、视频
Groq (OpenAI-proxy) 文本、图像
HuggingFace 文本
Mistral AI 文本、图像
MiniMax 文本
Moonshot AI 文本
NVIDIA (OpenAI-proxy) 文本、图像
OCI GenAI/Cohere 文本
Ollama 文本、图像
OpenAI 输入:文本、图像、音频 输出:文本、音频
Perplexity (OpenAI-proxy) 文本
QianFan 文本
ZhiPu AI 文本
Amazon Bedrock Converse 文本、图像、视频、文档(PDF、HTML、MD、DOCX…)

本文采用DeepSeek用于聊天模型,ZhiPu用户文生图模型,其他模型类似

DeepSeek api-key获取:https://platform.deepseek.com/api_keys,DeepSeek创建后需充值

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

新用户可使用ZhiPu,可白嫖!

ZhiPu api-key获取:https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />
在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

三、Chat Client API

ChatClient提供与AI模型通信的流畅API,支持同步和流式编程模型。

3.1 导入pom依赖

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- spring-web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- deepseek依赖 -->
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-starter-model-deepseek</artifactId>
    </dependency>

    <!-- zhipuai依赖 -->
<!--        <dependency>-->
<!--            <groupId>org.springframework.ai</groupId>-->
<!--            <artifactId>spring-ai-starter-model-zhipuai</artifactId>-->
<!--        </dependency>-->
</dependencies>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>
    <repository>
        <name>Central Portal Snapshots</name>
        <id>central-portal-snapshots</id>
        <url>https://central.sonatype.com/repository/maven-snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

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

3.2 配置application.properties文件

spring:
  ai:
    deepseek:
      # API 密钥
      api-key: <your-deepseek-api-key>

      # 可选:DeepSeek API 基础地址,默认是 https://api.deepseek.com
      # base-url: https://api.deepseek.com

      chat:
        options:
          # DeepSeek 使用的聊天模型,可选 deepseek-chat 或 deepseek-reasoner
          # deepseek-chat为聊天模型,deepseek-reasoner为推理模型,推理模型会生成推理过程,比较消耗token
          model: deepseek-chat

          # 模型的温度值,控制生成文本的随机性(0.0 = 最确定,1.0 = 最随机)
          temperature: 0.8

3.3 创建 ChatClient

ChatClient通过ChatClient.Builder对象创建。可获取自动配置的ChatClient.Builder实例用于任何ChatModel Spring Boot自动配置,或编程创建。因依赖中导入DeepSeek,默认采用DeepSeek模型。

3.3.1 使用自动配置的 ChatClient.Builder

Spring AI提供Spring Boot自动配置,创建原型ChatClient.Builder bean,可注入类中。以下是获取简单用户请求String响应的示例:

@RestController
public class ChatClientController {

    private final ChatClient chatClient;

    public ChatClientController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping("/ai")
    String generation(@RequestParam("userInput") String userInput) {
        return this.chatClient.prompt()
                .user(userInput)
                .call()
                .content();
    }
}

此示例中,用户输入设置用户消息内容,call()方法向AI模型发送请求,content()方法返回AI模型响应字符串。

在这里插入图片描述Spring AI 1.0.0里Chat Client API的便捷开启(首部分)

" />

3.3.2 使用多个聊天模型

单个应用中使用多个聊天模型有多种场景:

  • 为不同任务用不同模型(如用强大模型做复杂推理,用快且便宜模型处理简单任务)

  • 模型服务不可用时实现回退

  • 对不同模型或配置进行A/B测试

  • 根据用户偏好提供模型选择

  • 组合专业模型(一个用于代码生成,另一个用于创意内容等)

默认情况下,Spring AI

相关文章

暂无评论

暂无评论...