Spring AI实现结构化输出

介绍:让AI大模型输出指定格式数据,便于操作数据并与前端交互

makefile 复制代码
jdk版本:17  
spring-ai-alibaba版本:1.0.0.2  
spring-boot版本:3.4.4

步骤一:引入依赖

依赖管理

xml 复制代码
<properties>
  <java.version>17</java.version>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <spring-boot.version>3.4.4</spring-boot.version>
  <spring-ai-alibaba.version>1.0.0.2</spring-ai-alibaba.version>
</properties>
xml 复制代码
<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>com.alibaba.cloud.ai</groupId>
                <artifactId>spring-ai-alibaba-bom</artifactId>
                <version>${spring-ai-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
	</dependencies>
</dependencyManagement>	

具体依赖-模块所在位置pom.xml

xml 复制代码
<dependency>
  <groupId>com.alibaba.cloud.ai</groupId>
  <artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>

步骤二:配置信息

application.yml

yaml 复制代码
server:
  port: 8098

spring:
  application:
    name: RuoYi-Vue-Plus
  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY}
      chat:
        response-format: json

步骤三:测试类

TestController

less 复制代码
@RestController
@RequestMapping("/structure")
@Slf4j
public class TestController {
    private final ChatClient chatClient;

    private final ChatModel chatModel;

    private final BeanOutputConverter<PersonalInfo> beanOutputConverter;

    private final String format;


    public TestController(ChatClient.Builder builder, ChatModel chatModel) {
        this.chatModel = chatModel;

        this.beanOutputConverter = new BeanOutputConverter<>(
                new ParameterizedTypeReference<PersonalInfo>() {
            }
        );

        this.format = beanOutputConverter.getFormat();
        log.info("format: {}", format);
        this.chatClient = builder.build();
    }

    @GetMapping(value = "/simple-chat-format")
    public PersonalInfo simpleChatFormat(@RequestParam(value = "query", defaultValue = "以小研说技术为作者,写一篇50字左右的人物介绍") String query) {
        return chatClient.prompt(query)
            .call().entity(PersonalInfo.class);
    }

    @GetMapping(value = "/simple-chat")
    public PersonalInfo simpleChat(HttpServletResponse response) {
        Flux<String> flux = this.chatClient.prompt()
            .user(u -> u.text("""
						requirement: 请用大概 100 字, 作者为 小研 , 为AI的发展史写一首诗;
						format: 以纯文本输出 json, 请不要包含任何多余的文字------包括 markdown 格式;
						outputExample: {
							 "title": {title},
							 "author": {author},
							 "date": {date},
							 "content": {content}
						};
						"""))
            .stream()
            .content();

        String result = String.join("\n", Objects.requireNonNull(flux.collectList().block()))
            .replaceAll("\\n", "")
            .replaceAll("\\s+", " ")
            .replaceAll("\"\\s*:", "\":")
            .replaceAll(":\\s*\"", ":\"");

        return beanOutputConverter.convert(result);
    }
}

PersonalInfo

typescript 复制代码
@Data
public class PersonalInfo {
    private String title;

    private String author;

    private String date;

    private String content;

}

步骤四:启动

步骤五:测试

至此,Spring AI实现结构化输出Demo版结束啦!

本人正在打造技术交流群,欢迎志同道合的朋友一起探讨,一起努力,通过自己的努力,在技术岗位这条道路上走得更远。QQ群号:952912771 备注:技术交流 即可通过!

加入技术群可以获取资料,含AI资料、Spring AI中文文档等,等你加入~

相关推荐
IT_陈寒2 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰2 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
用户8356290780513 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
小满zs3 小时前
Go语言第二章(小无相功)
后端·go
用户8356290780513 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k3 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花3 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
贰先生3 小时前
Xiuno BBS X版 用户封禁系统
后端
karry_k3 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
ServBay4 小时前
不会写代码也能建站?AI 时代,非技术创始人如何从零搭建自己的 Web 项目
后端·mcp