极简集成大模型!Spring AI Alibaba ChatClient 快速上手指南

ChatClient简介

官网地址: java2ai.com/docs/1.0.0....

ChatClient 提供了与 AI 模型通信的 Fluent API,它支持同步和反应式(Reactive)编程模型。与 ChatModelMessageChatMemory 等原子 API 相比,使用 ChatClient 可以将与 LLM 及其他组件交互的复杂性隐藏在背后,因为基于 LLM 的应用程序通常要多个组件协同工作(例如,提示词模板、聊天记忆、LLM Model、输出解析器、RAG 组件:嵌入模型和存储),并且通常涉及多个交互,因此协调它们会让编码变得繁琐。当然使用 ChatModel 等原子 API 可以为应用程序带来更多的灵活性,成本就是您需要编写大量样板代码

ChatClient 类似于应用程序开发中的服务层,它为应用程序直接提供 AI 服务,开发者可以使用 ChatClient Fluent API 快速完成一整套 AI 交互流程的组装。

包括一些基础功能,如:

  • 定制和组装模型的输入(Prompt)
  • 格式化解析模型的输出(Structured Output)
  • 调整模型交互参数(ChatOptions)

还支持更多高级功能:

  • 聊天记忆(Chat Memory)
  • 工具/函数调用(Function Calling)
  • RAG

编码案例

建model

改POM

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.miao</groupId>
        <artifactId>SpringAIAlibaba-test01</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>SAA-03ChatClient</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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

        <!--  模型服务灵积  调用alibaba生态的协议 对标openai协议   -->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
            <version>1.0.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.38</version>
        </dependency>
    </dependencies>
</project>

写YML

ini 复制代码
server.port=8082

#大模型对话中文UTF8编码处理
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8

spring.application.name=SAA-01HelloWorld

#spring-ai-alibaba config
#百炼大模型的api-key
spring.ai.dashscope.api-key=${qwen-api-key}
spring.ai.dashscope.url=https://dashscope.aliyuncs.com/compatible-mode/v1
spring.ai.dashscope.model=qwen3-vl-flash

主启动

typescript 复制代码
package com.miao.chatclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ChatClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ChatClientApplication.class, args);
    }
}

config配置类

kotlin 复制代码
package com.miao.chatclient.config;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SaaLLMConfig {

    /**
     * 方式一 : 通过配置文件注入 API Key
     */
    @Value("${spring.ai.dashscope.api-key}")
    private String apiKey;


    @Bean
    public DashScopeApi dashScopeApi() {
        return DashScopeApi.builder()
                // 从系统环境变量中读取配置
                .apiKey(apiKey)
                .build();
    }
}

业务类第一版 ChatModel

ChatClient不支持自动注入 启动程序会报错

kotlin 复制代码
package com.miao.chatclient.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
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;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/chatModel")
public class ChatModelController {
    /**
     * 文生文对话模型 ChatModel 调用阿里云的百炼平台
     */
    @Resource
    private ChatModel dashScopeChatModel;

    /**
     * ChatClient不支持自动注入 启动程序会报错
     */
//    @Resource
//    private ChatClient client;

    /**
     * 普通通用调用 一次性返回
     */
    @GetMapping(value = "call")
    public String doChatCall(@RequestParam(name = "msg", defaultValue = "你是谁") String message) {
        return dashScopeChatModel.call(message);
    }


    /**
     * 流式调用 有多少返回多少 挤牙膏式返回
     */
    @GetMapping(value = "steam")
    public Flux<String> doChatStream(@RequestParam(name = "msg", defaultValue = "你是谁") String message) {
        return dashScopeChatModel.stream(message);
    }

}

业务类第二版 ChatClient

分为:

  • 使用自动配置注入的ChatClient
  • 以编程方式创建ChatClient
使用自动配置的 ChatClient.Builder
kotlin 复制代码
package com.miao.chatclient.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatClientController {
    
    private final ChatClient dashScopeChatClient;

    /**
     * 1. 使用自动配置的 ChatClient.Builder
     * ChatClient 不支持自动注入,需要通过 ChatClient.Builder 来构建 ChatClient 实例
     */
    public ChatClientController(ChatModel dashScopeChatModel) {
        this.dashScopeChatClient = ChatClient
                .builder(dashScopeChatModel)
                .build();
    }

    @GetMapping(value = "/chatClient/call")
    public String doChatClientCall(@RequestParam(name = "msg", defaultValue = "你是谁") String message) {
        return dashScopeChatClient.prompt().user(message).call().content();
    }
}
以编程方式创建ChatClient

1.配置类中注入ChatClient

kotlin 复制代码
package com.miao.chatclient.config;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SaaLLMConfig {

    /**
     * 方式一 : 通过配置文件注入 API Key
     */
    @Value("${spring.ai.dashscope.api-key}")
    private String apiKey;


    @Bean
    public DashScopeApi dashScopeApi() {
        return DashScopeApi.builder()
                // 从系统环境变量中读取配置
                .apiKey(apiKey)
                .build();
    }

    /**
     * Bean方式注入 ChatClient
     */
    @Bean
    public ChatClient ChatClient(ChatModel dashScopeChatModel) {
        return ChatClient.builder(dashScopeChatModel).build();
    }
}

2.业务类使用ChatClietn

kotlin 复制代码
package com.miao.chatclient.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatClientControllerV2 {

    @Resource
    private ChatModel dashScopeChatModel;

    @Autowired
    private ChatClient doshScopeChatClientV2;

    @GetMapping("/chatClientV2/call")
    public String chatCall(@RequestParam(name = "msg", defaultValue = "你是谁") String message) {
        return doshScopeChatClientV2.prompt().user(message).call().content();
    }

    @GetMapping("/chatModelV2/call")
    public String chatModelCall(@RequestParam(name = "msg", defaultValue = "你是谁") String message) {
        return dashScopeChatModel.call(message);
    }
}

小总结

生产的时候, ChatCliet和ChatModel混合使用,拥有不同的使用场景

ChatModel ChatClient
代码简洁性 代码繁琐,需手动构建请求 / 解析响应 极简 DSL,一行代码完成提问 + 获取结果
参数控制 完全暴露所有模型参数,支持精细化配置 支持参数配置,但封装了底层 Request 构建
上下文管理 需手动维护消息列表(多轮对话) 内置上下文管理,自动维护对话历史
响应处理 需手动从 ChatResponse 提取内容 / 元数据 提供 content ()/entity () 等快捷方法
扩展性 高,可自定义 Request/Response 处理器 中,扩展需基于底层 ChatModel
学习成本 高,需理解 Spring AI 核心抽象(Request/Response) 低,无需关注底层,专注业务逻辑
流式响应 支持,但需处理流式 ChatResponse 支持,提供 stream ().content () 简化流式处理
相关推荐
jiayong232 小时前
Markdown编辑完全指南
java·编辑器
heartbeat..2 小时前
深入理解 Redisson:分布式锁原理、特性与生产级应用(Java 版)
java·分布式·线程·redisson·
一代明君Kevin学长2 小时前
快速自定义一个带进度监控的文件资源类
java·前端·后端·python·文件上传·文件服务·文件流
aiopencode2 小时前
上架 iOS 应用到底在做什么?从准备工作到上架的流程
后端
未来之窗软件服务3 小时前
幽冥大陆(四十九)PHP打造Java的Jar实践——东方仙盟筑基期
java·php·jar·仙盟创梦ide·东方仙盟·东方仙盟sdk·东方仙盟一体化
普通网友3 小时前
深入探讨Linux驱动开发:字符设备驱动开发与测试_linux 驱动开发设备号(2)
java·linux·驱动开发
4Forsee3 小时前
【Android】动态操作 Window 的背后机制
android·java·前端
小二李3 小时前
第12章 koa框架重构篇 - Koa框架项目重构
java·前端·重构
cike_y3 小时前
JavaBean&MVC三层架构
java·架构·mvc·javaweb·java开发