【Spring AI】08. 输出解析器

文章目录

Output Parsers

OutputParser接口允许您获取结构化输出,例如将输出映射到 Java 类或从 AI 模型的基于字符串的输出中获取值数组。

您可以将其类比为 Spring JDBC 概念中的RowMapper或ResultSetExtractor。开发人员希望快速将 AI 模型的结果转换为可以传递给应用程序中其他函数和方法的数据类型。OutputParser有助于实现这一目标。

API 概述


本节提供了OutputParser接口的指南。

OutputParser

这里是 OutputParser 接口定义

java 复制代码
public interface OutputParser<T> extends Parser<T>, FormatProvider {

}

它继承了 Parser 接口

java 复制代码
@FunctionalInterface
public interface Parser<T> {
    T parse(String text);
}

和 FormatProvider 接口

java 复制代码
public interface FormatProvider {

	String getFormat();

}

Parser接口解析文本字符串以生成类型 T 的实例。

FormatProvider为 AI 模型提供文本指令,以便格式化输出,以便可以通过Parser将其解析为类型 T。 这些文本指令通常附加在用户输入到 AI 模型的末尾。


可用实现


OutputParser接口具有以下可用的实现。

  • BeanOutputParser:指定 Java 类的 JSON 模式,并使用 JSON 模式规范的DRAFT_2020_12,因为 OpenAI 表示这将提供最佳结果。 AI 模型的 JSON 输出然后被反序列化为 Java 对象,也就是JavaBean。
  • MapOutputParser:类似于BeanOutputParser,但 JSON 负载被反序列化为java.util.Map<String, Object>实例。
  • ListOutputParser:指定输出为逗号分隔的列表。
    近期,OpenAI 模型已经付出了相当大的努力,以提高模型通过简单指定"以 JSON 返回"的能力,但并非所有模型都支持直接支持返回结构化数据。

示例用法


您可以运行一个完全可工作的示例 Spring AI Azure Workshop,其中的一部分演示了BeanOutputParser的使用。这个工程代码的一部分如下所示。

该示例的用例是使用 AI 模型为演员生成电影作品列表。

使用的用户提示词是

java 复制代码
String userMessage = """
        Generate the filmography for the actor {actor}.
        {format}
        """;

下面显示的类 ActorsFilms

java 复制代码
public class ActorsFilms {

	private String actor;

	private List<String> movies;

    // getters and toString omitted
}

这是一个控制器类,显示了这些类的使用

java 复制代码
    @GetMapping("/ai/output")
    public ActorsFilms generate(@RequestParam(value = "actor", defaultValue = "Jeff Bridges") String actor) {
        var outputParser = new BeanOutputParser<>(ActorsFilms.class);

        String userMessage =
                """
                Generate the filmography for the actor {actor}.
                {format}
                """;

        PromptTemplate promptTemplate = new PromptTemplate(userMessage, Map.of("actor", actor, "format", outputParser.getFormat() ));
        Prompt prompt = promptTemplate.create();
        Generation generation = chatClient.call(prompt).getResult();

        ActorsFilms actorsFilms = outputParser.parse(generation.getOutput().getContent());
        return actorsFilms;
    }

相关推荐
YYXZZ。。35 分钟前
PyTorch——搭建小实战和Sequential的使用(7)
人工智能·pytorch·python
四川兔兔38 分钟前
pytorch 与 张量的处理
人工智能·pytorch·python
AI蜗牛之家4 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
王上上4 小时前
【论文阅读30】Bi-LSTM(2024)
论文阅读·人工智能·lstm
whyeekkk5 小时前
python打卡第48天
开发语言·python
YunTM5 小时前
贝叶斯优化+LSTM+时序预测=Nature子刊!
人工智能·机器学习
舒一笑6 小时前
智能体革命:企业如何构建自主决策的AI代理?
人工智能
Chan167 小时前
【 SpringCloud | 微服务 MQ基础 】
java·spring·spring cloud·微服务·云原生·rabbitmq
丁先生qaq7 小时前
热成像实例分割电力设备数据集(3类,838张)
人工智能·计算机视觉·目标跟踪·数据集
Eiceblue7 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf