Skip to main content

Liquifai

Liquifai is a modern, type-safe application framework for Python, designed to bind Loggair and Confluid into high-performance CLI applications.

Key Features

  • Zero-Boilerplate Startup: Automatically handles logging and hierarchical config initialization.
  • Type-Safe CLI: Streamlined argument parsing and validation.
  • Dependency Injection: Seamlessly injects configured Confluid objects into your commands.
  • Rich Integration: Beautiful terminal output and progress reporting via Rich.
  • Modular Commands: Register and compose multiple tools into a single entry point.
  • Operations → CLI + MCP: register a pure operation once (@app.operation) and surface it as an auto-generated CLI command and an MCP tool (make_mcp_tools).
  • SDK Bridge (provisional): mirror an existing Python SDK as a full CLI/MCP app by decorating its client classes (liquifai.bridge).
  • Shell Completion: bash/zsh/fish tab completion for commands, options, overrides — and live positional values.
  • Host Facts: every run carries the machine's os and device — as scopes (!scope:os=darwin) and as values (${platform.os}), with no env vars and nothing typed.

Documentation

Each topic has its own guide, and every guide has a runnable companion script in examples/:

Guide What it covers Example
Commands & Dependency Injection @command / @script_command, config promotion (with ./config/ + XDG search paths and its DEBUG provenance notice), DI block lookup, positional arguments, flow modes positionals_app.py, promotion_app.py et al.
CLI Overrides The override grammar (--key value, dotted keys, polarity, add/delete) and the dropped-token warning overrides_app.py
Global Flags Log control (--level, --log-dir, …), --scope / dimension flags, --debug, --docs global_flags_app.py
Host Facts The os / device scopes and the injected platform namespace — !scope:os=darwin blocks and ${platform.os} values host_facts_app.py
Error Handling The typed LiquifaiError hierarchy and the CLI failure contract failure_contract.py
Shell Completion Install, aliases, workspace-local setup, dynamic & dependent positional values completion_providers.py
Architecture Decisions Why liquifai is shaped this way: the hand-rolled parser, out-of-process completion, the shared argv walk, who owns settability — (records carry inline examples)

For everything at once, examples/pypeek/ is a complete, installable showcase app — a small PyPI query CLI whose <package> completes from your installed distributions (offline) and whose <version> completes from the live PyPI API (dependent completion with the background self-heal cache), plus the failure contract, override broadcast, and dry-run in action.

Its counterpart examples/linefit/ is a training-style installable CLI (think Lightning CLI): fit / validate / test / predict script commands with config promotion, a YAML that instantiates the model/data/optimizer via confluid tags (the optimizer !lazy: until the run supplies the live model), dotted CLI overrides reaching any knob, and a print-config verb that dumps the fully-merged configuration as a reloadable recipe.

Design Goals & Requirements

CLI Framework

  • Zero-Boilerplate Startup: Automate the bootstrapping of Loggair and Confluid.
  • Contextual Scripting: Support @app.script_command() which promotes the first positional argument to a configuration file path.
  • Type-Safe DI: Inject fully-configured objects directly into command signatures based on type hints.
  • Default Command Redirection: Run a default command when no subcommand is given — its positionals (and a script default's config) bind without the name: my-app w.yaml.

User Experience

  • Abbreviation Support: Allow brief aliases for the main executable (e.g. ma for my-app).
  • Dynamic Overrides: Support --KEY VAL CLI overrides with broadcast injection into nested configurations.
  • Observability Overrides: Provide CLI flags for log control (--level, --console-level, --file-level, --log-dir) as the top layer of a four-step hierarchy — flag, then LOGGAIR_* environment variable, then config file, then default. A flag you do not type is left unset rather than defaulted, so the lower layers still apply (global flags).

Architecture

  • Config Promotion: Automatically look for <arg>.yaml if the first argument is not a registered command.
  • Smart DI Lookup: Search configuration blocks by both argument name and class name to ensure hydration.

Quick Start

from liquifai import LiquifyApp, LiquifyContext
from confluid import configurable

@configurable
class MyTrainer:
    def __init__(self, lr: float = 0.01):
        self.lr = lr

app = LiquifyApp(name="my-app")

@app.command()
def train(trainer: MyTrainer) -> None:
    # 'trainer' is automatically loaded via Confluid and injected
    print(f"Training with lr={trainer.lr}")

if __name__ == "__main__":
    app.run()

CLI Overrides

Any token left after the command, positionals, and global flags is parsed as a config override. All forms interoperate in one invocation:

Form Example Effect
--key value --max_epochs 10 set max_epochs (broadcast into matching nested configs)
--key=value --trainer.lr=0.001 equals form; dotted keys target nested blocks
key=value model.dropout=0.2 bare form, no dashes
--key+ / --key- --debug+ polarity: explicit True / False
--key --verbose implicit True
+key=value +new_feature=true add a new key
~key ~trainer.stale delete the dotted key from the config

A token that matches none of these forms is not applied and liquifai logs a warning naming it (Ignoring unrecognized CLI token 'lr' — expected one of: …). Previously such tokens were dropped silently — a typo'd lr 0.1 instead of --lr 0.1 would run the whole job on defaults without a trace.

Hyphens and underscores are the same key. --custom-node URL and --custom_node URL both address the parameter custom_node, and a dotted key normalises per segment (--my-opt.learning-rate → my_opt.learning_rate). This is safe rather than a guess: a hyphen cannot appear in a Python identifier, so a hyphenated key could not have addressed a parameter under any spelling. Only keys are normalised — a URL or a negative number keeps its hyphens, and the polarity suffix is read first, so --default-nodes- still means false rather than a key ending in a separator.

Short options

A command may declare single-letter aliases. They are declared, never derived from the parameter's first letter — deriving would silently shadow the global shorts (-c, -s, -d, -h are already config / scope / debug / help):

@app.command(short={"p": "port", "b": "background"})
def restart(port: int = 8188, background: bool = False):
    ...
$ myapp restart -b                 # == --background
$ myapp restart -p 9000            # == --port 9000   (-p=9000 also works)

$ myapp restart --help
 Option (Shortest Unique)  Type  Current/Default Value  Documentation
 -b, --background          bool  False                  Start detached.
 --port                    int   8188                   Port to use.

A letter that is reserved by a global, declared twice, longer than one character, or names no parameter of the command raises CommandDefinitionError at decoration time — an author's startup error rather than a user's wrong action. A short is pure sugar: it is expanded to the long spelling before parsing, so everything downstream sees only --parameter, and an undeclared -x still reaches the unrecognised-token path.

Strict flags

By default an override that reaches nothing falls through to the config document, which is a legitimate pattern for a config-driven app. An app whose commands take plain values has no such fall-through — there, a flag that reaches nothing is indistinguishable from one that worked. Such an app opts in:

app = LiquifyApp(name="myapp", description="…", strict_flags=True)
$ myapp launch --custom-nod URL
Error: myapp: unknown option 'custom_nod' — it names no parameter of the 'launch' command
and no key in the configuration. Did you mean 'custom_node'? Declared parameters: …

The check is narrow on purpose: only a bare key is judged, against the command's own parameters plus the top-level config keys. A dotted key (--opt.lr) addresses a nested object, and whether it was delivered is something only confluid's materialization report knows — that path keeps its existing post-materialization warning, which sees delivery this check cannot.

The single source of truth for the global-flag vocabulary and token classification is liquifai/grammar.py (stdlib-only); the parser, --help, and shell completion all derive from it, so they cannot drift apart. Override parsing/application lives in liquifai/overrides.py, and annotation-driven dependency injection in liquifai/di.py.

Error Handling

Liquifai raises typed exceptions rooted at LiquifaiError; each also inherits the builtin it replaces, so pre-existing except ValueError: / except KeyError: code keeps working unchanged:

Exception Also a Raised when
CommandDefinitionError ValueError a @script_command / @operation / bridge declaration is invalid (bad flow_mode / presentation, or an SdkBridge group naming an unregistered policy / adapter)
UnknownOperationError KeyError set_completions() names an operation that is not registered
MissingArgumentError TypeError a command parameter without a default got no value from the command line, the config, or dependency injection
UnsupportedShellError ValueError a completion shell is not one of bash / zsh / fish

Configuration-loading failures propagate Confluid's own hierarchy (confluid.ConfluidError and subclasses) — LiquifaiError covers CLI-definition errors only.

CLI failure contract

When a command runs via app.run():

Failure Behavior Exit code
LiquifaiError or confluid.ConfluidError (bad config, unresolvable class, invalid declaration) One clean Error: … line on the console; full traceback written to the log file at DEBUG 1
Same, with --debug on the line The exception propagates — full traceback on the console (Python default)
Missing --config file Dedicated Configuration file not found message 1
Unknown command/group Unknown command or group (or help when no default command exists) 1
Missing required argument Error: pypeek versions: missing required argument 'package' — pass it as `pypeek versions <package>` or `--package <value>`. 1
Any other exception A bug — always propagates with its traceback, never converted to a clean exit (Python default)

Operations, MCP Tools, and the SDK Bridge

Beyond plain @app.command handlers, liquifai has a pure operations model: a function returning a JSON-serializable dict is registered once and surfaced on every front-end.

app = LiquifyApp(name="dataset")

@app.operation(presentation="list", columns=(("name", "Name"),))
def dataset_list(conn: MyConn) -> dict:      # `conn` injected, never CLI-visible
    return {"items": [...], "count": 3}

app.set_context_factory(build_conn)          # how CLI calls get their `conn`
app.set_presenter(render_result)             # how CLI renders the returned dict
app.build_commands()                         # -> CLI command `dataset list`

from liquifai import make_mcp_tools          # -> MCP tools from the same ops
for tool in make_mcp_tools(app):
    mcp_server.tool()(tool)

@app.operation is the ONE ops-registration path (the pre-release @app.command(presentation=...) dual-mode was removed). CLI positionals are derived from the operation signature: every keyword-only parameter without a default becomes a positional slot.

SDK bridge (liquifai.bridge, provisional)

For CLIs that mirror an existing Python SDK, liquifai.bridge generates the operations themselves: decorate a subclass of the real SDK client and declare how each method maps to a CLI/MCP operation.

from liquifai.bridge import P, SdkBridge, custom, expose

bridge = SdkBridge(conn_cls=MyConn)              # your @configurable connection

@bridge.group(name="widget", sub="widget", aliases=["w"])
class WidgetClient(sdk.WidgetClient):            # inherits the real SDK class

    @expose(verb="info", presentation="fields", params=[P("name")])
    def get_widget(self) -> None: ...            # method name = the SDK method

    @expose(verb="delete", presentation="status", params=[P("name")],
            status_word="deleted", status_echo=("name",))
    def delete_widget(self) -> None: ...

    @custom(verb="export", presentation="status")
    def widget_export(conn, *, name: str) -> dict:   # escape hatch: conn-first body
        """Export one widget somewhere the declarative engine can't express."""
        ...

bridge.mount(root_app)                           # CLI sub-app `widget` / `w`

The knobs you can tune, and where they live:

Knob Where Purpose
conn_cls= SdkBridge(...) Concrete connection class baked into op signatures (contract: dry_run attr + get_client() — see BridgeConnection)
configure= SdkBridge(...) Hook run per group after all ops register (wire context factory / presenter, then build_commands()); default just builds commands
adapters= SdkBridge(...) Extra P(adapt=...) string→value parsers merged over DEFAULT_ADAPTERS (list/csv/kv/props/str)
policies= SdkBridge(...) Spec→op builders merged over the built-ins (call, items); register SDK dialects (e.g. a paginated list) here
target= SdkBridge(...) (conn, sub) -> call target override for non-attribute sub-client access
shape_status= SdkBridge(...) Override the default status-presentation result shaper
P(cli, sdk=, default=, adapt=, ...) @expose(params=[...]) One CLI param mapped onto an SDK kwarg; no default = required = CLI positional
extra **options @expose(...) Policy-specific knobs (e.g. a list policy's client_filter= / extras=) — opaque to the generic bridge

Every generated op honors conn.dry_run before touching the SDK client, returning a {"dry_run": True, "command", "action", "call"} descriptor — so --help, MCP schemas, and tests run without credentials.

Provisional — outside the version contract. liquifai.bridge has a single production consumer so far; its API may change in 0.x minor releases without a deprecation cycle, and it may move to its own distribution. It is not re-exported from the top-level liquifai package, so import liquifai never reaches it. Depend on it as liquifai[bridge] so the dependency on an unstable surface is recorded in your own metadata. Rationale: Architecture Decisions §6.

Installation

Released on PyPI:

pip install liquifai

The installed version (read from the package metadata):

import liquifai
print(liquifai.__version__)  # e.g. 0.3.0

Optional extras

Extra What it opts into
liquifai[bridge] The provisional liquifai.bridge subpackage (see above). It adds no requirements today — it is a contract marker that records, in your metadata, a dependency on a surface excluded from the version contract.

License

MIT

Metadata

Release files for liquifai 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for liquifai 0.3.0
File Size Uploaded Provenance Actions
liquifai-0.3.0.tar.gz 205.0 kB With provenance Details for liquifai-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for liquifai 0.3.0
File Interpreter ABI Platform Actions
liquifai-0.3.0-py3-none-any.whl Python 3 none any Details for liquifai-0.3.0-py3-none-any.whl

Total release size: 324.9 kB

Release files / liquifai-0.3.0.tar.gz

Download URL liquifai-0.3.0.tar.gz
Size 205.0 kB
Tags Source
SHA-256 checksum
How to use checksums
cfcb1d3552e5a2098b1072a7bac42c05ab724390824157d87b6c02ebdd292dea
BLAKE2b-256 checksum
How to use checksums
4ad689b621095fab32910d8c2f8557d53c3f4bfa51807d2dd326569c3b949b77
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.

Transparency log

Release files / liquifai-0.3.0-py3-none-any.whl

Download URL liquifai-0.3.0-py3-none-any.whl
Size 119.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
08eee2766f0b05395046426bc67be634b62e6a31a3c79011c5b83cf8989f0252
BLAKE2b-256 checksum
How to use checksums
b64693449a2649de39c00557e28c5f4954c20d9cab886fc744089996cb677e5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.

Transparency log

Security for liquifai 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for liquifai-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page