Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
Add a CLI for testing Laya locally (#119) (#155)
Aashish Mahatoc766f289d642
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 069952d2..59bacdbc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,6 +71,7 @@ jobs:python tests/test_router_memory.pypython tests/test_shortlist_cosine.pypython tests/test_temperature_loading.py+ python tests/test_cli.py- name: Email cleaning testsrun: python tests/test_email.pydiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 40ce7392..0fcdd5b9 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -53,6 +53,7 @@ jobs:python tests/test_router_memory.pypython tests/test_shortlist_cosine.pypython tests/test_temperature_loading.py+ python tests/test_cli.py- name: Buildrun: python -m builddiff --git a/README.md b/README.mdindex 58f11db5..eeaa0617 100644--- a/README.md+++ b/README.md@@ -137,6 +137,19 @@ own. Both ids run the checkpoints published here, unmodified, at `max_len` 8192.[Docs](https://impossibl.com/docs/evaluation) · [Model page](https://impossibl.com/convaiinnovations/laya)+### Command line++Installing the package also installs a `laya` command for quick local testing, no script needed:++```bash+laya "I was charged twice, please refund" # routing decision only; works offline, no download+laya "Refactor this service" --predict # full answers (downloads the checkpoint on first use)+laya "Mein Konto wurde zweimal belastet" --lang de # force a language instead of detecting it+laya # interactive mode+```++Routing alone never downloads a checkpoint, so it returns in milliseconds. `--predict` loads the routed checkpoint, which needs network access to the Hugging Face hub the first time; if a checkpoint cannot be downloaded, the CLI says so instead of crashing.+---## Quickstart: Route Mode (Recommended)diff --git a/laya/cli.py b/laya/cli.pynew file mode 100644index 00000000..6dde2865--- /dev/null+++ b/laya/cli.py@@ -0,0 +1,120 @@+"""Command-line interface for testing Laya locally.++ laya "I was charged twice, please refund" # routing decision only (no model download)+ laya "Refactor this service" --predict # full answers, loads the checkpoint+ laya # interactive mode+ laya "Mein Konto wurde zweimal belastet" --lang de # explicit language++Routing (the default) never downloads a checkpoint, so it works offline and+returns in milliseconds. --predict loads the routed checkpoint on first use,+which needs network access to the Hugging Face hub.+"""++import argparse+import json+import sys++import laya+++def build_parser():+ parser = argparse.ArgumentParser(+ prog="laya",+ description="Test Laya locally: route or answer a request from the command line.",+ )+ parser.add_argument("text", nargs="*", help="the request text (omit for interactive mode)")+ parser.add_argument("--predict", action="store_true",+ help="run the full prediction, not just the routing decision (downloads the checkpoint on first use)")+ parser.add_argument("--model", choices=sorted(laya.DEFAULT_MODELS),+ help="force a checkpoint instead of auto-routing")+ parser.add_argument("--lang", help="force a language, e.g. en or de, instead of detecting it")+ parser.add_argument("--task", help="force a typed-decisions workflow instead of detecting it")+ parser.add_argument("--device", help="torch device, e.g. cpu or cuda")+ parser.add_argument("--json", action="store_true", help="print the raw result as JSON")+ return parser+++def make_router(args):+ return laya.Router(device=args.device, preload=False)+++def show_decision(decision):+ print("Model :", decision["model"])+ print("Reason :", decision["reason"])+ detection = decision.get("detection")+ if detection:+ print("Detected :", json.dumps(detection, ensure_ascii=False))+++def show_answers(result):+ routing = result.get("routing")+ if routing:+ show_decision(routing)+ print()+ for qid, answer in result.get("answers", {}).items():+ if "choice" in answer:+ detail = "%s (p=%.3f)" % (answer["choice"], answer.get("probability", 0.0))+ elif "score" in answer:+ detail = "%.2f" % answer["score"]+ elif "noul" in answer:+ detail = "%.3f" % answer["noul"]+ else:+ detail = json.dumps(answer, ensure_ascii=False)+ print("%-12s: %s" % (qid, detail))+++def run(text, args, router=None):+ """Route or predict one request; returns 0 on success, 2 on a handled error."""+ router = router or make_router(args)+ state = {"text": text}+ try:+ if args.predict:+ result = router.predict(state, laya.router_questions(),+ model=args.model, task=args.task, lang=args.lang)+ if args.json:+ print(json.dumps(result, ensure_ascii=False, indent=2, default=str))+ else:+ show_answers(result)+ else:+ decision = router.route(state, model=args.model, task=args.task, lang=args.lang)+ if args.json:+ print(json.dumps(dict(decision), ensure_ascii=False, indent=2, default=str))+ else:+ show_decision(decision)+ except ValueError as error:+ print("laya: %s" % error, file=sys.stderr)+ return 2+ except (ImportError, OSError, RuntimeError) as error:+ print("laya: could not run Laya (%s)." % error, file=sys.stderr)+ print("Check that the dependencies are installed and the checkpoints can be "+ "downloaded from the Hugging Face hub (network access is needed on first use).",+ file=sys.stderr)+ return 2+ return 0+++def interactive(args):+ print("Laya interactive mode. Type a request and press Enter; Ctrl-D or 'quit' to exit.")+ router = make_router(args)+ while True:+ try:+ text = input("laya> ").strip()+ except (EOFError, KeyboardInterrupt):+ print()+ break+ if not text or text.lower() in ("quit", "exit"):+ break+ run(text, args, router)+ return 0+++def main(argv=None):+ args = build_parser().parse_args(argv)+ text = " ".join(args.text).strip()+ if not text:+ return interactive(args)+ return run(text, args)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/pyproject.toml b/pyproject.tomlindex f519fc39..81918d8a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -44,6 +44,7 @@ serve = [][project.scripts]+laya = "laya.cli:main"laya-serve = "laya.serve:main"[project.urls]diff --git a/tests/test_cli.py b/tests/test_cli.pynew file mode 100644index 00000000..49a8ea8d--- /dev/null+++ b/tests/test_cli.py@@ -0,0 +1,93 @@+"""CLI tests. No model weights are loaded: the Router is stubbed throughout."""+import io+import os+import sys+from contextlib import redirect_stderr, redirect_stdout++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from laya import cli # noqa: E402++PASS, FAIL = [], []+++def check(name, condition, detail=""):+ if condition:+ PASS.append(name)+ else:+ FAIL.append("%s: %s" % (name, detail))+++class StubDecision(dict):+ def __init__(self):+ super().__init__(model="multilingual", repo="convaiinnovations/laya",+ reason="detected non-English text", detection={"lang": "de"}, workflow=None)+++class StubRouter:+ def __init__(self):+ self.route_calls = []+ self.predict_calls = []++ def route(self, state, **kwargs):+ self.route_calls.append((state, kwargs))+ return StubDecision()++ def predict(self, state, questions, **kwargs):+ self.predict_calls.append((state, kwargs))+ return {"answers": {"difficulty": {"score": 1.4}}, "routing": dict(StubDecision())}+++def run_cli(argv, router=None):+ stub = router or StubRouter()+ original = cli.make_router+ cli.make_router = lambda args: stub+ out, err = io.StringIO(), io.StringIO()+ try:+ with redirect_stdout(out), redirect_stderr(err):+ code = cli.main(argv)+ finally:+ cli.make_router = original+ return code, out.getvalue(), err.getvalue(), stub+++# --------------------------------------------------------------------- routing (default)+code, out, err, stub = run_cli(["Ich wurde doppelt belastet"])+check("route: exit code", code == 0, "got %r" % code)+check("route: prints the chosen checkpoint", "multilingual" in out, out)+check("route: state carries the text", stub.route_calls[0][0] == {"text": "Ich wurde doppelt belastet"})+check("route: never loads a checkpoint", stub.predict_calls == [])++# --------------------------------------------------------------------- full prediction+code, out, err, stub = run_cli(["--predict", "Refactor this service"])+check("predict: exit code", code == 0, "got %r" % code)+check("predict: prints answers", "difficulty" in out, out)+check("predict: router.predict called once", len(stub.predict_calls) == 1)++# --------------------------------------------------------------------- json output+code, out, err, stub = run_cli(["--json", "hello there"])+check("json: exit code", code == 0, "got %r" % code)+check("json: raw decision printed", '"model": "multilingual"' in out, out)++# --------------------------------------------------------------------- friendly errors+class BrokenRouter:+ def route(self, state, **kwargs):+ raise OSError("connection failed")+++code, out, err, stub = run_cli(["some text"], router=BrokenRouter())+check("error: exit code 2", code == 2, "got %r" % code)+check("error: names the failure", "could not run Laya" in err, err)+check("error: points at the fix", "Hugging Face hub" in err, err)++# --------------------------------------------------------------------- explicit flags+code, out, err, stub = run_cli(["--model", "english", "charged twice"])+check("flags: --model forwarded", stub.route_calls[0][1]["model"] == "english")++# --------------------------------------------------------------------- report+print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))+for f in FAIL:+ print(" FAIL", f)+if not FAIL:+ print("all CLI tests passed")+sys.exit(1 if FAIL else 0)