Skip to content

solvi.core.types

Typed facts: the types a catalog function's hints give the facts it reads and sets, Scale, FactTypeError.

Typed facts: a catalog function's type hints are the types of the facts it reads and sets.

@cat.fn def risk_score(risk_points: dict[str, float]) -> float: ...

  • registration: the catalog records each fact's type (cat.types, cat.readers) and checks every producer's return type against every consumer's argument type; a definite mismatch is a FactTypeError naming both functions (the check is conservative: what may pass, e.g. int | None into int, is left to run time);
  • run time: a typed part's inputs (given or computed) are validated / coerced with pydantic before the call, its output after it; a value that fails is rejected — the fact is missing (the next producer runs, else dependent answers abstain) and the step's error starts with "type rejected" (safeguard type_rejected). A Literal / Enum return type is a closed set: a value outside it is rejected as "outside the options";
  • untyped parts (no annotation, Any, object) cost nothing: nothing is validated, and pydantic is not even imported.

pydantic is imported on the first typed part (or BaseModel input, or serialization), so import solvi stays light.

FactTypeError

Bases: TypeError

A catalog error: a producer's return type cannot be what a consumer reads, or a rule's return type does not fit its question's answer type.

Spec

Spec(t, ta)

A compiled type: cls for the exact-type fast path (plain classes), the pydantic TypeAdapter, the closed set of values (Literal / Enum, else None) and a display name.

Ordinal

Marks a closed set as ordered levels, lowest first: Annotated[Literal["low", "medium", "high"], Ordinal()], or Scale["low", "medium", "high"]. An Enum class with __solvi_ordinal__ = True is ordinal too.

Scale

An ordinal type from its levels, lowest first: Scale[Literal["low", "medium", "high"]] (type checkers and linters read it as the Literal), Scale["low", "medium", "high"], Scale[1, 2, 3, 4, 5], or Scale[AnEnum] — that is Annotated[Literal[...], Ordinal()]. As a question: Answer.ordinal; as a decision: a score (see solvi.core.deciders).

SpanOf

SpanOf(source='doc')

Marks a type as a span of a text fact: Span[float] is Annotated[float, SpanOf("doc")].

RankOf

RankOf(k=None)

Marks a tuple of options as a ranking (top k): Rank[Literal[...], 2].

Bins

Bins(edges, coverage=0.8, unit=None, integer=None)

Marks a number as an estimate over bins cut at edges: Annotated[float, Bins([0, 7, 14, 30], coverage=0.9, unit="days")], or Estimate[0, 7, 14, 30] (see Answer.estimate).

Maybe

Maybe[T] is T | NotStated: the answer may be solvi.Unknown — "the text does not state it", a real answer with a confidence, distinct from "no" and from an abstention.

Span

Span[T] (or Span[T, "source"]): an exact substring of a given text fact (default "doc"), coerced to T with pydantic (Span[float]: "12.50" → 12.5). As a question: Answer.span; as a decision: a pointer over the input.

Rank

Rank[Literal["a", "b", "c"]] (or Rank[Literal[...], k], Rank[AnEnum, k]): the options best first, the top k (all by default), as a tuple. As a question: Answer.rank; as a decision: scores over the options.

Estimate

Estimate[0, 7, 14]: a number estimated over the bins cut at these edges — less than 0, 0–6, 7–13, 14 or more — with an 80% interval (Annotated[float, Bins(edges, coverage=, unit=)] for other settings). As a question: Answer.estimate; as a decision ("number"): the bins as ordered options.

type_name

type_name(t)

A short readable name: dict[str, float], Literal['a', 'b'], Invoice | None.

hints

hints(f, kind)

→ ({argument: type} for the typed arguments, or None; the return type, or None when untyped). A Quote / Decision return annotation says nothing about the fact's type (the fact is the plain value), so it counts as untyped.

span_value

span_value(vtype, text, strict=False, spec=None)

The value a typed span states (Span[float], Span[date], ...) → the value; ValueError when the text is not one. First the type's own reading of the text ("149.90", "2026-09-12") — except a number the guarded parser calls ambiguous ("2.500", "1.000": refused, as below). When that fails and the type is a date or a number (date, int, float, Decimal), the deterministic parsers of solvi.core.textin read what people write — "21 July 2026", "July 21, 2026", "18 октября 2026 г.", "21.07.2026"; "41,908.56 USD", "EUR 18,851.12", "1 500 000 руб", "1.5 million" — and refuse what would be a guess: a numeric date that reads both ways ("03/04/2026", "12.09.2026": day or month first?), a date without a year, two dates or two numbers, "1.000", a percentage. strict=True: the type's own reading only. spec: reading rules passed to the number parser as its spec (e.g. {"decimal": ","}: the document writes a dot where a comma is the decimal separator — a declaration, never a guess).

spec

spec(t, where='')

A Spec for type t, or None (with a warning) when pydantic cannot validate it.

check

check(s, v)

Validate / coerce one value → (value, None) or (None, pydantic's message).

typed_in

typed_in(part, args, known=None)

Validate / coerce a typed part's inputs → (arguments for the call, None) or (args, the rejection reason). known: fact → the type its value already passed in this run; an argument of that same type is not validated again.

typed_out

typed_out(part, value)

Validate / coerce a typed part's plain output → (value, None) or (None, the rejection reason).

compile_part

compile_part(p)

Compile a part's types (p.types, p.returns) into validators (p.tin, p.tout). A rule returning an answer primitive (Maybe, Span, Rank, Estimate) is checked when its answer is resolved instead.

compatible

compatible(p, c)

Can a value of type p be read as type c? False only for a definite mismatch (no value of p can pass as c).

register

register(catalog, p)

Check a new part's types against the catalog (raises FactTypeError before anything is changed) → a function that records them.

producers

producers(catalog, fact)

[(function name, return type)] of the typed producers of a fact.

split_unknown

split_unknown(t)

→ (t without NotStated, whether NotStated was a member). X | None keeps its None.

primitive_answer

primitive_answer(t)

A primitive type (without NotStated) → its AnswerType, or None for an ordinary type.

question_kind

question_kind(t)

A Python type → how a model decides it: (kind, values, as_bool) with kind "noul" (bool, Literal["yes", "no"]), "score" (an ordinal type: Scale[...], 2–10 levels), "multi" (list / set / tuple of a Literal or Enum) or "choice" (a Literal or Enum). X | None is X. as_bool: the decision's value is True / False (a bool type).

answer_type_of

answer_type_of(t, ordinal=False)

A Python type → an AnswerType: bool → yes_no; Literal / Enum → choice (ordinal=True, or an ordinal type such as Scale[...]: ordinal, in declaration order; Literal["yes", "no"] → yes_no); list / set / tuple of a Literal or Enum → multi. X | None is X (None = abstain).

check_answer

check_answer(rule, q)

A typed rule's return type must fit its question's answer type (raises FactTypeError).

is_model

is_model(obj)

A pydantic BaseModel instance? (pydantic is never imported for this: if it is not loaded, obj cannot be one).

state_of

state_of(obj, model=None)

init_state as a dict of given facts → (state, [(fact, rejection reason)]). A BaseModel instance gives its fields; with model (System(input_model=...)) a dict is validated against it: the model's fields (with defaults) become given facts, a field that fails validation is left out (the fact is missing) and reported; other keys pass through — unless the model forbids them (extra="forbid"): then each is left out and reported as rejected, like a field that failed. With model the facts come in the model's field order, then the other keys as they were given: the order is declared once, in the type, and does not depend on who built the dict (a decider reads a state's keys in their order).

field_types

field_types(model)

{field: annotation} of a pydantic model class (cached on the class): the types its validated fields already have.