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

Python · 6 lines
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

Python · 13 lines
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

Python · 5 lines
class ParseMode(Enum):
    STRICT = "strict"
    LENIENT = "lenient"
    SEMANTIC = "semantic"
    TOOL_CALL = "tool_call"

See Concepts → Parse modes.

ValidationStatus

Python · 5 lines
class ValidationStatus(Enum):
    PASSED = auto()
    FAILED = auto()
    WARNING = auto()
    SKIPPED = auto()

Result status of a single validation check performed by OutputValidator or ValidationRule.

FixStrategy

Python · 6 lines
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

Python · 6 lines
@dataclass
class ValidationResult:
    status: ValidationStatus
    field: Optional[str] = None
    message: str = ""
    value: Any = None

Properties

  • passed: bool — True iff status == ValidationStatus.PASSED.

__repr__: ValidationResult(STATUS, field='...', msg='...').

ParseTrace

Python · 13 lines
@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 to self.errors.
  • add_warning(msg: str) -> None — appends to self.warnings.
  • add_validation(result: ValidationResult) -> None — appends to self.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.
Python · 7 lines
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

Python · 6 lines
@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 — True iff self.data is not None. Note this means a successfully parsed falsy value that isn't None (e.g. an empty list [] from ListOutputParser-style extraction inside the orchestrator, or 0/False/"") still counts as ok = True; only None itself is treated as failure.

Methods

  • as_typed(schema_cls: Type) -> Any — if self.data is already an instance of schema_cls, returns it unchanged. If it's a dict, attempts schema_cls(**self.data). Otherwise raises TypeError(f"Cannot cast {type(self.data)} to {schema_cls}").

__repr__: ParseResult(ok=True, type=dict).

FieldSchema

Python · 9 lines
@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 — if value is None and required, returns FAILED ("Required field ... is missing"); if value is None and not required, returns SKIPPED. If choices is set and value isn't among them, returns FAILED. Otherwise PASSED.

Raises: ValueError in __post_init__ if dtype is invalid.

Python
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

Python · 5 lines
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 to 1.0, constrained ge=0.0, le=1.0 at the Pydantic field level, and additionally clamped via a @field_validator("confidence", mode="before") classmethod _clamp_confidence: attempts float(v), then max(0.0, min(1.0, f)); if the value can't be converted to float at all (TypeError/ValueError), it silently defaults to 1.0 rather than raising a validation error. This means an out-of-range or malformed confidence value from an LLM (e.g. "very confident" or 1.5) will never cause AnswerSchema construction to fail — it will be silently coerced.
  • reasoning — optional chain-of-thought field, defaults to None.

ToolCallSchema

Python · 4 lines
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

Python · 5 lines
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

Python · 3 lines
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 — returns self.answers[self.best_index]. Note: no bounds checking is performed here beyond Pydantic's ge=0 constraint on best_index at construction time — if best_index is set to a value ≥ len(answers) after construction (or via a validator that doesn't catch it), accessing .best will raise IndexError at access time, not at validation time.

Version History

Not determinable from source.

Related pages