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
feat(mcp): expose task/lang/max_len/head_max_len on the decision tools
Aashishd38aab24a523
diff --git a/laya/mcp/server.py b/laya/mcp/server.pyindex 0a0ddade..63750e7b 100644--- a/laya/mcp/server.py+++ b/laya/mcp/server.py@@ -84,6 +84,20 @@ _MODEL_DOC = ("routing.model always reports the canonical name.")+# The routing overrides and the token budget, spelled out once because the tools take them as free+# strings and integers. Precedence matters to say plainly: a client that pins a model and also sets+# a task would otherwise see the task silently ignored (the tool rejects it instead).+_CONTROLS_DOC = (+ " task: name a checkpoint by what the work is ('typed_decisions', or any checkpoint name) -- "+ "refused on a call that also pins model, since the pin would win and the task would be ignored. "+ "lang: a language code ('de', 'en-US') -- routes non-English text to the multilingual "+ "checkpoint and selects that checkpoint's per-language calibration. "+ "max_len / head_max_len: positive integers overriding the answering token budget for this call "+ "only -- head_max_len is the option-and-instructions budget, so raise it when a choice question "+ "has many options and the answers look like the labels blur together. Leave any of them unset to "+ "keep the checkpoint's own default."+)+def _models_from_env() -> list[str]:"""Preload list from LAYA_MODELS (laya.serve contract: comma list of names).@@ -178,13 +192,31 @@ def laya_status_tool() -> str:description=("Decide which Laya checkpoint would answer, without running a forward pass. ""Use this to explain routing (english vs multilingual vs typed-decisions) to the user. "+ "Passing a laya_predict call's model/task/lang here reproduces the routing block it "+ "reported, without paying for the forward pass; leaving model unset (or 'auto') routes as "+ "normal. "+ _GUARDRAILS+ + _CONTROLS_DOC),)-def laya_route_tool(state: dict, questions: dict) -> str:+def laya_route_tool(+ state: dict,+ questions: dict,+ model: str | None = None,+ task: str | None = None,+ lang: str | None = None,+) -> str:"""Decide which Laya checkpoint would answer, without running a forward pass."""router = _router_or_error()- return _wrap(laya_route, state=state, questions=questions, router=router)+ return _wrap(+ laya_route,+ state=state,+ questions=questions,+ model=model,+ task=task,+ lang=lang,+ router=router,+ )@server.tool(@@ -197,9 +229,18 @@ def laya_route_tool(state: dict, questions: dict) -> str:"device of the checkpoint that answered. "+ _GUARDRAILS+ _MODEL_DOC+ + _CONTROLS_DOC),)-def laya_predict_tool(state: dict, questions: dict, model: str = "auto") -> str:+def laya_predict_tool(+ state: dict,+ questions: dict,+ model: str = "auto",+ task: str | None = None,+ lang: str | None = None,+ max_len: int | None = None,+ head_max_len: int | None = None,+) -> str:"""Answer typed questions (choice/score/noul) over any state in one forward pass."""router = _router_or_error()return _wrap(@@ -207,6 +248,10 @@ def laya_predict_tool(state: dict, questions: dict, model: str = "auto") -> str:state=state,questions=questions,model=model,+ task=task,+ lang=lang,+ max_len=max_len,+ head_max_len=head_max_len,router=router,)@@ -220,11 +265,23 @@ def laya_predict_tool(state: dict, questions: dict, model: str = "auto") -> str:"laya_predict whenever a choice question has more options than the guardrails allow. ""Returns the answers plus per-question shortlist metadata (kept labels, cosine ""scores, k, option count). "+ "Shortlisting narrows the label set; head_max_len decides how many tokens each kept label "+ "is read with, so the two together are the fix for a large-criteria question. "+ _GUARDRAILS+ _MODEL_DOC+ + _CONTROLS_DOC),)-def laya_shortlist_tool(state: dict, questions: dict, model: str = "auto", k: int = 20) -> str:+def laya_shortlist_tool(+ state: dict,+ questions: dict,+ model: str = "auto",+ k: int = 20,+ task: str | None = None,+ lang: str | None = None,+ max_len: int | None = None,+ head_max_len: int | None = None,+) -> str:"""Shortlist many-option choice questions, then answer."""# k's default mirrors laya.shortlist.DEFAULT_SHORTLIST_K; it is a literal# here so the MCP schema carries the default without importing numpy at@@ -236,6 +293,10 @@ def laya_shortlist_tool(state: dict, questions: dict, model: str = "auto", k: inquestions=questions,model=model,k=k,+ task=task,+ lang=lang,+ max_len=max_len,+ head_max_len=head_max_len,router=router,)@@ -260,20 +321,31 @@ _PRESET_DOC = (for name, info in _PRESET_INFO.items()for alias in info.get("aliases", [])),)-) + _GUARDRAILS+) + _GUARDRAILS + _CONTROLS_DOC@server.tool(name="laya_preset",description=_PRESET_DOC,)-def laya_preset_tool(preset: str, state: dict) -> str:+def laya_preset_tool(+ preset: str,+ state: dict,+ task: str | None = None,+ lang: str | None = None,+ max_len: int | None = None,+ head_max_len: int | None = None,+) -> str:"""Run a built-in workflow preset; the tool description carries the names and state fields."""router = _router_or_error()return _wrap(laya_preset,preset=preset,state=state,+ task=task,+ lang=lang,+ max_len=max_len,+ head_max_len=head_max_len,router=router,preset_builder=_preset_builder,)diff --git a/laya/mcp/tools.py b/laya/mcp/tools.pyindex e320c802..9aa3b62f 100644--- a/laya/mcp/tools.py+++ b/laya/mcp/tools.py@@ -176,6 +176,73 @@ def validate_model(model: Any) -> str:raise ToolError("invalid_model", "%s, or %r" % (error, AUTO)) from None+def validate_task(task: Any) -> str | None:+ """Core's ``task`` override, checked the way core checks it, or ``None`` for "not set".++ ``Router._route`` sends ``task`` through the same ``normalise_name`` as ``model`` and then looks+ the result up in its registry, so a task that names nothing raises ``KeyError`` from inside the+ router -- and over MCP a ``KeyError`` is reported as ``internal_error``, which tells a caller+ nothing about what it typed. Validating here turns that into ``invalid_task`` with the list of+ names that do resolve. The caller's own spelling is what gets forwarded, so ``routing.reason``+ still reads as the request that was made.+ """+ if task is None:+ return None+ from laya.router import normalise_name++ # The remap is core's own expression, copied rather than relied upon through the alias table:+ # `Router._route` turns task="typed_decisions" (the underscore form the CLI and the question ids+ # use) into the hyphenated checkpoint name before normalising it. `_ALIASES` happens to hold the+ # same mapping today, so this costs nothing and keeps the two paths agreeing if it ever goes.+ name = "typed-decisions" if str(task).lower().replace("-", "_") == "typed_decisions" else task+ try:+ normalise_name(name)+ except ValueError as error:+ raise ToolError("invalid_task", "%s, or %r" % (error, "typed_decisions")) from None+ return task+++def validate_lang(lang: Any) -> str | None:+ """A language code for core's ``lang`` override, or ``None`` for "not set".++ Passed through verbatim: what a code means is core's business -- on the router it decides which+ checkpoint can read the state, on a checkpoint it selects the per-language temperature table --+ and a blank or unknown code falls through to the built-in detection rather than failing. Only+ the type is checked, because a truthy list or object would reach the temperature lookup and+ raise ``AttributeError`` on ``.split`` deep inside a forward pass.+ """+ if lang is None:+ return None+ if not isinstance(lang, str):+ raise ToolError("invalid_lang", "lang must be a language code like 'en' or 'de', got %r" % (lang,))+ return lang+++def validate_budget(value: Any, name: str) -> int | None:+ """One of the two per-call token budgets (``max_len``, ``head_max_len``), or ``None``.++ Core slices and compares against these, so a float, a numeric string or a zero does not fail+ cleanly -- it truncates the sequence to nothing or raises ``TypeError`` mid-forward. ``None``+ means "use what the checkpoint was trained with", which is the same thing the CLI's flags mean.+ """+ if value is None:+ return None+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise ToolError("invalid_%s" % name, "%s must be a positive integer, got %r" % (name, value))+ return value+++def _overrides(task: Any, lang: Any, max_len: Any, head_max_len: Any) -> dict:+ """The per-call controls as keyword arguments, with the unset ones left out.++ Only what the caller actually set is forwarded: an injectable router or agent is not required to+ accept a keyword it was never asked about, and dropping the unset ones keeps every call that+ passes no controls byte-identical to the call it made before they existed.+ """+ values = {"task": task, "lang": lang, "max_len": max_len, "head_max_len": head_max_len}+ return {name: value for name, value in values.items() if value is not None}++def _normalize_answers(raw: Any) -> dict:if not isinstance(raw, dict):raise ToolError("internal_error", "predict returned non-object answers")@@ -187,27 +254,51 @@ def laya_predict(questions: Any,model: Any = "auto",*,+ task: Any = None,+ lang: Any = None,+ max_len: Any = None,+ head_max_len: Any = None,router: Any = None,agent: Any = None,) -> dict:"""Typed questions, one forward pass.``router`` is used when model == "auto"; ``agent`` for a direct checkpoint.++ ``task``/``lang`` are the router's own overrides (an explicit ``model`` outranks an explicit+ ``task``, which outranks an explicit ``lang``); ``max_len``/``head_max_len`` override the token+ budget the answering checkpoint was configured with. None of them is forwarded unless set, so a+ router or agent that predates those keywords keeps working."""state_d = validate_state(state)questions_d = validate_questions(questions)model_name = validate_model(model)+ budget = _overrides(+ validate_task(task),+ validate_lang(lang),+ validate_budget(max_len, "max_len"),+ validate_budget(head_max_len, "head_max_len"),+ )+ # `task` picks a checkpoint by saying what the work is, so it means nothing once one is pinned:+ # `Router._route` checks an explicit `model` first and never reaches the task, and+ # `Agent.system_one` does not accept the keyword at all. Both would answer as if it were unset,+ # so it is refused here instead.+ if model_name != AUTO and "task" in budget:+ raise ToolError(+ "invalid_task",+ "task routes between checkpoints; with a pinned model there is nothing to route",+ )def _run() -> Any:if model_name == "auto":if router is None:raise ToolError("models_not_ready", "Router is not loaded (auto mode)")- return router.predict(state_d, questions_d)+ return router.predict(state_d, questions_d, **budget)if agent is not None:- return agent.predict(state_d, questions_d)+ return agent.predict(state_d, questions_d, **budget)if router is None:raise ToolError("models_not_ready", "no agent/router loaded")- return router.predict(state_d, questions_d, model=model_name)+ return router.predict(state_d, questions_d, model=model_name, **budget)started = time.perf_counter()result = _run()@@ -239,15 +330,49 @@ def laya_predict(return out-def laya_route(state: Any, questions: Any, *, router: Any = None) -> dict:- """Routing decision only: no forward pass."""+def laya_route(+ state: Any,+ questions: Any,+ *,+ model: Any = None,+ task: Any = None,+ lang: Any = None,+ router: Any = None,+) -> dict:+ """Routing decision only: no forward pass.++ Takes the three routing overrides :meth:`laya_predict` takes -- ``model``, ``task``, ``lang`` --+ so "which checkpoint would this go to?" can be asked under a pin without running anything.+ Passing a predict call's controls here reproduces the ``routing`` block it returned, which is+ what makes a route a cheap explanation of a decision rather than a different decision.+ """state_d = validate_state(state)questions_d = validate_questions(questions)+ # `auto` is this layer's word for "do not pin"; core has no such name, so it becomes an absent+ # override rather than a ValueError from normalise_name.+ model_name = validate_model(model)+ task_name = validate_task(task)+ # Same rule as the decision tools: `_route` checks an explicit model first and never reaches+ # the task, so a call that sets both is asking a question with two answers.+ if model_name != AUTO and task_name is not None:+ raise ToolError(+ "invalid_task",+ "task routes between checkpoints; with a pinned model there is nothing to route",+ )+ overrides: dict[str, Any] = {}+ if model_name != AUTO:+ overrides["model"] = model_name+ if task_name is not None:+ overrides["task"] = task_name+ lang_code = validate_lang(lang)+ if lang_code is not None:+ overrides["lang"] = lang_code+ # Everything the caller typed is checked before the server is asked for a checkpoint.if router is None:raise ToolError("models_not_ready", "Router is not loaded")if not hasattr(router, "route"):raise ToolError("internal_error", "router has no route() method")- decision = router.route(state_d, questions_d)+ decision = router.route(state_d, questions_d, **overrides)if isinstance(decision, dict):return {"model": decision.get("model"),@@ -284,6 +409,10 @@ def laya_shortlist(model: Any = "auto",k: Any = None,*,+ task: Any = None,+ lang: Any = None,+ max_len: Any = None,+ head_max_len: Any = None,router: Any = None,agent: Any = None,embed_fn: Callable[[Sequence[str]], Any] | None = None,@@ -299,6 +428,11 @@ def laya_shortlist(``routing`` reports the real route decision in auto mode (the forwardpass then runs with an explicit ``model=``, so routing happens once).++ ``head_max_len`` matters more here than anywhere else: shortlisting exists+ because a large label set shares that budget, and narrowing to ``k`` is only+ half of the fix. The budget override reaches the answering forward pass;+ ``task``/``lang`` reach the route that chose the checkpoint."""# Lazy: keeps numpy/shortlist out of module import for laya.mcp.tools.from laya.shortlist import DEFAULT_SHORTLIST_K, embed_fn_from_agent, predict_shortlist@@ -306,6 +440,19 @@ def laya_shortlist(state_d = validate_state(state)questions_d = validate_questions(questions)model_name = validate_model(model)+ routing_overrides = _overrides(validate_task(task), validate_lang(lang), None, None)+ budget = _overrides(None, None, validate_budget(max_len, "max_len"),+ validate_budget(head_max_len, "head_max_len"))+ # Same rule as `laya_predict`: a checkpoint is already pinned, so `task` has nothing left to+ # decide -- and it is a routing keyword, which the answering `system_one` does not accept.+ if model_name != AUTO and "task" in routing_overrides:+ raise ToolError(+ "invalid_task",+ "task routes between checkpoints; with a pinned model there is nothing to route",+ )+ # `lang` survives pinning because it means two things: it can route, and on the answering+ # checkpoint it selects the per-language temperature table.+ forward_overrides = {name: value for name, value in routing_overrides.items() if name != "task"}if k is None:k = DEFAULT_SHORTLIST_Kif isinstance(k, bool) or not isinstance(k, int) or k < 1:@@ -317,7 +464,7 @@ def laya_shortlist(raise ToolError("models_not_ready", "Router is not loaded (auto mode)")if not hasattr(router, "route"):raise ToolError("internal_error", "router has no route() method")- decision = router.route(state_d, questions_d)+ decision = router.route(state_d, questions_d, **routing_overrides)if isinstance(decision, dict):routed = decision.get("model")routing = {@@ -335,20 +482,23 @@ def laya_shortlist(if not isinstance(routed, str) or not routed:raise ToolError("internal_error", "router.route returned no model")predict_target = router- predict_kwargs: dict[str, Any] = {"model": routed}+ # The route already happened here, so the forward pass pins that checkpoint instead of+ # routing a second time.+ predict_kwargs: dict[str, Any] = {"model": routed, **forward_overrides, **budget}embed_agent = _resident_or_load(router, routed)- elif agent is not None:- routing = {"model": model_name, "repo": None, "reason": "explicit model"}- predict_target = agent- predict_kwargs = {}- embed_agent = agentelse:- if router is None:- raise ToolError("models_not_ready", "no agent/router loaded")routing = {"model": model_name, "repo": None, "reason": "explicit model"}- predict_target = router- predict_kwargs = {"model": model_name}- embed_agent = _resident_or_load(router, model_name)+ if agent is not None:+ predict_target = agent+ predict_kwargs = dict(forward_overrides)+ embed_agent = agent+ else:+ if router is None:+ raise ToolError("models_not_ready", "no agent/router loaded")+ predict_target = router+ predict_kwargs = {"model": model_name, **forward_overrides}+ embed_agent = _resident_or_load(router, model_name)+ predict_kwargs.update(budget)if embed_fn is None:try:@@ -383,6 +533,10 @@ def laya_preset(preset: Any,state: Any,*,+ task: Any = None,+ lang: Any = None,+ max_len: Any = None,+ head_max_len: Any = None,router: Any = None,agent: Any = None,preset_builder: Callable[[str], dict] | None = None,@@ -394,6 +548,10 @@ def laya_preset(asked to trust an answer about a field that is not there. So a state that is one string getsplaced under the field the questions actually name; anything richer than that is the caller'sshape and is passed through untouched.++ The preset fixes the questions, not the route or the budget, so the per-call controls a+ hand-written :func:`laya_predict` takes are available here too -- most usefully ``lang``, since+ a preset's instructions are English text whatever state they read."""preset_name = validate_preset(preset)state_d = validate_state(state)@@ -409,6 +567,10 @@ def laya_preset(state_d,questions,model="auto",+ task=task,+ lang=lang,+ max_len=max_len,+ head_max_len=head_max_len,router=router,agent=agent,)