Interface OutputParser<T>

Type Parameters:
T - the target type to parse into
All Known Implementing Classes:
FormatAwareOutputParser, JsonOutputParser, RetryableParser

public interface OutputParser<T>
Type-safe output parser interface for parsing LLM responses into structured Java objects.

Parsers validate that LLM outputs match expected schemas before returning them to the application, ensuring type safety and data integrity.

Usage


 // Define your output type
 record WeatherResponse(String location, double temperature, String condition) {}

 // Create parser
 OutputParser<WeatherResponse> parser = JsonOutputParser.forType(WeatherResponse.class);

 // Parse LLM output
 ParseResult<WeatherResponse> result = parser.parse(llmOutput);
 if (result.isSuccess()) {
     WeatherResponse weather = result.get();
 } else {
     String error = result.getError();
 }
 
  • Method Details

    • parse

      ParseResult<T> parse(String output)
      Parses the raw LLM output into the target type.
      Parameters:
      output - the raw string output from the LLM
      Returns:
      parse result containing either the parsed object or error details
    • parseOrThrow

      default T parseOrThrow(String output) throws ParseException
      Parses the output, throwing an exception on failure.
      Parameters:
      output - the raw string output
      Returns:
      the parsed object
      Throws:
      ParseException - if parsing fails
    • parseOptional

      default Optional<T> parseOptional(String output)
      Parses the output, returning empty Optional on failure.
      Parameters:
      output - the raw string output
      Returns:
      Optional containing the parsed object, or empty if parsing failed
    • getTargetType

      Class<T> getTargetType()
      Returns the target class this parser produces.
      Returns:
      the target class
    • getFormatInstruction

      String getFormatInstruction()
      Returns a format instruction string to include in the LLM prompt.

      This helps guide the LLM to produce output in the expected format.

      Returns:
      format instruction for the prompt
    • getSchemaDescription

      String getSchemaDescription()
      Returns a schema description of the expected output format.
      Returns:
      schema description (e.g., JSON Schema, example)
    • getErrorCorrectionPrompt

      default String getErrorCorrectionPrompt(String failedOutput, String error)
      Generates an error correction prompt when parsing fails.

      This can be used in retry logic to ask the LLM to fix its output.

      Parameters:
      failedOutput - the output that failed to parse
      error - the error message
      Returns:
      a prompt asking the LLM to correct its output