ocracy.kit#

The facade kit: the three helpers every fleet facade used to copy by hand.

One interface over many backends needs the same three mechanisms whatever the backends do, and until this kit each facade (ocracy, scribed, denote, arioso, illustration, aix, foley, falaw, voxy) carried its own drifting copy:

  • translation – canonical kwargs -> native kwargs from a declared param_map, with an unsupported-parameter policy that never drops silently (every drop and clamp comes back as a note);

  • credentials – the key chain (explicit -> bound in context -> env -> store -> prompt), whose error names the env vars and where to get a key;

  • install – per-OS install plans an agent can act on;

  • ledger – the filterable catalog over a facade’s backends.json, with implemented computed from its registry.

Usage:

from ocracy.kit import make_translator, resolve_credential, using_credentials

translate = make_translator(BACKEND_CONFIG["param_map"], backend="acme",
                            on_unsupported="note", always_raise=("seed",))
t = translate(canonical_kwargs)        # t.kwargs, t.notes, t.dropped
key = resolve_credential("acme", env_var="ACME_API_KEY", api_key=api_key)

Every module here is stdlib-only and imports nothing from ocracy outside ocracy.kit, so the kit can move to its own distribution without a rewrite. The decisions behind its shape are in docs/adr/0001-facade-kit.md.

Functions

make_translator(param_map, *[, backend, ...])

Build translate(kwargs, *, on_unsupported=None) -> Translation from a map.

check_range(name, value, spec)

Raise ValueError unless value fits spec's min/max/choices.

resolve_credential([provider, api_key, ...])

Resolve a provider's credential through the chain in the module docstring.

using_credentials([keys])

Bind provider keys for the with block (overlaying any outer binding).

current_credentials()

The provider keys bound in this context by using_credentials() (a copy).

env_var_names([provider, env_var, ...])

The env vars the chain checks: env_var first, then the provider's row.

credential_help(provider, *[, guidance])

A short, link-bearing "how to get a key" line for provider (or '').

credential_lines(env_var, provider, *[, ...])

export VAR  (get a key: URL) lines for an install plan (empty if no var).

credential_rows(provider_env_vars[, ...])

Declared-credential rows from the kit's tables, one per provider.

read_declared_credentials([group])

(rows, problems): every installed package's declared credentials.

build_requirements(backend_id, *, package, ...)

Build Requirements for backend_id from its recipe and known facts.

run_install(req, *, package[, yes, ...])

Plan (default) or run (yes=True) the pip install that req describes.

current_platform()

'darwin', 'linux', 'windows', or sys.platform for anything else.

Classes

Translation([kwargs, notes, dropped])

What a translator produced: the native kwargs, and every change it made.

Requirements(backend_id, implemented, ...[, ...])

What a backend needs to run, structured for an agent to act on.

Catalog([path, records, default_path, ...])

A filterable, dict-like collection of BackendInfo, keyed by id.

BackendInfo(record, *[, implemented])

One backend's ledger entry: a read-only record, by key or by attribute.

Exceptions

UnsupportedParameter

A backend cannot honour a parameter, and the policy says not to drop it.

MissingCredentialError([message, provider, ...])

A required credential could not be resolved; the message says how to get one.

class ocracy.kit.BackendInfo(record, *, implemented=False)[source]#

Bases: Mapping

One backend’s ledger entry: a read-only record, by key or by attribute.

New fields added to the JSON are available at once (info.price_note, info["price_note"]) with no code change; a few common fields get typed properties.

property id: str#

The backend id ("" if absent).

property implemented: bool#

Whether a working facade exists for this backend.

property is_local: bool#

Whether the engine runs locally.

property is_remote: bool#

Whether the engine is a remote service.

property name: str#

The display name, falling back to the id.

to_dict()[source]#

A plain-dict copy of the record.

Return type:

dict

class ocracy.kit.Catalog(path=None, *, records=None, default_path=None, env_var=None, implemented=<function _nothing_implemented>, text_fields=frozenset({'beyond_text', 'languages_note', 'output_formats'}), capability_suffixes=(), compare_fields=('name', 'is_local', 'is_remote', 'open_source', 'pricing_model', 'price_note', 'accuracy_tier', 'languages_count', 'best_for'))[source]#

Bases: Mapping

A filterable, dict-like collection of BackendInfo, keyed by id.

Loaded lazily from path, else from the env_var environment variable, else from default_path; a missing file is an empty catalog. records gives the records directly instead. filter() returns a new Catalog with the same settings over the matching subset, so filters compose:

catalog.filter(is_remote=True).filter(pricing_model="free_tier_then_paid")
Parameters:
  • path (Union[str, Path, None]) – The ledger JSON (a {"backends": [...]} object or a bare list).

  • records (Optional[List[dict]]) – The records themselves, instead of a file.

  • default_path (Union[str, Path, None]) – Where the ledger lives when neither path nor the environment says otherwise.

  • env_var (Optional[str]) – An environment variable that overrides default_path.

  • implemented (Callable[[], Iterable[str]]) – Returns the ids that have a working adapter; called once, on first load (a filtered subset reuses the flags already computed). An exception it raises propagates: catch it in the binding if a broken registry should read as “nothing implemented”.

  • text_fields (Iterable[str]) – Fields filtered by case-insensitive membership.

  • capability_suffixes (Iterable[str]) – Extra field-name suffixes can() checks besides the capability’s own field: ("_formula",) makes can("math") also read math_formula.

  • compare_fields (Iterable[str]) – Default columns of compare().

text_fields, capability_suffixes and compare_fields take collections of names; a bare string is refused rather than split into letters. A subclass binding a facade’s data should keep no derived state of its own: filter() builds a subset from these settings alone.

can(capability)[source]#

Backends with capability: listed in beyond_text, or a field set.

A field counts when it is named capability, or that plus one of the catalog’s capability_suffixes, and its value is one of CAPABILITY_VALUES.

Return type:

Catalog

compare(ids=None, *, fields=None)[source]#

A trimmed, side-by-side view of selected backends and fields.

Return type:

List[dict]

filter(*, predicate=None, implemented=None, **criteria)[source]#

Return a new Catalog of backends matching every criterion.

Parameters:
  • predicate (Optional[Callable[[BackendInfo], bool]]) – An arbitrary BackendInfo -> bool callable.

  • implemented (Optional[bool]) – If set, keep only (un)implemented backends.

  • **criteria (Any) – field=value constraints. value may be a set/list/tuple meaning “one of”. The catalog’s text fields (by default languages_note, beyond_text, output_formats) use a case-insensitive substring match.

Return type:

Catalog

Example:

catalog.filter(is_local=True, open_source=True)
property ids: List[str]#

All backend ids, sorted.

supports_language(language)[source]#

Backends whose languages_note mentions language (name or code).

Return type:

Catalog

to_dataframe(*, columns=None)[source]#

Return a pandas DataFrame of the catalog (pandas imported lazily).

to_records()[source]#

All records as plain dicts.

Return type:

List[dict]

exception ocracy.kit.MissingCredentialError(message='', *, provider=None, env_vars=(), get_key_url=None)[source]#

Bases: RuntimeError

A required credential could not be resolved; the message says how to get one.

provider#

The provider id asked for (or None).

env_vars#

The env vars that were checked, in order.

get_key_url#

Where to get a key, when the guidance table knows.

class ocracy.kit.Requirements(backend_id, implemented, available, is_local, is_remote, pip_command, extra=None, system=list(), system_note=None, gpu=None, weights=None, heavy=False, alternative=None, credentials=list(), notes=list(), verify_command=None, alternative_label='Lighter alternative')[source]#

Bases: object

What a backend needs to run, structured for an agent to act on.

instructions()[source]#

An agent- and human-readable, copy-pasteable install plan.

Return type:

str

class ocracy.kit.Translation(kwargs=dict(), notes=list(), dropped=list())[source]#

Bases: object

What a translator produced: the native kwargs, and every change it made.

kwargs#

The native kwargs to pass to the backend.

Type:

dict

notes#

One human-readable line per drop or clamp, for the facade’s result.

Type:

list

dropped#

The canonical names that were dropped.

Type:

list

exception ocracy.kit.UnsupportedParameter[source]#

Bases: ValueError

A backend cannot honour a parameter, and the policy says not to drop it.

ocracy.kit.build_requirements(backend_id, *, package, implemented, available, recipe=None, is_local=False, is_remote=False, ledger_pip='', credentials=(), platform=None, verify_command=None, unimplemented_note=None, alternative_label='Lighter alternative')[source]#

Build Requirements for backend_id from its recipe and known facts.

Parameters:
  • backend_id (str) – The backend’s id.

  • package (str) – The distribution whose extra installs it (pip install "pkg[x]").

  • implemented (bool) – Whether the package ships a facade for it.

  • available (bool) – Whether it is usable right now (the package’s own probe).

  • recipe (Optional[Mapping]) – Its row of the package’s recipes table (see the module docstring).

  • is_remote (bool) – From the backend’s config or ledger record.

  • ledger_pip (str) – The ledger’s install line, used for a backend not implemented.

  • credentials (Iterable[str]) – export lines (see credential_lines()).

  • platform (Optional[str]) – Override current_platform() (for tests and docs).

  • verify_command (Optional[str]) – The shell line shown as Verify:.

  • unimplemented_note (Optional[str]) – Appended to notes when not implemented.

  • alternative_label (str) – The wording before alt in the instructions.

Return type:

Requirements

ocracy.kit.check_range(name, value, spec)[source]#

Raise ValueError unless value fits spec’s min/max/choices.

The standalone form of the translator’s out_of_range='raise' check; returns value unchanged. None is “unset” and always fits.

Return type:

Any

ocracy.kit.credential_help(provider, *, guidance=None)[source]#

A short, link-bearing “how to get a key” line for provider (or '').

guidance[provider] may carry note and get_key_url.

Return type:

str

ocracy.kit.credential_lines(env_var, provider, *, guidance=None)[source]#

export VAR  (get a key: URL) lines for an install plan (empty if no var).

Several env vars (alternatives) are shown as A / B.

Return type:

list

ocracy.kit.credential_rows(provider_env_vars, guidance=None, *, unlocks=None, cost=None, also_requires=None)[source]#

Declared-credential rows from the kit’s tables, one per provider.

provider_env_vars and guidance are the tables a package already binds the chain with; unlocks and cost are optional {provider: line} tables. A provider with no env var is skipped (nothing to set). also_requires is an optional {provider: names} table of the variables needed with the key (env_vars are alternatives; these are all required).

>>> credential_rows(
...     {"acme": ["ACME_API_KEY", "ACME_KEY"], "local": None},
...     {"acme": {"get_key_url": "https://acme.example/keys"}},
...     unlocks={"acme": "acme transcription"},
... )
[{'provider': 'acme', 'env_vars': ['ACME_API_KEY', 'ACME_KEY'], 'get_key_url': 'https://acme.example/keys', 'unlocks': 'acme transcription'}]
>>> credential_rows({"acme": "ACME_KEY"}, also_requires={"acme": ["ACME_APP_ID"]})
[{'provider': 'acme', 'env_vars': ['ACME_KEY'], 'also_requires': ['ACME_APP_ID']}]
Return type:

list

ocracy.kit.current_credentials()[source]#

The provider keys bound in this context by using_credentials() (a copy).

Return type:

dict

ocracy.kit.current_platform()[source]#

'darwin', 'linux', 'windows', or sys.platform for anything else.

Return type:

str

ocracy.kit.env_var_names(provider=None, *, env_var=None, provider_env_vars=None)[source]#

The env vars the chain checks: env_var first, then the provider’s row.

Return type:

list

ocracy.kit.make_translator(param_map, *, backend='', on_unsupported='warn', always_raise=(), vocabulary=None, passthrough=(), skip_none=False, out_of_range='raise', stacklevel=2)[source]#

Build translate(kwargs, *, on_unsupported=None) -> Translation from a map.

Parameters:
  • param_map (Mapping[str, Any]) – Canonical name -> spec (see the module docstring). Specs are validated here, so a malformed map fails when the backend loads, not on the first call that happens to use the bad entry.

  • backend (str) – The backend’s name, used in notes and errors.

  • on_unsupported (str) – The backend’s policy (one of POLICIES).

  • always_raise (Iterable[str]) – Canonical names that raise under the backend’s policy because dropping them changes what the caller gets.

  • vocabulary (Optional[Mapping[str, Any]]) – The facade’s canonical names -> their default values. Enables “not asked for” detection and “not a parameter of” wording.

  • passthrough (Iterable[str]) – Names passed through untranslated and unreported.

  • skip_none (bool) – Treat a None value as unset: never sent, never reported.

  • out_of_range (str) – The default for specs that do not set their own.

  • stacklevel (int) – The frame a 'warn' points at, counted from the code that calls translate (1 = that code, 2 = its caller).

Return type:

Callable[..., Translation]

Returns:

translate. Its optional on_unsupported= is the caller’s policy for this one call; when given it replaces both the backend’s policy and always_raise.

ocracy.kit.read_declared_credentials(group='ocracy.credentials.v1')[source]#

(rows, problems): every installed package’s declared credentials.

Each row is normalize_credential_row()’s, plus package (the distribution that declared it). A declaration that fails to load, or a row that is malformed, is a line in problems rather than an exception, so one broken package never hides the others’ keys. Reads no key’s value.

Return type:

tuple[list, list]

ocracy.kit.resolve_credential(provider=None, *, api_key=None, env_var=None, provider_env_vars=None, guidance=None, store=None, dotenv=False, prompt_if_missing=False, required=True, error=<class 'ocracy.kit.credentials.MissingCredentialError'>, hint='')[source]#

Resolve a provider’s credential through the chain in the module docstring.

Parameters:
  • provider (Optional[str]) – The provider id, used for bindings, table rows and messages.

  • api_key (Optional[str]) – An explicit value; wins when non-empty.

  • env_var (Union[str, Sequence[str], None]) – Env var name(s) checked before the provider’s table row.

  • provider_env_vars (Optional[Mapping[str, Union[str, Sequence[str], None]]]) – The package’s provider -> env var(s) table.

  • guidance (Optional[Mapping]) – The package’s provider -> {note, get_key_url} table.

  • store (Optional[Mapping[str, str]]) – A mapping keyed by env-var name, read after the environment.

  • dotenv (bool) – On an environment miss, load a project .env (searched from the current directory, never overriding) and look again.

  • prompt_if_missing (bool) – Ask with getpass when interactive (last resort).

  • required (bool) – Raise when nothing resolves; else return None.

  • error (Callable[[str], BaseException]) – The exception to raise, called with the message. When it builds a MissingCredentialError (or subclass), its provider, env_vars and get_key_url attributes are filled in.

  • hint (str) – An extra sentence for the error message (why this key is needed).

Return type:

Optional[str]

Returns:

The secret, or None when required=False and nothing resolved.

ocracy.kit.run_install(req, *, package, yes=False, verify_code=None, upgrade=False)[source]#

Plan (default) or run (yes=True) the pip install that req describes.

Parameters:
  • req (Requirements) – The plan, from build_requirements().

  • package (str) – The distribution whose extra to install.

  • yes (bool) – Actually run pip; otherwise a dry run that changes nothing.

  • verify_code (Optional[str]) – Python source run in a fresh interpreter after a successful install; available_after is whether it printed True.

  • upgrade (bool) – Pass --upgrade to pip.

Return type:

dict

Returns:

{backend, requirements, ran, available_before, message?, pip_argv?, returncode?, stdout_tail?, stderr_tail?, available_after?, system_todo?}.

ocracy.kit.using_credentials(keys=None, /, **provider_keys)[source]#

Bind provider keys for the with block (overlaying any outer binding).

Pass a mapping for provider ids that are not identifiers ("google-vision") or keywords for the rest. Falsy values are ignored, so an optional request header can be passed straight through.

>>> with using_credentials(acme="outer"):
...     with using_credentials({"acme": "inner", "other": None}):
...         inner = current_credentials()
...     outer = current_credentials()
>>> inner, outer
({'acme': 'inner'}, {'acme': 'outer'})
Return type:

Iterator[dict]

Modules

credentials

One credential chain for every facade: explicit -> bound -> env -> store -> prompt.

install

Install plans: what a backend needs on this OS, as data an agent can act on.

ledger

The ledger loader: a filterable catalog over a facade's backends.json.

translation

Canonical -> native keyword translation, with an honest unsupported-parameter policy.