Spring-Ai-Alibaba [02] chatclient-demo

Spring-Ai-Alibaba 02 chatclient-demo

概述

本文是 Spring AI Alibaba 框架学习系列第二篇,介绍 chatclient 的使用。

代码上传至 Gitee:https://gitee.com/xbjct/spring-ai-alibaba-demo

开发环境

  • 基础框架: Spring Boot 3.5.14
  • AI 框架: Spring AI 1.1.2 + Spring AI Alibaba 1.1.2.2
  • 大模型: 阿里云通义千问 (qwen-plus)
  • 构建工具: Maven 3.9.11
  • JDK 版本: 21.0.10

项目结构

pom.xml

xml 复制代码
<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.junjiu.spring.ai.alibaba.demo</groupId>
        <artifactId>Spring-AI-Alibaba-Demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>02-chatclient-demo</artifactId>
    <packaging>jar</packaging>

    <name>02-chatclient-demo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

application.yml 配置文件

yaml 复制代码
server:
  port: 5826
  servlet:
    # 解决流式中文对话乱码问题.
    encoding:
      charset: utf-8
      enabled: true
      force: true

spring:
  application:
    name: 02-chatclient-demo
  ai:
    dashscope:
      base-url: https://dashscope.aliyuncs.com
      api-key: ${AIALI_API_KEY}
      chat:
        options:
          model: qwen-plus

config 配置类

java 复制代码
package com.junjiu.spring.ai.alibaba.demo.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * program: Spring-AI-Alibaba-Demo
 * ClassName: ChatClientConfig
 * description:
 *
 * @author: 君九
 * @create: 2026-05-21 08:55
 * @version: 1.0
 **/
@Configuration
public class ChatClientConfig {

    /**
     * 创建 ChatClient 对象,并注入到 Spring 容器中。
     * @param chatModel
     * @return
     */
    @Bean
    public ChatClient chatClient(ChatModel chatModel) {
        // return ChatClient.builder(chatModel).build();
        return ChatClient.create(chatModel);
    }

}

controller 层

Hello01Controller.java

java 复制代码
package com.junjiu.spring.ai.alibaba.demo.controller;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * program: Spring-AI-Alibaba-Demo
 * ClassName: HelloController
 * description:
 *
 * @author: 君九
 * @create: 2026-05-18 01:05
 * @version: 1.0
 **/
@RestController
@RequestMapping("/hello01")
public class Hello01Controller {

    @Autowired
    private ChatModel chatModel;

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/chat")
    public String chat(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatModel.call(message);
    }

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/streamChat")
    public Flux<String> streamChat(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatModel.stream(message);
    }


    /********************************************************************************************************************/
    // ChatClient 模式
    /********************************************************************************************************************/

    /**
     * ChatClient 第一种使用方式,
     *  在 SpringBoot 项目中,创建 ChatClient.Builder 对象,并注入到 Spring 容器中,然后使用 ChatClient 对象进行聊天对话。
     */

    private ChatClient chatClient;

    public Hello01Controller(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/chat01")
    public String chat01(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/streamChat01")
    public Flux<String> streamChat01(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .content();
    }

}

Hello02Controller.java

java 复制代码
package com.junjiu.spring.ai.alibaba.demo.controller;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * program: Spring-AI-Alibaba-Demo
 * ClassName: Hello02Controller
 * description:
 *
 * @author: 君九
 * @create: 2026-05-21 08:54
 * @version: 1.0
 **/
@RestController
@RequestMapping("/hello02")
public class Hello02Controller {

    @Autowired
    private ChatModel chatModel;

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/chat")
    public String chat(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatModel.call(message);
    }

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/streamChat")
    public Flux<String> streamChat(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatModel.stream(message);
    }


    /********************************************************************************************************************/
    // ChatClient 模式
    /********************************************************************************************************************/

    /**
     * ChatClient 第二种使用方式:
     *      在配置文件 ChatClientconfig中,创建 ChatClient.Builder 对象,并注入到 Spring 容器中,然后使用 ChatClient 对象进行聊天对话。
     */

    @Autowired
    ChatClient chatClient;

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/chat02")
    public String chat02(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatClient.prompt()
                .user(message)
                .call()
                .content();
    }

    /**
     * 聊天对话.
     * @param message
     * @return
     */
    @GetMapping("/streamChat02")
    public Flux<String> streamChat02(@RequestParam(name = "message", defaultValue = "你好") String message) {
        return chatClient.prompt()
                .user(message)
                .stream()
                .content();
    }

}

启动类

java 复制代码
package com.junjiu.spring.ai.alibaba.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;

/**
 * program: Spring-AI-Alibaba-Demo
 * ClassName: CheckClientApplication
 * description:
 *
 * @author: 君九
 * @create: 2026-05-21 08:23
 * @version: 1.0
 **/
@SpringBootApplication
public class CheckClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(CheckClientApplication.class, args);
    }

    public ApplicationListener<ApplicationReadyEvent> readyEventApplicationListener(Environment env) {
        return event -> {
            System.out.println("\n🎉========================================🎉");
            System.out.println("✅ Application is ready!");
            System.out.println("AIALI_API_KEY=" + System.getenv("AIALI_API_KEY"));
            System.out.println("🎉========================================🎉\n");
        };
    }
}

验证

打开浏览器访问:

ChatClient-方式1:Hello01Contrller

  1. 基本对话

  2. 流式对话

ChatClient-方式2:Hello2Controller

  1. 基本对话

  2. 流式对话

代码上传至 Gitee:https://gitee.com/xbjct/spring-ai-alibaba-demo

若有转载,请标明出处:https://blog.csdn.net/CharlesYuangc/article/details/161273025

相关推荐
AI小白Lin18 小时前
Agent Harness 越堆越烂?600 次实验推翻"自进化",个人场景下更适合"自驯化"
人工智能·架构
ViperL118 小时前
[智能算法]NASSFG-显著特征指导的医学目标检测NAS
人工智能·目标检测·计算机视觉
ShallWeL18 小时前
Orin 上 USB / CSI 相机采集踩坑
人工智能·嵌入式硬件·智能硬件·agi
武子康18 小时前
Pi vs Claude Code vs Codex 正确读法:6 组同模型匹配 + 2.08×/1.46×/1.20×/1.54×/1.22×/1.44× 成
人工智能·ai编程·claude
renhongxia118 小时前
AI安全保卫战:我们如何防止“失控”的智能体?
人工智能·深度学习·安全·机器学习·架构·机器人
千桐科技18 小时前
DataX 执行引擎正式加入:qData 开源版 v1.6.0 新增 Quartz + DataX 轻量运行模式!
java·大数据·开源·数据治理·数据中台·qdata
江边风声18 小时前
PCB自动化收放板机 在薄板制程中的特殊取放策略——0.05mm芯板怎么稳抓不掉
人工智能·科技·自动化·制造·pcb工艺
lupai18 小时前
汽车维保记录精准版 API 快速接入指南
大数据·人工智能·汽车
Irene199118 小时前
Oracle PL/SQL Developer 版本差异(11g、14)实战总结
java·开发语言
AI人工智能+电脑小能手18 小时前
【大白话说Java面试题 第191题】【08_Kafka篇】第7题:消息队列的优缺点
java·消息队列·系统设计·分布式架构·技术选型