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 declaredparam_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’sbackends.json, withimplementedcomputed 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
|
Build |
|
Raise |
|
Resolve a provider's credential through the chain in the module docstring. |
|
Bind provider keys for the |
The provider keys bound in this context by |
|
|
The env vars the chain checks: |
|
A short, link-bearing "how to get a key" line for |
|
|
|
Declared-credential rows from the kit's tables, one per provider. |
|
|
|
Build |
|
Plan (default) or run ( |
|
Classes
|
What a translator produced: the native kwargs, and every change it made. |
|
What a backend needs to run, structured for an agent to act on. |
|
A filterable, dict-like collection of |
|
One backend's ledger entry: a read-only record, by key or by attribute. |
Exceptions
A backend cannot honour a parameter, and the policy says not to drop it. |
|
|
A required credential could not be resolved; the message says how to get one. |
- class ocracy.kit.BackendInfo(record, *, implemented=False)[source]#
Bases:
MappingOne 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.
- 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:
MappingA filterable, dict-like collection of
BackendInfo, keyed by id.Loaded lazily from
path, else from theenv_varenvironment variable, else fromdefault_path; a missing file is an empty catalog.recordsgives the records directly instead.filter()returns a newCatalogwith 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 neitherpathnor the environment says otherwise.env_var (
Optional[str]) – An environment variable that overridesdefault_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 suffixescan()checks besides the capability’s own field:("_formula",)makescan("math")also readmath_formula.compare_fields (
Iterable[str]) – Default columns ofcompare().
text_fields,capability_suffixesandcompare_fieldstake 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 inbeyond_text, or a field set.A field counts when it is named
capability, or that plus one of the catalog’scapability_suffixes, and its value is one ofCAPABILITY_VALUES.- Return type:
- compare(ids=None, *, fields=None)[source]#
A trimmed, side-by-side view of selected backends and fields.
- filter(*, predicate=None, implemented=None, **criteria)[source]#
Return a new
Catalogof backends matching every criterion.- Parameters:
predicate (
Optional[Callable[[BackendInfo],bool]]) – An arbitraryBackendInfo -> boolcallable.implemented (
Optional[bool]) – If set, keep only (un)implemented backends.**criteria (
Any) –field=valueconstraints.valuemay be a set/list/tuple meaning “one of”. The catalog’s text fields (by defaultlanguages_note,beyond_text,output_formats) use a case-insensitive substring match.
- Return type:
Example:
catalog.filter(is_local=True, open_source=True)
- supports_language(language)[source]#
Backends whose
languages_notementionslanguage(name or code).- Return type:
- exception ocracy.kit.MissingCredentialError(message='', *, provider=None, env_vars=(), get_key_url=None)[source]#
Bases:
RuntimeErrorA 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:
objectWhat a backend needs to run, structured for an agent to act on.
- class ocracy.kit.Translation(kwargs=dict(), notes=list(), dropped=list())[source]#
Bases:
objectWhat a translator produced: the native kwargs, and every change it made.
- exception ocracy.kit.UnsupportedParameter[source]#
Bases:
ValueErrorA 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
Requirementsforbackend_idfrom 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]) –exportlines (seecredential_lines()).platform (
Optional[str]) – Overridecurrent_platform()(for tests and docs).verify_command (
Optional[str]) – The shell line shown asVerify:.unimplemented_note (
Optional[str]) – Appended tonoteswhen not implemented.alternative_label (
str) – The wording beforealtin the instructions.
- Return type:
- ocracy.kit.check_range(name, value, spec)[source]#
Raise
ValueErrorunlessvaluefitsspec’smin/max/choices.The standalone form of the translator’s
out_of_range='raise'check; returnsvalueunchanged.Noneis “unset” and always fits.- Return type:
- ocracy.kit.credential_help(provider, *, guidance=None)[source]#
A short, link-bearing “how to get a key” line for
provider(or'').guidance[provider]may carrynoteandget_key_url.- Return type:
- 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:
- 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_varsandguidanceare the tables a package already binds the chain with;unlocksandcostare optional{provider: line}tables. A provider with no env var is skipped (nothing to set).also_requiresis an optional{provider: names}table of the variables needed with the key (env_varsare 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:
- ocracy.kit.current_credentials()[source]#
The provider keys bound in this context by
using_credentials()(a copy).- Return type:
- ocracy.kit.current_platform()[source]#
'darwin','linux','windows', orsys.platformfor anything else.- Return type:
- ocracy.kit.env_var_names(provider=None, *, env_var=None, provider_env_vars=None)[source]#
The env vars the chain checks:
env_varfirst, then the provider’s row.- Return type:
- 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) -> Translationfrom 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 ofPOLICIES).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 aNonevalue 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 callstranslate(1 = that code, 2 = its caller).
- Return type:
- Returns:
translate. Its optionalon_unsupported=is the caller’s policy for this one call; when given it replaces both the backend’s policy andalways_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, pluspackage(the distribution that declared it). A declaration that fails to load, or a row that is malformed, is a line inproblemsrather than an exception, so one broken package never hides the others’ keys. Reads no key’s value.
- 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 withgetpasswhen interactive (last resort).required (
bool) – Raise when nothing resolves; else returnNone.error (
Callable[[str],BaseException]) – The exception to raise, called with the message. When it builds aMissingCredentialError(or subclass), itsprovider,env_varsandget_key_urlattributes are filled in.hint (
str) – An extra sentence for the error message (why this key is needed).
- Return type:
- Returns:
The secret, or
Nonewhenrequired=Falseand 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 thatreqdescribes.- Parameters:
req (
Requirements) – The plan, frombuild_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_afteris whether it printedTrue.upgrade (
bool) – Pass--upgradeto pip.
- Return type:
- 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
withblock (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'})
Modules
One credential chain for every facade: explicit -> bound -> env -> store -> prompt. |
|
Install plans: what a backend needs on this OS, as data an agent can act on. |
|
The ledger loader: a filterable catalog over a facade's |
|
Canonical -> native keyword translation, with an honest unsupported-parameter policy. |