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);
    }
  • 测试结果
相关推荐
湘美书院--湘美谈教育8 小时前
湘美谈教育AI系列经验集锦:赋能整理聊斋志异大寓言
大数据·人工智能·深度学习·神经网络·机器学习
不知名的老吴8 小时前
线程的生命周期之线程同步
java·开发语言·jvm
宜昌未来智慧谷8 小时前
WWDC 2026开发者视角解读:Siri独立App的技术架构与第三方AI模型接入机制
人工智能·架构·apple·wwdc·gemini
协享科技8 小时前
Spring Boot 与 Go 双服务架构实践:从单体拆分到通信设计
java·人工智能·spring boot·后端·架构·golang·ai编程
piglet121388 小时前
把搜索调到 Claude.ai 的水准
前端·人工智能
Linlingu8 小时前
openClaw不能操作我的电脑提示没有权限如何解决?
人工智能·windows·办公自动化·数字员工·小龙虾
snpgroupcn9 小时前
SNP亮相2026思爱普中国峰会,助力企业加速数据价值兑现
人工智能
IT乐手9 小时前
Anthropic 为何限制中国大陆使用 Claude?
人工智能
To_OC9 小时前
用 ESM 模块化搭建 DeepSeek LLM 调用,顺带用 Prompt 实现轻量 NLP 任务
人工智能·nlp·deepseek
jrjrgood9 小时前
现货黄金和黄金期货的区别有哪些?如何投资?
大数据·人工智能·区块链