Package com.tnsai.parser
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 Summary
Modifier and TypeMethodDescriptiondefault StringgetErrorCorrectionPrompt(String failedOutput, String error) Generates an error correction prompt when parsing fails.Returns a format instruction string to include in the LLM prompt.Returns a schema description of the expected output format.Returns the target class this parser produces.Parses the raw LLM output into the target type.parseOptional(String output) Parses the output, returning empty Optional on failure.default TparseOrThrow(String output) Parses the output, throwing an exception on failure.
-
Method Details
-
parse
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
Parses the output, throwing an exception on failure.- Parameters:
output- the raw string output- Returns:
- the parsed object
- Throws:
ParseException- if parsing fails
-
parseOptional
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
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
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 parseerror- the error message- Returns:
- a prompt asking the LLM to correct its output
-