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();
    }

查看控制台

相关推荐
墨黎芜1 分钟前
SQL Server从入门到精通——C#与数据库
数据库·学习·信息可视化
wdfk_prog10 分钟前
[Linux]学习笔记系列 -- [drivers][dma]stm32-dma
linux·笔记·学习
暖阳之下12 分钟前
学习周报三十三
学习
写点什么呢20 分钟前
Ltspice_安装与使用
学习·测试工具
CappuccinoRose24 分钟前
CSS前端布局总指南
前端·css·学习·布局·flex布局·grid布局·float布局
mango_mangojuice28 分钟前
Linux学习笔记(角色,权限管理)1.21
linux·笔记·学习
好奇龙猫2 小时前
【人工智能学习-AI入试相关题目练习-第十六次】
人工智能·学习
啊我不会诶2 小时前
Codeforces Round 1071 (Div. 3) vp补题
开发语言·学习·算法
星火开发设计3 小时前
命名空间 namespace:解决命名冲突的利器
c语言·开发语言·c++·学习·算法·知识
强子感冒了3 小时前
CSS基础学习:CSS选择器与优先级规则
前端·css·学习