spring-ai 第三结构化输出

spring-ai 第三结构化输出

结构化输出

LLM生成结构化输出的能力对于下游应用非常重要

  • 基于 StructuredOutputConverter

快速将AI模型的结果转换为数据类型,例如JSON、XML或Java类,以便可以传递给其他应用程序函数和方法

示例

复制代码
    StructuredOutputConverter outputConverter = ...
    String userInputTemplate = """
        ... user text input ....
        {format}
        """; // user input with a "format" placeholder.
    Prompt prompt = new Prompt(
            PromptTemplate.builder()
						.template(this.userInputTemplate)
						.variables(Map.of(..., "format", this.outputConverter.getFormat())) // replace the "format" placeholder with the converter's format.
						.build().createMessage()
    );

源码示例

https://gitee.com/kcnf_open/spring-ai-sample/tree/master/spring-ai/spring-ai-sample03

返回BeanOutputConverter

复制代码
  @GetMapping("/ai/output")
    public ActorsFilms generate(@RequestParam(value = "actor", defaultValue = "小猪佩奇") String actor) {
        var outputConverter = new BeanOutputConverter<>(ActorsFilms.class);

        String userMessage = """
                Generate the filmography for the actor {actor}.
                Provide the output in JSON format that matches the following structure:
                Actor name and list of movies.
                """;

        return chatClient.prompt()
                .user(user -> user.text(userMessage)
                        .param("actor", actor))
                .call()
                .entity(outputConverter);
    }
  • 测试结果

返回MapOutputConverter

复制代码
    @GetMapping("/ai/map")
    public Map<String, Object> map(@RequestParam(value = "actor", defaultValue = "小猪佩奇") String actor) {
        MapOutputConverter mapOutputConverter = new MapOutputConverter();

        String template = """
        Provide me a List of films for the actor {actor}.
        Return the data as JSON with two fields: 'actor' (the actor name) and 'name movies' (list of movie titles).
        """;

        return chatClient.prompt()
                .user(user -> user.text(template)
                        .param("actor", actor))
                .call()
                .entity(mapOutputConverter);
    }
  • 测试结果
相关推荐
一点一木1 小时前
🚀 2026 年 8 月 GitHub 十大热门项目排行榜 🔥
人工智能·github
ssshooter1 小时前
现在网页都能提供 MCP 了?!
前端·人工智能·程序员
京东云开发者1 小时前
Claude Code vs Codex 记忆体系深度对比
人工智能
用户3126874877202 小时前
ConcurrentHashMap 怎么保证线程安全?从分段锁到 CAS+synchronized
java
不加辣椒2 小时前
第 4 章 什么是 Harness Engineering
人工智能
桃西西呀2 小时前
上下文窗口都卷到 100 万了,大模型为什么还在为"位置"发愁?
人工智能·llm·ai编程
阿拉斯攀登2 小时前
SpringBoot整合MQTT:后端订阅设备数据、解析传感器报文
人工智能
vipxieliang2 小时前
ValidX vs Apache Commons Validator:功能与性能对比
java·spring boot
SimonKing2 小时前
升级Spring Boot 4后,从 Jackson 2 到 3,到底有哪些变化
java·后端·程序员
然我2 小时前
模型不是 Agent:从零实现一个最小 Agent Loop
前端·人工智能·agent