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中文文档等,等你加入~

相关推荐
whyfail26 分钟前
前端学 Spring Boot(2):一次点击,如何穿过整个后端?
前端·spring boot·后端
程序员cxuan2 小时前
Loop 还没玩明白,Graph Engineering 又火了。
人工智能·后端·程序员
uzong3 小时前
把一面面试总结做成一个 Skill:重复的事,就别每次都重写
后端·面试
程序员海军4 小时前
一个 AI 应用开发程序员的一天,都在屏幕前忙些什么?
前端·后端·程序员
不能放弃治疗4 小时前
MCP
后端
江湖十年5 小时前
Go 语言中 YAML to JSON 踩坑笔记
后端·go·json
你驴我5 小时前
WhatsApp 消息撤回与编辑的幂等性设计实践
java·服务器·前端·后端·python
一缕清烟在人间6 小时前
HarmonyOS开发实战:小分享-TextEditPage文字编辑器——Header+TextArea+工具栏
后端·华为·harmonyos·鸿蒙
人间凡尔赛6 小时前
K8s 十年之变:从 Cloud Native 到 AI Native,2026 年后端架构的范式革命
后端·云原生·架构
程序员cxuan6 小时前
Opus 5 深夜炸场,价格还挺香。。。
人工智能·后端·程序员