Skip to content

Python API

The public API is what import schemaguru as sg exposes (spec §19). It is stable within a 0.x minor release. Everything below is rendered from the source docstrings.

import schemaguru as sg

print(sorted(n for n in sg.__all__ if n[0].isupper()))

The façade

schemaguru.Guru

Schema intelligence for one warehouse: crawl, measure, draft, overlay, scope, render.

diagnostics property

diagnostics: tuple[Diagnostic, ...]

Every distinct diagnostic the façade has seen (overlays, rules, chains, wiring).

connect classmethod

connect(url: str, *, name: str = 'default', store: Store | str | PathLike[str] | None = None, config: Config | None = None, backend: MeasureBackend | None = None, crawl: bool | None = None) -> Guru

Open url through the FactLang seam (built-in DuckDB fallback) and build a Guru.

The store defaults to ./.schemaguru/<name>.db. crawl=None crawls the catalog (metadata only) when the store holds no table yet, so the three-line quickstart works; True always crawls, False never.

crawl

crawl(*, include: Sequence[str] | None = None, exclude: Sequence[str] | None = None) -> CrawlReport

Index the catalog (metadata only); include/exclude override the config.

measure

measure(targets: Target | Iterable[Target] | None = None, *, all: bool = False, budget: Budget | None = None) -> MeasureReport

Measure targets (names or globs); with none, drain the queue (spec 8.2).

all=True measures every live table, hottest first (feedback, declared foreign keys, log row count). budget replaces the configured one for this run.

measure_queue

measure_queue() -> MeasureReport

Drain the measurement queue (first-touch and feedback tables) under the budget.

refresh

refresh(*, label: str | None = None) -> RefreshReport

Incremental crawl, re-measure stale/changed tables, snapshot and classify (spec 15).

draft

draft(targets: Target | Iterable[Target], *, provider: LLMProvider, budget: Budget | int | None = None, verify: bool = True) -> DraftReport

Draft table meaning with an LLM (never on the query path); verify checkable parts.

accept

accept(ids: Iterable[str], *, write_overlay: str | PathLike[str] | None = None) -> list[Fact]

Turn drafted facts into HUMAN facts; optionally append them to an accepted overlay.

verify

verify(facts_or_claims: str, exact: bool = False) -> list[Evidence]
verify(facts_or_claims: Sequence[Fact], exact: bool = False) -> list[Fact]
verify(facts_or_claims: str | Sequence[Fact], exact: bool = False) -> list[Evidence] | list[Fact]

Check FactLang claim text, or facts: drafts become claims (spec 10.3).

Claims are never sampled. With exact=True the tables behind sampled (ESTIMATED) measurements are re-measured exactly within budget, and the exact facts are appended (a sample can refute but never confirm, spec 8.6).

load_overlays

load_overlays(*paths: str | PathLike[str]) -> list[Diagnostic]

Load human overlay files/directories (spec 14); returns this load's diagnostics.

Never raises on data. Replaces the previously loaded rules, chains, waivers and overlay facts: an entry removed from its file (or a file no longer passed) has its facts retracted, except for a file that failed to load, which keeps them until it loads again. A human soft-delete filter that does not fit the catalog or the measured values is reported (SG210) and shown with a warning, never applied silently.

find_path

find_path(a: Target, b: Target, *, k: int | None = None) -> PathResult

Measured join routes between two tables, or a typed refusal (spec 9).

context

context(question: str, *, budget_tokens: int = 4000, profile: str = 'agent', format: str = 'text') -> ContextView

The question-scoped view an agent reads (spec 12, 13); str(view) is format.

Read-only apart from the measurement queue: shown tables that were never measured are enqueued. It spends warehouse money only when Config.measure_on_demand says so.

fingerprint_views

fingerprint_views(questions: Iterable[str]) -> dict[str, str]

{question: fingerprint} for a host's CI to detect prompt drift (spec 13.4).

report_error

report_error(sql: str, error: str, dialect: str | None = None) -> int

Record a failed agent query (identifiers and counts only); never raises (spec 16).

feedback_summary

feedback_summary() -> list[dict[str, object]]

export

export(path: str | PathLike[str]) -> None

Byte-deterministic JSON export of the store (spec 7.3).

tools

tools() -> list[dict[str, Any]]

JSON-schema tool specs (name, description, input_schema).

handle_tool_call

handle_tool_call(name: str, args: Mapping[str, Any]) -> dict[str, Any]

Run one tool; always JSON with a text field, never raises (errors: SG8xx).

prompt_block

prompt_block(question: str | None = None) -> str

A system-prompt fragment: how to use the tools, the legend; with a question, its view.

close

close() -> None

Stop the drainer and wait for in-flight runs, then close what this Guru opened.

Configuration

schemaguru.Config dataclass

from_env classmethod

from_env(prefix: str = 'SCHEMAGURU_', *, environ: Mapping[str, str] | None = None) -> Config

PREFIX_FIELD sets a top-level field, PREFIX_SECTION__FIELD a nested one.

Values are parsed as YAML scalars (7 -> int, true -> bool, none stays text).

schemaguru.Budget dataclass

schemaguru.SamplingConfig dataclass

schemaguru.GraphConfig dataclass

schemaguru.ScopeConfig dataclass

schemaguru.CrawlConfig dataclass

Knowledge model

schemaguru.ObjectRef dataclass

parse classmethod

parse(text: str, *, has_column: bool | None = None) -> ObjectRef

Inverse of :meth:canonical.

A bare schema.table.column is ambiguous with catalog.schema.table; so four parts always mean a column, and with fewer parts pass has_column=True to read the last part as the column (default: a table reference).

schemaguru.JoinRef dataclass

identity_key

identity_key() -> str

Canonical form plus cast_to: two joins differing only in cast are distinct facts.

schemaguru.Fact dataclass

make classmethod

make(kind: KindSpec | str, subject: ObjectRef | JoinRef, value: Mapping[str, Any], provenance: Provenance, status: Status, *, method: str | None = None, evidence: Evidence | None = None, source: str | None = None, observed_at: datetime | None = None, snapshot_id: str | None = None) -> Fact

Build a fact; the id is always computed (never supplied).

from_dict classmethod

from_dict(d: Mapping[str, Any]) -> Fact

The fact d describes. The id is recomputed, never trusted: a stored id that does not match the fact's identity raises ValueError("fact id mismatch ..."). A dict whose keys were integers when hashed (they come back from JSON as text) is also checked in its original numeric key order.

schemaguru.FactKind

The built-in kinds (spec 4.3 table).

schemaguru.Provenance

Bases: Enum

schemaguru.Status

Bases: Enum

Results

schemaguru.ContextView dataclass

What an agent reads for one question (spec 13.1).

schemaguru.PathResult dataclass

schemaguru.Refusal

Bases: Enum

schemaguru.RefreshReport dataclass

schemaguru.Diagnostic dataclass

schemaguru.SchemaGuruError

Bases: Exception

Base class of every exception SchemaGuru raises on purpose.

Helpers

schemaguru.guard.check_sql

check_sql(sql: str, dialect: str | None = None, *, never_query: Collection[ObjectRef] = ()) -> GuardVerdict

Verdict on one statement of agent SQL (see the module docstring for the limits).

Subpackages

The subpackages sg.catalog, sg.measure, sg.draft, sg.render, sg.scope, sg.graph, sg.pii, sg.overlays and sg.guard hold the extension points and building blocks; see Extending. The agent surface is schemaguru.agent (tools, dispatcher, prompt block), schemaguru.agent.mcp and schemaguru.agent.adapters.*; see Agents, tools and MCP.