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.
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 |
|
|
|
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. |
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. |
- 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=<factory>, system_note=None, gpu=None, weights=None, heavy=False, alternative=None, credentials=<factory>, notes=<factory>, 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=<factory>, notes=<factory>, dropped=<factory>)[source]#
Bases:
objectWhat a translator produced: the native kwargs, and every change it made.
- kwargs#
The native kwargs to pass to the backend.
- notes#
One human-readable line per drop or clamp, for the facade’s result.
- dropped#
The canonical names that were dropped.
- 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.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.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. |
|
Canonical -> native keyword translation, with an honest unsupported-parameter policy. |