Output Parsers

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

The OutputParser interface allows you to obtain structured output, for example mapping the output to a Java class or an array of values from the String based output of AI Models.

你可以从类似于 Spring JDBC 的 RowMapperResultSetExtractor 的概念的角度对其进行考虑。开发者希望快速地将 AI 模型的结果转换为可以传递给其应用程序中的其他函数和方法的数据类型。OutputParser 有助于实现此目标。

You can think of it in terms similar to Spring JDBC’s concept of a RowMapper or ResultSetExtractor. Developers want to quickly turn results from an AI model into data types that can be passed to other functions and methods in their application. The OutputParser helps achieve that goal.

API Overview

此部分提供了有关 OutputParser 接口的指南。

This section provides a guide to the OutputParser interface.

OutputParser

以下是 OutputParser 接口定义

Here is the OutputParser interface definition

public interface OutputParser<T> extends Parser<T>, FormatProvider {

}

它结合了 Parser<T> 接口

It combines the Parser<T> interface

@FunctionalInterface
public interface Parser<T> {
    T parse(String text);
}

FormatProvider 接口

and the FormatProvider interface

public interface FormatProvider {

	String getFormat();

}

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

The Parser interface parses text strings to produce instances of the type T.

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

The FormatProvider provides text instructions for the AI Model to format the output so that it an be parsed into the type T by the Parser. These text instructions are most often appended to the end of the user input to the AI Model.

Available Implementations

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

The OutputParser interface has the following available implementations.

  • BeanOutputParser: Specifies the JSON schema for Java class and uses DRAFT_2020_12 of the JSON schema specification as OpenAI has indicated this would give the best results. The JSON output of the AI Model is then deserialized to a Java object, aka JavaBean.

  • MapOutputParser: Similar to BeanOutputParser but the JSON payload is deserialized into a java.util.Map<String, Object> instance.

  • ListOutputParser: Specifies the output to be a comma delimited list.

最近 OpenAI 模型在通过简单指定“以 JSON 格式返回”来提高模型返回 JSON 的能力方面已经付出了大量努力,但并非所有模型都支持对返回结构化数据进行此类直接支持。

There has been considerable effort in recent OpenAI models to improve the model’s ability to return JSON by simply specifying 'return in JSON', but not all models support such direct support for returning structured data.

Example Usage

您可以运行一个完全可行示例,演示如何将 BeanOutputParser 用作 Spring AI Azure Workshop 的一部分。本文档中再现了此研讨会代码的一部分。

You can run a fully working example that demonstrates the use of BeanOutputParser as part of the Spring AI Azure Workshop. Part of this workshop code is reproduced below.

此示例的用例是使用 AI 模型生成某个演员的影视作品资料。

The use case for the example is to use the AI Model to generate the filmography for an actor.

使用的用户提示是

The User prompt used is

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

在下方显示的 ActorsFilms

The class ActorsFilms shown below

public class ActorsFilms {

	private String actor;

	private List<String> movies;

    // getters and toString omitted
}

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

Here is a controller class that shows these classes in use

    @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;
    }