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 天前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
腾讯云开发者1 天前
港科大郭毅可谈Agentic AI时代的核心命题:人机共生,人不可能退场
人工智能
常丛丛1 天前
5.6 LangGraph-Edges理解-Agent图的道路系统
人工智能
雪隐1 天前
个人电脑玩AI-08让5060 Ti给你打工——我拿 Unlimited-OCR扫了 600 页书,然后悟了
人工智能·后端
Coffeeee1 天前
Prompt要花心思写,与 AI 对话的七个技巧
人工智能·aigc·ai编程
蝎子莱莱爱打怪1 天前
Claude Code 官宣新升级:子智能体默认后台跑,你边聊它边干活
人工智能
武子康1 天前
调查研究-206 DeepSeek DSpark 深度解析:大模型推理加速,正在从“模型能力”转向“系统工程”
人工智能·agent·deepseek
NE_STOP1 天前
Vibe Coding -- 完整项目案例实操
java
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing1 天前
Google第三方授权登录
java·后端·程序员