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);
    }
  • 测试结果
相关推荐
代码AI弗森1 小时前
一文理清楚“算力申请 / 成本测算 / 并发评估”
java·服务器·数据库
马丁聊GEO1 小时前
解码AI用户心智,筑牢可信GEO根基——悠易科技深度参与《中国AI用户态度与行为研究报告(2026)》发布会
人工智能·科技
nap-joker1 小时前
Fusion - Mamba用于跨模态目标检测
人工智能·目标检测·计算机视觉·fusion-mamba·可见光-红外成像融合·远距离/伪目标问题
一只幸运猫.1 小时前
2026Java 后端面试完整版|八股简答 + AI 大模型集成技术(最新趋势)
人工智能·面试·职场和发展
Old Uncle Tom1 小时前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
Promise微笑1 小时前
2026年国产替代油介损测试仪:油介损全场景解决方案与技术演进
大数据·网络·人工智能
深海鱼在掘金1 小时前
深入浅出 LangChain —— 第三章:模型抽象层
人工智能·langchain·agent
小小小米粒1 小时前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
生信碱移1 小时前
PACells:这个方法可以鉴定疾病/预后相关的重要细胞亚群,作者提供的代码流程可以学习起来了,甚至兼容转录组与 ATAC 两种数据类型!
人工智能·学习·算法·机器学习·数据挖掘·数据分析·r语言
workflower2 小时前
具身智能行业应用-生活服务业
大数据·人工智能·机器人·动态规划·生活