Package com.tnsai.parser
Class JsonOutputParser<T>
java.lang.Object
com.tnsai.parser.JsonOutputParser<T>
- Type Parameters:
T- the target type
- All Implemented Interfaces:
OutputParser<T>
JSON-based output parser that converts LLM JSON output into Java objects.
Features:
- Automatic JSON extraction from markdown code blocks
- Support for Java Records and POJOs
- Field validation with annotations
- Detailed error messages for LLM correction
Usage
// For a record
record Person(String name, int age) {}
JsonOutputParser<Person> parser = JsonOutputParser.forType(Person.class);
// Parse LLM output (handles JSON in markdown blocks too)
ParseResult<Person> result = parser.parse("""
Here's the person data:
```json
{"name": "John", "age": 30}
```
""");
Person person = result.get();
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for JsonOutputParser. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> JsonOutputParser.Builder<T> Creates a builder for customizing the parser.static <T> JsonOutputParser<T> Creates a parser for the given type with default settings.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.Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface com.tnsai.parser.OutputParser
getErrorCorrectionPrompt, parseOptional, parseOrThrow
-
Method Details
-
forType
Creates a parser for the given type with default settings.- Type Parameters:
T- the type- Parameters:
targetType- the target class- Returns:
- new parser
-
builder
Creates a builder for customizing the parser.- Type Parameters:
T- the type- Parameters:
targetType- the target class- Returns:
- new builder
-
parse
Description copied from interface:OutputParserParses the raw LLM output into the target type.- Specified by:
parsein interfaceOutputParser<T>- Parameters:
output- the raw string output from the LLM- Returns:
- parse result containing either the parsed object or error details
-
getTargetType
Description copied from interface:OutputParserReturns the target class this parser produces.- Specified by:
getTargetTypein interfaceOutputParser<T>- Returns:
- the target class
-
getFormatInstruction
Description copied from interface:OutputParserReturns a format instruction string to include in the LLM prompt.This helps guide the LLM to produce output in the expected format.
- Specified by:
getFormatInstructionin interfaceOutputParser<T>- Returns:
- format instruction for the prompt
-
getSchemaDescription
Description copied from interface:OutputParserReturns a schema description of the expected output format.- Specified by:
getSchemaDescriptionin interfaceOutputParser<T>- Returns:
- schema description (e.g., JSON Schema, example)
-