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);
    }
  • 测试结果
相关推荐
yyzc1111117 分钟前
AI聚合支付搭配数字门店系统让实体店告别粗放经营
大数据·运维·人工智能
Rain的Java大神之路18 分钟前
把 ThreadLocal 换成 ScopedValue 后,请求上下文为什么在子线程里"消失"了?三个边界 + 完整迁移指南(JDK 25)
java·后端·面试
inferno20 分钟前
Java正则表达式学习笔记
java·笔记·学习·正则表达式
阿enna28 分钟前
从误检和漏检出发改进YOLO26n:建立错误样本库
人工智能·python·深度学习·yolo·目标检测·机器学习·cnn
会编程的吕洞宾1 小时前
JVM频繁Full GC排查实战_后端定位与调优
java·经验分享·后端
木井巳1 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
大今野2 小时前
人工智能与区块链核心考点全解析
人工智能·区块链·uml·专转本
nice_lcj5202 小时前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
腾讯云开发者2 小时前
当 30 年 ERP 功力遇上 WorkBuddy ,哪些活儿该交出去?
人工智能
腾讯云开发者2 小时前
老板带头,全员跟上:1药网用 WorkBuddy 跑通 AI 落地的一年
人工智能