Skip to content

armgit / laya

Public Imported from GitHub
0

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.

feat(cli): answer your own questions, and give them the token budget they need

Aashish20996c051eb1
diff --git a/laya/cli.py b/laya/cli.py
index 9f6f9868..c59a8e07 100644
--- a/laya/cli.py
+++ b/laya/cli.py
@@ -5,11 +5,15 @@
laya # interactive mode
laya "Mein Konto wurde zweimal belastet" --lang de # explicit language
laya "My payment failed twice" --preset triage # a ready-made question preset
+ laya "Where is my card" --questions intents.json # your own questions, from a JSON file
+ laya "Where is my card" --questions intents.json --head-max-len 384
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. --preset answers one of the
-ready-made question presets from laya.presets and implies --predict.
+ready-made question presets from laya.presets and implies --predict. --questions
+answers the question set in a JSON file instead; --max-len and --head-max-len
+raise its token budget for the request, which is what a many-label question needs.
"""
import argparse
@@ -54,6 +58,15 @@ def build_parser():
parser.add_argument("--preset", choices=sorted(PRESETS), metavar="NAME",
help="answer a ready-made question preset (%s) instead of the router questions; implies --predict"
% ", ".join(sorted(PRESETS)))
+ parser.add_argument("--questions", metavar="FILE",
+ help="a JSON file of your own typed questions to answer instead of the router questions"
+ " or a preset; implies --predict")
+ parser.add_argument("--max-len", type=int, dest="max_len", metavar="N",
+ help="token budget for the whole request (state plus options); defaults to the"
+ " checkpoint's own budget")
+ parser.add_argument("--head-max-len", type=int, dest="head_max_len", metavar="N",
+ help="token budget the choice options share; raise it when a question has many"
+ " labels, so each keeps enough tokens to stay distinct")
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
@@ -63,6 +76,39 @@ def make_router(args):
return laya.Router(device=args.device, preload=False)
+def load_questions(path):
+ """Read a ``--questions`` file: returns ``(questions, state_key)``.
+
+ The file is either a bare ``question id -> definition`` mapping, or an object holding one
+ under ``"questions"`` plus an optional ``"state_key"`` naming the field the instructions
+ refer to. That second field exists because #426 found the CLI sending every request under a
+ key no question set named: with a user's own questions the CLI cannot guess the key, so the
+ file declares it. Default ``"request"``, matching bare ``--predict``.
+ """
+ try:
+ with open(path, encoding="utf-8") as handle:
+ raw = json.load(handle)
+ except FileNotFoundError:
+ raise ValueError("no such --questions file: %s" % path)
+ if not isinstance(raw, dict):
+ raise ValueError("--questions file must be a JSON object of question id -> definition")
+ state_key = "request"
+ questions = raw
+ if "questions" in raw:
+ if not isinstance(raw["questions"], dict):
+ raise ValueError("the 'questions' field of the --questions file must be an object")
+ questions = raw["questions"]
+ state_key = raw.get("state_key", "request")
+ if not isinstance(state_key, str) or not state_key.strip():
+ raise ValueError("'state_key' must be a non-empty string, got %r" % (state_key,))
+ if not questions:
+ raise ValueError("--questions file holds no questions")
+ for qid, qdef in questions.items():
+ if not isinstance(qdef, dict):
+ raise ValueError("question %r must map to an object, got %s" % (qid, type(qdef).__name__))
+ return questions, state_key
+
+
def show_decision(decision):
print("Model :", decision["model"])
print("Reason :", decision["reason"])
@@ -90,22 +136,49 @@ def show_answers(result):
print("%-12s: %s" % (qid, detail))
+def budget_overrides(args):
+ """The token-budget flags as `predict` keyword arguments, absent when unset.
+
+ Unset has to mean unsent, so the checkpoint's own defaults stay in charge. A zero is a real
+ budget, not an absence, so this tests `is not None` rather than truthiness.
+ """
+ overrides = {}
+ for flag in ("max_len", "head_max_len"):
+ value = getattr(args, flag, None)
+ if value is not None:
+ overrides[flag] = value
+ return overrides
+
+
+def resolve_questions(args):
+ """The question set to answer and the state field it reads, from the flags given."""
+ if args.questions and args.preset:
+ raise ValueError("--questions and --preset choose different question sets; pass one")
+ if args.questions:
+ return load_questions(args.questions)
+ if args.preset:
+ return PRESETS[args.preset](), PRESET_STATE_KEYS[args.preset]
+ return laya.router_questions(), PRESET_STATE_KEYS["router"]
+
+
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)
try:
- if args.predict or args.preset:
- questions = PRESETS[args.preset]() if args.preset else laya.router_questions()
+ if args.predict or args.preset or args.questions:
+ questions, state_key = resolve_questions(args)
# Each preset's instructions name the field they read -- `` `message` ``,
# `` `body` ``, `` `prompt` ``, `` `post` ``, `` `request` `` -- and the CLI used to
# send every request as `{"text": ...}`, a key none of them names, so the model was
# asked about a field that was not there. The state key therefore follows the
- # question set being answered. Routing is not affected either way: `route` reads the
- # state only for language detection, which is key-invariant, so the default path
- # keeps `{"text": ...}`.
- state = {PRESET_STATE_KEYS.get(args.preset, "request"): text}
+ # question set being answered: the preset's own key, or the one a --questions file
+ # declares. Routing is not affected either way: `route` reads the state only for
+ # language detection, which is key-invariant, so the default path keeps
+ # `{"text": ...}`.
+ state = {state_key: text}
result = router.predict(state, questions,
- model=args.model, task=args.task, lang=args.lang)
+ model=args.model, task=args.task, lang=args.lang,
+ **budget_overrides(args))
if args.json:
print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
else:
diff --git a/tests/test_cli.py b/tests/test_cli.py
index a4b3262a..6e79c9bc 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -43,9 +43,12 @@ def run_cli(argv, router=None):
original = cli.make_router
cli.make_router = lambda args: stub
out, err = io.StringIO(), io.StringIO()
+ code = None
try:
with redirect_stdout(out), redirect_stderr(err):
code = cli.main(argv)
+ except SystemExit as exit_: # argparse rejects a bad flag value by exiting
+ code = exit_.code
finally:
cli.make_router = original
return code, out.getvalue(), err.getvalue(), stub
@@ -90,12 +93,14 @@ class QuestionRecorder:
self.questions = None
self.route_calls = []
self.states = []
+ self.kwargs = {}
def route(self, state, **kwargs):
self.route_calls.append((state, kwargs))
return StubDecision()
def predict(self, state, questions, **kwargs):
+ self.kwargs = kwargs
self.questions = questions
self.states.append(state)
return {"answers": {"intent": {"choice": "refund", "probability": 0.9}}}
@@ -149,13 +154,142 @@ check("preset: absent means router questions",
sorted(stub.questions) == sorted(cli.PRESETS["router"]()),
str(sorted(stub.questions or {})))
-code, out, err, stub = 0, "", "", None
-try:
- run_cli(["hi", "--preset", "bogus"])
-except SystemExit as exit_:
- code = exit_.code
+code, out, err, stub = run_cli(["hi", "--preset", "bogus"])
check("preset: unknown name rejected by argparse", code == 2, "got %r" % code)
+# --------------------------------------------------------------------- --questions FILE
+# The CLI could only ever answer the five built-in presets, while the library's whole input is a
+# user-written question dict. A file is the only way to get one onto the command line, so the
+# loader is the seam under test here: what it accepts, and what the request ends up under.
+import json as _json # noqa: E402
+import tempfile as _tempfile # noqa: E402
+
+_TMP = _tempfile.mkdtemp(prefix="laya-cli-questions-")
+
+
+def write_json(name, payload):
+ path = os.path.join(_TMP, name)
+ with open(path, "w", encoding="utf-8") as handle:
+ _json.dump(payload, handle)
+ return path
+
+
+INTENTS = {
+ "intent": {"type": "choice", "instructions": "Which intent?",
+ "criteria": {"card_arrival": "where is my card", "fee": "a charge appeared"}},
+}
+INTENTS_PATH = write_json("intents.json", INTENTS)
+KEYED_PATH = write_json("keyed.json", {"state_key": "body",
+ "questions": {"spam": {"type": "noul",
+ "instructions": "Is `body` spam?"}}})
+
+code, out, err, stub = run_cli(["My payment failed twice", "--questions", INTENTS_PATH],
+ router=QuestionRecorder())
+check("questions: exit code", code == 0, "got %r, err %r" % (code, err))
+check("questions: implies --predict", stub.questions == INTENTS, str(stub.questions))
+check("questions: state under the default key", stub.states[0] == {"request": "My payment failed twice"},
+ str(stub.states[0]))
+check("questions: no standalone route call", stub.route_calls == [])
+check("questions: prints answers", "intent" in out, out)
+
+# A file that declares its own key has to win: the instructions name `body`, and asking about a
+# field that is not there is the #426 failure this path keeps reproducing.
+code, out, err, stub = run_cli(["hello", "--questions", KEYED_PATH], router=QuestionRecorder())
+check("questions: declared state_key used", stub.states[0] == {"body": "hello"}, str(stub.states[0]))
+check("questions: questions unwrapped",
+ sorted(stub.questions) == ["spam"], str(sorted(stub.questions or {})))
+
+# The CLI validates the file's shape and defers question semantics to core, so a question set is
+# handed over unchanged rather than normalised twice.
+code, out, err, stub = run_cli(["hi", "--questions", write_json("odd.json", {"a": {"type": "bogus"}})],
+ router=QuestionRecorder())
+check("questions: nonsense type reaches predict unchanged",
+ stub.questions == {"a": {"type": "bogus"}}, str(stub.questions))
+
+for name, payload, fragment in (
+ ("empty.json", {}, "holds no questions"),
+ ("list.json", [1], "must be a JSON object"),
+ ("scalar.json", {"a": 5}, "must map to an object"),
+ ("badwrap.json", {"questions": [1]}, "'questions' field"),
+ ("badkey.json", {"state_key": "", "questions": {"a": {"type": "noul"}}}, "'state_key'"),
+):
+ code, out, err, stub = run_cli(["hi", "--questions", write_json(name, payload)],
+ router=QuestionRecorder())
+ check("questions %s: exit code 2" % name, code == 2, "got %r" % code)
+ check("questions %s: names the problem" % name, fragment in err, err)
+
+code, out, err, stub = run_cli(["hi", "--questions", os.path.join(_TMP, "missing.json")],
+ router=QuestionRecorder())
+check("questions: missing file is a handled error",
+ code == 2 and "no such --questions file" in err, "code %r, err %r" % (code, err))
+
+code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH, "--preset", "triage"],
+ router=QuestionRecorder())
+check("questions: two sources refuse each other",
+ code == 2 and "pass one" in err, "code %r, err %r" % (code, err))
+
+code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH, "--json"],
+ router=QuestionRecorder())
+check("questions: --json prints the raw answers", code == 0 and '"intent"' in out,
+ "code %r, out %r" % (code, out))
+
+# The same file answers every preset's questions too, so --questions replaces none of them.
+code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH, "--model", "english"],
+ router=QuestionRecorder())
+check("questions: --model still forwarded", stub.kwargs.get("model") == "english", str(stub.kwargs))
+
+# --------------------------------------------------------------------- the token budget
+# `--questions` is what makes a many-label question reachable from the shell, and a many-label
+# question is exactly what overflows the shared option budget. Both halves have to be here: on
+# `laya` (head budget 192) the 58-label Massive-Intent question scores 24/58 by default and
+# 34/58 at --head-max-len 384, so the CLI that can ask the question must also be able to fit it.
+# Nothing set has to mean nothing sent: the checkpoint's own budget stays in charge, and a
+# `max_len=None` in the call would be a different promise from the one `predict` documents.
+code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH], router=QuestionRecorder())
+check("budget: default sends no override", "max_len" not in stub.kwargs and
+ "head_max_len" not in stub.kwargs, str(stub.kwargs))
+
+for argv, expected in (
+ (["--max-len", "1024"], {"max_len": 1024}),
+ (["--head-max-len", "384"], {"head_max_len": 384}),
+ (["--max-len", "1024", "--head-max-len", "384"], {"max_len": 1024, "head_max_len": 384}),
+ # A zero budget is a real value, not an absent one.
+ (["--head-max-len", "0"], {"head_max_len": 0}),
+):
+ code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH] + argv, router=QuestionRecorder())
+ sent = {k: v for k, v in stub.kwargs.items() if k in ("max_len", "head_max_len")}
+ check("budget %s: forwarded" % " ".join(argv), sent == expected, "%r != %r" % (sent, expected))
+
+# The budget belongs to the request, not to how the questions arrived.
+for argv in (["--predict"], ["--preset", "triage"], ["--questions", INTENTS_PATH]):
+ code, out, err, stub = run_cli(["hi"] + argv + ["--head-max-len", "512"], router=QuestionRecorder())
+ check("budget on %s: forwarded" % " ".join(argv), stub.kwargs.get("head_max_len") == 512,
+ str(stub.kwargs))
+ check("budget on %s: questions unaffected" % " ".join(argv), stub.questions is not None)
+
+# A head budget cannot exceed the request budget it lives inside; that is core's rule, so the CLI
+# passes the pair through and reports core's words rather than inventing its own.
+class BudgetRejectingRouter(QuestionRecorder):
+ def predict(self, state, questions, **kwargs):
+ self.kwargs = kwargs
+ if kwargs.get("head_max_len", 0) > kwargs.get("max_len", 1 << 30):
+ raise ValueError("head_max_len must not exceed max_len")
+ return {"answers": {}}
+
+
+code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH, "--max-len", "128",
+ "--head-max-len", "384"], router=BudgetRejectingRouter())
+check("budget: a rejected pair exits 2", code == 2, "got %r" % code)
+check("budget: core's message reaches the shell", "head_max_len must not exceed max_len" in err, err)
+check("budget: both flags reached predict together",
+ (stub.kwargs.get("max_len"), stub.kwargs.get("head_max_len")) == (128, 384), str(stub.kwargs))
+
+for value in ("abc", ""):
+ code, out, err, stub = run_cli(["hi", "--questions", INTENTS_PATH, "--head-max-len=%s" % value],
+ router=QuestionRecorder())
+ check("budget %r: rejected by argparse" % value, code == 2 and "invalid int value" in err,
+ "code %r, err %r" % (code, err))
+
# --------------------------------------------------------------------- report
print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))
for f in FAIL: