Schema & Types (schema.py)
On this page
schema.py is the shared type module for the whole package — every enum and dataclass listed here is imported by at least one other module. It has no dependency on any other module in the package (leaf module in the dependency graph), only on pydantic (optional).
PYDANTIC_AVAILABLE
try:
from pydantic import BaseModel, Field, field_validator
PYDANTIC_AVAILABLE = True
except ImportError:
PYDANTIC_AVAILABLE = False
BaseModel = object
A module-level boolean flag other modules check to decide whether to use Pydantic-based schemas or the dataclass fallbacks. When False, BaseModel is aliased to plain object, and the four schema classes below (AnswerSchema, ToolCallSchema, RetrievalResultSchema, RankedAnswersSchema) are defined as @dataclass instead of Pydantic models.
Enums
OutputFormat
class OutputFormat(Enum):
JSON = "json"
YAML = "yaml"
CSV = "csv"
MARKDOWN_TABLE = "markdown_table"
NUMBERED_LIST = "numbered_list"
BULLETED_LIST = "bulleted_list"
KEY_VALUE = "key_value"
XML = "xml"
TOOL_CALL = "tool_call"
PLAIN_TEXT = "plain_text"
MIXED = "mixed"
UNKNOWN = "unknown"
See Concepts → Output formats for the meaning of each value and how FormatDetector assigns them.
ParseMode
class ParseMode(Enum):
STRICT = "strict"
LENIENT = "lenient"
SEMANTIC = "semantic"
TOOL_CALL = "tool_call"
ValidationStatus
class ValidationStatus(Enum):
PASSED = auto()
FAILED = auto()
WARNING = auto()
SKIPPED = auto()
Result status of a single validation check performed by OutputValidator or ValidationRule.
FixStrategy
class FixStrategy(Enum):
REGEX_REPAIR = "regex_repair"
LLM_REFORMAT = "llm_reformat"
FIELD_INJECTION = "field_injection"
FALLBACK_PARSE = "fallback_parse"
NONE = "none"
Identifies which repair strategy OutputFixer.fix() successfully applied (or NONE if all failed). See fixer.md.
Dataclasses
ValidationResult
@dataclass
class ValidationResult:
status: ValidationStatus
field: Optional[str] = None
message: str = ""
value: Any = None
Properties
passed: bool—Trueiffstatus == ValidationStatus.PASSED.
__repr__: ValidationResult(STATUS, field='...', msg='...').
ParseTrace
@dataclass
class ParseTrace:
raw_input: str
detected_format: OutputFormat = OutputFormat.UNKNOWN
parse_mode: ParseMode = ParseMode.LENIENT
fix_applied: FixStrategy = FixStrategy.NONE
retries: int = 0
validations: List[ValidationResult] = field(default_factory=list)
errors: List[str] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
duration_ms: float = 0.0
timestamp: float = field(default_factory=time.time)
success: bool = False
The full audit trail of a single OutputParser.parse() call — every stage of the pipeline appends to this object.
Methods
add_error(msg: str) -> None— appends toself.errors.add_warning(msg: str) -> None— appends toself.warnings.add_validation(result: ValidationResult) -> None— appends toself.validations.summary() -> Dict[str, Any]— returns a compact dict:success,detected_format(.value),parse_mode(.value),fix_applied(.value),retries,errors,warnings,validation_passed(count),validation_failed(count),duration_ms(rounded to 2 decimals). This is the recommended shape to log/serialize rather than the full dataclass.
trace = result.trace
print(trace.summary())
# {
# "success": True, "detected_format": "json", "parse_mode": "lenient",
# "fix_applied": "none", "retries": 0, "errors": [], "warnings": [],
# "validation_passed": 2, "validation_failed": 0, "duration_ms": 0.34
# }
ParseResult
@dataclass
class ParseResult:
data: Any
schema_type: Optional[type] = None
trace: Optional[ParseTrace] = None
raw: str = ""
The object returned by every OutputParser.parse() call.
Properties
ok: bool—Trueiffself.data is not None. Note this means a successfully parsed falsy value that isn'tNone(e.g. an empty list[]fromListOutputParser-style extraction inside the orchestrator, or0/False/"") still counts asok = True; onlyNoneitself is treated as failure.
Methods
as_typed(schema_cls: Type) -> Any— ifself.datais already an instance ofschema_cls, returns it unchanged. If it's adict, attemptsschema_cls(**self.data). Otherwise raisesTypeError(f"Cannot cast {type(self.data)} to {schema_cls}").
__repr__: ParseResult(ok=True, type=dict).
FieldSchema
@dataclass
class FieldSchema:
name: str
description: str
dtype: str = "str" # str | int | float | bool | list | dict
required: bool = True
aliases: List[str] = field(default_factory=list)
default: Any = None
choices: Optional[List[Any]] = None
Declares one field expected in an LLM output, used by OutputParser(fields=...), OutputValidator, and OutputFixer.
VALID_DTYPES = {"str", "int", "float", "bool", "list", "dict"} — __post_init__ raises ValueError if dtype is outside this set.
Properties
all_names: List[str]—[self.name] + self.aliases.
Methods
validate_value(value: Any) -> ValidationResult— ifvalue is Noneandrequired, returnsFAILED("Required field ... is missing"); ifvalue is Noneand not required, returnsSKIPPED. Ifchoicesis set andvalueisn't among them, returnsFAILED. OtherwisePASSED.
Raises: ValueError in __post_init__ if dtype is invalid.
FieldSchema("confidence", "Confidence score 0-1", dtype="float", required=False, default=1.0)
Built-in Pydantic Schemas
Defined conditionally on PYDANTIC_AVAILABLE. When True, these are pydantic.BaseModel subclasses; when False, they are plain @dataclass equivalents with the same field names but no runtime validation, coercion, or the _clamp_confidence validator described below.
AnswerSchema
class AnswerSchema(BaseModel):
answer: str
sources: List[str] = []
confidence: float = 1.0 # clamped to [0.0, 1.0]
reasoning: Optional[str] = None
The standard RAG answer schema used throughout the package (create_answer_parser, build_answer_validator, build_answer_fixer all target this shape).
answer— required.sources— optional, defaults to[].confidence— optional, defaults to1.0, constrainedge=0.0, le=1.0at the Pydantic field level, and additionally clamped via a@field_validator("confidence", mode="before")classmethod_clamp_confidence: attemptsfloat(v), thenmax(0.0, min(1.0, f)); if the value can't be converted tofloatat all (TypeError/ValueError), it silently defaults to1.0rather than raising a validation error. This means an out-of-range or malformed confidence value from an LLM (e.g."very confident"or1.5) will never causeAnswerSchemaconstruction to fail — it will be silently coerced.reasoning— optional chain-of-thought field, defaults toNone.
ToolCallSchema
class ToolCallSchema(BaseModel):
tool_name: str
arguments: Dict[str, Any] = {}
thought: Optional[str] = None
Schema for LLM tool/function-call outputs — mirrors the shape produced by _parse_tool_call in parser.py.
RetrievalResultSchema
class RetrievalResultSchema(BaseModel):
content: str
source: Optional[str] = None
score: Optional[float] = None # ge=0.0, le=1.0
metadata: Dict[str, Any] = {}
Represents a single retrieved document/chunk in a RAG pipeline.
RankedAnswersSchema
class RankedAnswersSchema(BaseModel):
answers: List[AnswerSchema] # min_length=1
best_index: int = 0 # ge=0
Multiple candidate answers with a pointer to the best one.
Properties
best: AnswerSchema— returnsself.answers[self.best_index]. Note: no bounds checking is performed here beyond Pydantic'sge=0constraint onbest_indexat construction time — ifbest_indexis set to a value ≥len(answers)after construction (or via a validator that doesn't catch it), accessing.bestwill raiseIndexErrorat access time, not at validation time.
Related APIs
OutputParser— primary consumer ofParseResult,ParseTrace,FieldSchema.OutputValidator— consumesFieldSchema, producesValidationResult.OutputFixer— consumes/producesFixStrategy.FormatDetector— producesOutputFormat.
Version History
Not determinable from source.