SpringAI入门学习

一、环境搭建

1、SpringAI+SpringBoot的pom依赖版本信息如下

SpringBoot 3.5.8 + SpringAI 1.0.0-M6.1+JDK 17

XML 复制代码
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.8</version>
        <relativePath/>
    </parent>
        <properties>
        <java.version>17</java.version>
    </properties>
     <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- SpringAI-->
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter</artifactId>
            <version>1.0.0-M6.1</version>
        </dependency>
    </dependencies>
复制代码
spring-ai-alibaba-starter依赖使用如下包

SpringAI版本查看SpringAI版本查看

二、通义千问API获取

1、开通阿里云百炼平台

阿里云百炼平台

三、测试调用

1、application.yaml配置如下

XML 复制代码
spring:
  application:
    name: SpringAIProjet
  ai:
    dashscope:
      base-url: https://dashscope.aliyuncs.com/compatible-mode/v1
      api-key: 你的上一步百炼大模型平台中的api-key
      chat:
        options:
          model: qwen-plus
server:
  port: 8088
  servlet:
    context-path: /boot
logging:
  level:
    org.springframework.ai.chat.client: DEBUG

2、AIConfig配置ChatClient

java 复制代码
package org.spring.springaiprojet.config;

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

@Configuration
public class AiConfig {
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder) {
        // defaultSystem,默认系统角色,带有对话身份
        return builder.defaultSystem("请你美国总统特朗普身份来回答"). build();
    }
}

3、REST接口如下

  • 普通模式对话问答
java 复制代码
package org.spring.springaiprojet.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ai/")
public class AiController {
    private final ChatClient chatClient;

    @Autowired
    public AiController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }
    @RequestMapping("/qwen/chat/api")
    public String chat(String question) {
        return chatClient.prompt().user(question).call().content();
    }
}
  • 流式响应回答--打字机效果
java 复制代码
    /**
     * 流式对话模式
     * @param question
     * @return
     */
    @RequestMapping("/qwen/chat/stream/api")
    public Flux<String> chatForStream(String question) {
        return chatClient.prompt()
                .user(question)
                .stream()
                .content();
    }
  • 对话记忆功能
java 复制代码
package org.spring.springaiprojet.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AiConfig {
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
        // defaultSystem,默认系统角色,带有对话身份
        return builder
                .defaultSystem("请以通俗开发者角度介绍")
                // 增加会话记忆
                .defaultAdvisors(new PromptChatMemoryAdvisor(chatMemory)).build();
    }
    // 注入会话
    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }
}

通过内存Map来保存历史信息,实现会话记忆功能。

提问:

XML 复制代码
 GET http://localhost:8088/boot/ai/qwen/chat/api?question=SpringBoot框架各个模块作用

再次基于以上内容提问:

XML 复制代码
GET http://localhost:8088/boot/ai/qwen/chat/api?question=基于上述回答,哪个模块学习难度较大,评估一下
  • 提示模版
java 复制代码
    /**
     * 模板模式
     * @param message
     * @return
     */
    @RequestMapping("/qwen/template/api")
    public String templateChat(@RequestParam("message") String message) {
        PromptTemplate template = new PromptTemplate("请用通俗易懂语言解释{message}");
        return chatClient.prompt()
                .user(template.render(Map.of("message", message)))
                .call()
                .content();
    }
XML 复制代码
GET http://localhost:8088/boot/ai/qwen/template/api?message=RAG

四、核心组件

1、对话增强器

Spring AI 提供了一些开箱即用的 Advisor:

SimpleLoggerAdvisor:打印请求和响应内容,便于调试

MessageChatMemoryAdvisor:维护对话历史(上下文),实现多轮对话

FunctionCallbackAdvisor:支持模型调用外部函数工具(如天气查询)

PromptLengthAdvisor:控制提示词长度,避免超限

java 复制代码
    @Bean
    public ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
        // defaultSystem,默认系统角色,带有对话身份
        return builder
                .defaultSystem("请以通俗开发者角度介绍")
                // 增加会话记忆
//                .defaultAdvisors(new PromptChatMemoryAdvisor(chatMemory)).build();
                .defaultAdvisors(new SimpleLoggerAdvisor()).build();
    }

查看控制台

相关推荐
憧憬成为web高手5 小时前
[HITCON 2017]SSRFme
学习
妖精的羽翼5 小时前
AI + 前端、可视化 & 大屏
学习
xuhaoyu_cpp_java11 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
小宋加油啊13 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
Xzh042314 小时前
AI Agent 学习路线(Java 后端方向)
java·人工智能·学习
做cv的小昊14 小时前
计算机图形学:【Games101】学习笔记08——光线追踪(辐射度量学、渲染方程与全局光照、蒙特卡洛积分与路径追踪)
图像处理·笔记·学习·计算机视觉·游戏引擎·图形渲染·概率论
星恒随风14 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
sensen_kiss16 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.8 软件测试 (Software Testing)(上)
学习·软件工程
力学与人工智能16 小时前
PPT分享 | 洛桑联邦理工学院魏震:深度几何学习在工业设计优化中的应用
学习·优化·工业设计·深度几何学习·洛桑联邦理工学院
sensen_kiss18 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.9 软件测试 (Software Testing)(下)
学习·软件工程