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
fix(router): validate questions in predict before checkpoint load (#707)
Swatantra Yadav56966e0dd318
diff --git a/laya-ts/src/router.ts b/laya-ts/src/router.tsindex a7d5114d..9f73e706 100644--- a/laya-ts/src/router.ts+++ b/laya-ts/src/router.ts@@ -1,5 +1,5 @@import { analyse, type AnalyseResult } from "./lang.js";-import type { PredictOptions, QuestionDef, SystemOneResult } from "./agent.js";+import { checkQuestion, type PredictOptions, type QuestionDef, type SystemOneResult } from "./agent.js";import { checkMinConfidence, flagLowConfidence } from "./common.js";import { decide, type DecideOptions, type DecisionResult } from "./structured.js";import {@@ -450,6 +450,13 @@ export class Router extends HookRegistry {questions: Record<string, unknown> | null = null,opts: RouteOptions = {},): RouteDecision {+ if (questions !== null && questions !== undefined) {+ if (typeof questions !== "object" || Array.isArray(questions)) {+ throw new TypeError(+ `questions must be a dict of question id -> definition, got ${Array.isArray(questions) ? "Array" : typeof questions}`,+ );+ }+ }const decision = this._route(state, questions, opts);const raiseErrors = opts.hooksRaise ?? this.hooksRaise;const active = composeHooks(this.hooks, opts.hooks);@@ -584,31 +591,59 @@ export class Router extends HookRegistry {questions: Record<string, QuestionDef>,opts: RouteOptions & PredictOptions = {},): Promise<RoutedResult> {+ if (state === null || state === undefined) {+ throw new TypeError("state must not be None; pass a string, dict, or list");+ }+ if (typeof questions !== "object" || questions === null || Array.isArray(questions)) {+ throw new TypeError(+ `questions must be a dict of question id -> definition, got ${questions === null ? "null" : Array.isArray(questions) ? "Array" : typeof questions}`,+ );+ }const mcOpt = opts.minConfidence ?? opts.min_confidence;const mc = mcOpt !== undefined && mcOpt !== null ? checkMinConfidence(mcOpt) : null;const active = composeHooks(this.hooks, opts.hooks, opts.onPredictStart, opts.onPredictEnd);const raiseErrors = opts.hooksRaise ?? this.hooksRaise;-- // Per-call hooks apply to the whole call, including onRoute inside route().- const decision = this.route(state, questions, opts);- const agent = (await this.load(decision.model)) as {- systemOne(- s: unknown,- q: Record<string, QuestionDef>,- opts?: PredictOptions,- ): Promise<SystemOneResult>;- };+ const hasStart = active.some((h) => typeof h.onPredictStart === "function");const ctx = new PredictContext({states: [state],questions: questions as Record<string, unknown>,- decision: { ...decision } as unknown as Record<string, unknown>,- model: decision.model,- agent,+ decision: null,+ model: null,+ agent: null,router: this,});try {+ if (!hasStart) {+ for (const [qid, qdef] of Object.entries(questions)) {+ checkQuestion(qid, qdef);+ }+ }++ // Per-call hooks apply to the whole call, including onRoute inside route().+ const decision = this.route(state, questions, opts);+ const agent = (await this.load(decision.model)) as {+ systemOne(+ s: unknown,+ q: Record<string, QuestionDef>,+ opts?: PredictOptions,+ ): Promise<SystemOneResult>;+ };+ ctx.decision = { ...decision } as unknown as Record<string, unknown>;+ ctx.model = decision.model;+ ctx.agent = agent;+await dispatchAsync(active, "onPredictStart", ctx, { raiseErrors });if (ctx.results === null) {+ if (hasStart) {+ if (typeof ctx.questions !== "object" || ctx.questions === null || Array.isArray(ctx.questions)) {+ throw new TypeError(+ `questions must be a dict of question id -> definition, got ${ctx.questions === null ? "null" : Array.isArray(ctx.questions) ? "Array" : typeof ctx.questions}`,+ );+ }+ for (const [qid, qdef] of Object.entries(ctx.questions as Record<string, QuestionDef>)) {+ checkQuestion(qid, qdef);+ }+ }// Python parity (router.py predict): the request's language also shapes the answer// distribution through the agent's lang_temperatures. An explicit lang wins;// otherwise forward the language the router detected for the routing decision.diff --git a/laya-ts/tests/router.test.ts b/laya-ts/tests/router.test.tsindex f5623b48..81573f70 100644--- a/laya-ts/tests/router.test.ts+++ b/laya-ts/tests/router.test.ts@@ -96,4 +96,104 @@ describe("router", () => {expect(loader).toHaveBeenCalledTimes(2);expect(r.loaded).toEqual(["english"]);});+ it("rejects invalid inputs in predict before loading any checkpoint", async () => {+ const loader = vi.fn();+ const r = new Router({ loader });++ await expect(r.predict(null, { q: { type: "noul", instructions: "?" } })).rejects.toThrow(+ TypeError,+ );+ await expect(r.predict(null, { q: { type: "noul", instructions: "?" } })).rejects.toThrow(+ /state must not be None/,+ );++ await expect(r.predict("text", [] as never)).rejects.toThrow(TypeError);+ await expect(r.predict("text", [] as never)).rejects.toThrow(+ /questions must be a dict of question id -> definition/,+ );++ await expect(+ r.predict("text", { q: { type: "bogus", instructions: "?" } } as never),+ ).rejects.toThrow(/unknown type/);++ await expect(+ r.predict("text", { "": { type: "noul", instructions: "?" } } as never),+ ).rejects.toThrow(/question id must be a non-empty string/);++ await expect(+ r.predict("text", { q: { type: "noul", instructions: "" } } as never),+ ).rejects.toThrow(/instructions.*must not be empty/);++ expect(loader).not.toHaveBeenCalled();+ expect(r.loaded).toEqual([]);+ });+ it("rejects invalid questions type in route", () => {+ const r = new Router();+ expect(() => r.route("text", [] as never)).toThrow(TypeError);+ expect(() => r.route("text", [] as never)).toThrow(+ /questions must be a dict of question id -> definition/,+ );+ });+ it("allows onPredictStart hook to complete an incomplete question or skip", async () => {+ const loader = vi.fn(async () => ({+ async systemOne() {+ return { model: "laya-rl-agent", answers: {}, usage: { input_tokens: 5, output_tokens: 0 } };+ },+ }));+ const r = new Router({ loader });+ const res = await r.predict("text", { q: { type: "noul" } as never }, {+ onPredictStart: (ctx) => {+ ctx.questions = { q: { type: "noul", instructions: "Added by hook?" } };+ },+ });+ expect(res.routing).toBeDefined();++ const skipLoader = vi.fn();+ const skipRouter = new Router({ loader: skipLoader });+ const skipped = await skipRouter.predict("text", { q: { type: "noul" } as never }, {+ onPredictStart: (ctx) => {+ ctx.skip([{ model: "cached", answers: {}, usage: { input_tokens: 0, output_tokens: 0 } }]);+ },+ });+ expect(skipped.routing).toBeDefined();+ expect(skipped.model).toBe("cached");+ });+ it("dispatches onError and onPredictEnd on invalid question definition without loading", async () => {+ const loader = vi.fn();+ const r = new Router({ loader });+ const events: string[] = [];++ await expect(+ r.predict("text", { q: { type: "bogus", instructions: "x" } } as never, {+ hooks: [+ {+ onError(ctx) {+ events.push(`error:${(ctx.error as Error).name}`);+ },+ onPredictEnd(ctx) {+ events.push(`end:${(ctx.error as Error).name}`);+ },+ },+ ],+ }),+ ).rejects.toThrow(/unknown type/);++ expect(events).toEqual(["error:Error", "end:Error"]);+ expect(loader).not.toHaveBeenCalled();+ expect(r.loaded).toEqual([]);+ });+ it("treats non-function onPredictStart as no start hook and rejects before load", async () => {+ const loader = vi.fn();+ const r = new Router({ loader });++ await expect(+ r.predict("text", { q: { type: "bogus", instructions: "x" } } as never, {+ hooks: [{ onPredictEnd: () => {}, onPredictStart: null as never }],+ }),+ ).rejects.toThrow(/unknown type/);++ expect(loader).not.toHaveBeenCalled();+ expect(r.loaded).toEqual([]);+ });});+diff --git a/laya/router.py b/laya/router.pyindex 7853ec9a..2e287560 100644--- a/laya/router.py+++ b/laya/router.py@@ -1327,11 +1327,16 @@ class Router(HookRegistry):raise TypeError("state must not be None; pass a string, dict, or list")if not isinstance(questions, dict):raise TypeError("questions must be a dict of question id -> definition, got %s" % type(questions).__name__)+ from .agent import Agent+ check_fn = Agent._check_question+mc = check_min_confidence(min_confidence) if min_confidence is not None else Noneactive = compose_hooks(self.hooks, hooks, on_predict_start, on_predict_end)raise_errors = self.hooks_raise if hooks_raise is None else bool(hooks_raise)timeout = self.hooks_timeout if hooks_timeout is None else validate_timeout(hooks_timeout)+ has_start = any(callable(getattr(h, "on_predict_start", None)) for h in active)+ctx = PredictContext(states=[state],questions=questions,@@ -1348,6 +1353,9 @@ class Router(HookRegistry):if scan is not None:_SCAN.set(None)try:+ if not has_start:+ for qid, qdef in questions.items():+ check_fn(qid, qdef)# Per-call hooks apply to the whole call, including on_route inside route().decision = self.route(state, questions, model=model, task=task, lang=lang,lang_guess=lang_guess, hooks=hooks, hooks_raise=hooks_raise,@@ -1365,6 +1373,14 @@ class Router(HookRegistry):ctx.started_at = time.perf_counter()dispatch(active, "on_predict_start", ctx, raise_errors=raise_errors, lock=self._hooks_lock, timeout=timeout)if ctx.results is None:+ if has_start:+ if not isinstance(ctx.questions, dict):+ raise TypeError(+ "questions must be a dict of question id -> definition, got %s"+ % type(ctx.questions).__name__+ )+ for qid, qdef in ctx.questions.items():+ check_fn(qid, qdef)skip = _SKIP_DEFAULTS.set(True)try:if scan is not None:diff --git a/tests/test_router.py b/tests/test_router.pyindex 44d24009..ea9b7923 100644--- a/tests/test_router.py+++ b/tests/test_router.py@@ -2250,6 +2250,89 @@ check("sort report/results keep input order regardless",["english"] * 4 + ["multilingual"] * 2)+# --------------------------------------------------------------------- predict input validation (#707)+_r_val = Router()+for label, state, qs, exc_type, err_match in [+ ("state is None", None, Q_GENERIC, TypeError, "state must not be None"),+ ("questions not dict", "text", ["q"], TypeError, "questions must be a dict"),+ ("invalid question type", "text", {"q": {"type": "bogus", "instructions": "x"}}, ValueError, "unknown type 'bogus'"),+ ("missing instructions", "text", {"q": {"type": "noul"}}, ValueError, "no 'instructions'"),+ ("empty instructions", "text", {"q": {"type": "noul", "instructions": ""}}, ValueError, "'instructions' must not be empty"),+ ("empty question id", "text", {"": {"type": "noul", "instructions": "x"}}, ValueError, "question id must be a non-empty string"),+]:+ try:+ _r_val.predict(state, qs)+ FAIL.append("predict validation/%s: should have raised %s" % (label, exc_type.__name__))+ except exc_type as _exc:+ check("predict validation/%s raises %s" % (label, exc_type.__name__), err_match in str(_exc), True)+ except Exception as _exc: # noqa: BLE001+ FAIL.append("predict validation/%s: raised %s instead of %s: %s" %+ (label, type(_exc).__name__, exc_type.__name__, _exc))+check("predict validation/failed calls loaded nothing", _r_val.loaded, [])++try:+ _r_val.route("text", ["q"])+ FAIL.append("route validation/questions not dict: should have raised TypeError")+except TypeError as _exc:+ check("route validation/questions not dict raises TypeError", "questions must be a dict" in str(_exc), True)+except Exception as _exc: # noqa: BLE001+ FAIL.append("route validation/questions not dict: raised %s instead of TypeError: %s" %+ (type(_exc).__name__, _exc))++# A start hook can rewrite an incomplete question before validation runs on it+_r_rewrite = Router()+_fake_ag = _Stub("english")+_fake_ag.predict = lambda s, q, **kw: {"model": "laya-rl-agent", "answers": {}, "usage": {}}+_r_rewrite.attach("english", _fake_ag)+_rewritten_res = _r_rewrite.predict(+ "hello",+ {"q": {"type": "noul"}},+ model="english",+ on_predict_start=lambda ctx: setattr(ctx, "questions", {"q": {"type": "noul", "instructions": "Fixed?"}}),+)+check("predict validation/start hook can complete questions", "routing" in _rewritten_res, True)++# A start hook can short-circuit with ctx.skip() before question validation+_r_skip = Router()+_r_skip.attach("multilingual", _fake_ag)+_skipped_res = _r_skip.predict(+ "hello",+ {"q": {"type": "noul"}},+ on_predict_start=lambda ctx: ctx.skip([{"model": "cached", "answers": {}, "usage": {}}]),+)+check("predict validation/start hook can skip with incomplete questions", "routing" in _skipped_res, True)++# Failure-hook lifecycle: invalid question definitions trigger on_error and on_predict_end without loading models+_r_fail_hook = Router()+_hook_events = []+class _FailHook:+ def on_error(self, ctx):+ _hook_events.append(("error", type(ctx.error).__name__))+ def on_predict_end(self, ctx):+ _hook_events.append(("end", type(ctx.error).__name__))++try:+ _r_fail_hook.predict("text", {"q": {"type": "bogus", "instructions": "x"}}, hooks=[_FailHook()])+ FAIL.append("predict validation/fail hook: should have raised ValueError")+except ValueError:+ pass+check("predict validation/fail hook dispatches on_error and on_predict_end",+ _hook_events, [("error", "ValueError"), ("end", "ValueError")])+check("predict validation/fail hook loaded nothing", _r_fail_hook.loaded, [])++# A hook with non-callable on_predict_start=None is not treated as having a start hook+_r_non_callable = Router()+class _DummyHook:+ on_predict_start = None++try:+ _r_non_callable.predict("text", {"q": {"type": "bogus", "instructions": "x"}}, hooks=[_DummyHook()])+ FAIL.append("predict validation/non-callable start hook: should have raised ValueError")+except ValueError:+ pass+check("predict validation/non-callable start hook rejects before load", _r_non_callable.loaded, [])++# --------------------------------------------------------------------- reportprint("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL: