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): add laya_predict_long for states past the context window
Aashish98f825cc6bba
diff --git a/README.md b/README.mdindex cdfe1c30..27679545 100644--- a/README.md+++ b/README.md@@ -1322,7 +1322,7 @@ TileLang fast path and `compile=True` refuse such a checkpoint, and `backend="auLaya can be exposed as an [MCP](https://modelcontextprotocol.io) stdio server, so any MCPclient (OpenClaw, Claude Desktop, Cursor, ...) can call typed decisions as tools-(`laya_predict`, `laya_predict_batch`, `laya_route`, `laya_route_batch`, `laya_decide`, `laya_shortlist`, `laya_preset`, `laya_status`) without writing glue code.+(`laya_predict`, `laya_predict_batch`, `laya_route`, `laya_route_batch`, `laya_decide`, `laya_shortlist`, `laya_predict_long`, `laya_preset`, `laya_status`) without writing glue code.This is an **optional extra**: the core package has no `mcp` dependency.```bash@@ -1385,7 +1385,9 @@ downloaded), answers in one forward pass, and returns per-question shortlist metunshortlisted). The guardrails shown on every decisiontool point clients to `laya_shortlist` for >20-option choices. As with the SDK, use it for structureddecisions only; not for open Q&A or-text generation. Tests: `tests/test_mcp.py` (CI, no weights) and+text generation. `laya_predict_long` is the MCP form of [`predict_long`](#long-documents-predict_long): it+scans a state past the context window in overlapping windows and answers with per-answer+window attribution plus the window count. Tests: `tests/test_mcp.py` (CI, no weights) and`tests/test_mcp_local_e2e.py` (local, real weights and a real stdio handshake).---diff --git a/docs/cli-mcp.md b/docs/cli-mcp.mdindex 736436be..b98ec39c 100644--- a/docs/cli-mcp.md+++ b/docs/cli-mcp.md@@ -165,6 +165,7 @@ Laya does not open a network port.| `laya_predict_batch` | Answers many requests in one call. Requests are routed first and grouped by checkpoint, so matching question schemas share forward passes; answers come back in input order. | `requests`, each `{state, questions, model?, task?, lang?, lang_guess?, max_len?, head_max_len?}`, optional `batch_size`, `hooks_timeout`, `min_confidence`, `sort_by_length` || `laya_route_batch` | Decides which checkpoint would answer each request, with no forward pass and no checkpoint load. | `requests`, each `{state, questions, model?, task?, lang?, lang_guess?}`, optional `hooks_timeout` || `laya_decide` | Answers a JSON-schema-shaped decision in one forward pass and returns the decided values with per-field confidence, instead of an answer map to parse. Schema properties may be enum choices, booleans, or integers with a minimum and maximum; free strings, arrays, and nested objects are rejected by path. | `state`, `schema`, optional `model`, `min_confidence` |+| `laya_predict_long` | Scans a state longer than the context window in overlapping windows, then answers with per-answer window attribution and the window count. | `state`, `questions`, optional `model`, optional `window`, optional `stride` |The three batch and schema tools exist because the same operations are available on the SDK and`laya-serve`: handling many requests, or serving a caller that already knows the answer shape,@@ -179,6 +180,14 @@ option count, and whether the question passed through unshortlisted for each shoquestion. A question with `k` at or past its option count is passed through unchanged, soits cosine scores come back `null` rather than empty.+When the state itself does not fit one window, `laya_predict` answers from its first window and+never reads the rest. `laya_predict_long` tokenizes the state once, scores it in overlapping+windows sized by `window` (default: the checkpoint budget) stepped by `stride` (default: half+the window), and aggregates per question -- strongest window for `noul`, most-confident window+for `choice`/`score`. Each answer names its deciding window, and the result counts the windows+scored. There is no `min_confidence` here and no `max_len`/`head_max_len`: core's scan takes+neither.+`state` must be a non-empty JSON object. `questions` must be a non-empty object whose values useLaya's typed question schema. `laya_preset` accepts the same five presets the CLI does: `email`,`guard`, `moderation`, `triage`, and the router workflow, whose canonical name on this surface isdiff --git a/laya/mcp/server.py b/laya/mcp/server.pyindex 41a57990..97890604 100644--- a/laya/mcp/server.py+++ b/laya/mcp/server.py@@ -52,6 +52,7 @@ from .tools import (get_available_presets,laya_predict,laya_predict_batch,+ laya_predict_long,laya_preset,laya_route,laya_route_batch,@@ -506,6 +507,33 @@ def laya_decide_tool(state: dict, schema: dict, model: str = "auto",min_confidence=min_confidence, router=router)+ name="laya_predict_long",+ description=(+ "Answer typed questions over a state longer than the context window: the state is "+ "scanned in overlapping windows in shared forward passes and aggregated per question "+ "(strongest window for noul, most-confident window for choice/score). Use this instead "+ "of laya_predict whenever the state does not fit one window -- laya_predict answers "+ "from its first window and never reads the rest. Returns the answers, each with the "+ "deciding window's attribution, plus the window count. "+ "window / stride: positive integers sizing the scan (a smaller window isolates a "+ "localized span); unset means the checkpoint budget and 50% overlap. "+ "task: name a checkpoint by what the work is -- refused on a call that also pins model. "+ "lang: a language code -- routes non-English text and selects that checkpoint's "+ "per-language calibration. "+ + _GUARDRAILS+ + _MODEL_DOC+ ),+)+def laya_predict_long_tool(state: dict, questions: dict, model: str = "auto",+ window: int | None = None, stride: int | None = None,+ task: str | None = None, lang: str | None = None) -> str:+ """Scan a long state in windows, then answer."""+ router = _router_or_error()+ return _wrap(laya_predict_long, state=state, questions=questions, model=model,+ window=window, stride=stride, task=task, lang=lang, router=router)++def main() -> None:# Windows without Developer Mode cannot create HF cache symlinks (WinError# 1314). On POSIX the cache uses symlinks by default and disabling themdiff --git a/laya/mcp/tools.py b/laya/mcp/tools.pyindex 30a96636..63aa0f20 100644--- a/laya/mcp/tools.py+++ b/laya/mcp/tools.py@@ -834,6 +834,122 @@ def laya_shortlist(return out+def laya_predict_long(+ state: Any,+ questions: Any,+ model: Any = "auto",+ *,+ window: Any = None,+ stride: Any = None,+ task: Any = None,+ lang: Any = None,+ router: Any = None,+ agent: Any = None,+) -> dict:+ """Scan a state longer than the context window, then answer.++ The in-process ``predict_long`` pattern over MCP: the state is tokenized once, scored in+ overlapping windows in shared forward passes, and aggregated per question (strongest window+ for ``noul``, most-confident window for ``choice``/``score``). Use this instead of+ ``laya_predict`` when the state does not fit one window -- ``laya_predict`` answers from+ its first window and never reads the rest.++ ``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``); ``window``/``stride`` size the scan the way core's+ ``predict_long`` sizes it, and only set values are forwarded, so a checkpoint that predates+ those keywords keeps working. ``max_len``/``head_max_len``/``min_confidence`` are not+ accepted here because core's ``predict_long`` takes none of them: a window is sized by+ ``window`` or the checkpoint budget, and there is no abstention gate on the scan.++ Each answer carries the deciding window's ``window`` attribution (index and token offsets+ into the tokenized state), and ``windows`` counts the windows the model scored.+ """+ state_d = validate_state(state)+ questions_d = validate_questions(questions)+ model_name = validate_model(model)+ # Only what the caller actually set is forwarded: `_overrides` is not reused because its keys+ # are the single-window budgets, and `predict_long` rejects those -- the scan is sized by+ # `window`/`stride` or the checkpoint budget instead.+ scan = {name: value for name, value in (+ ("task", validate_task(task)),+ ("lang", validate_lang(lang)),+ ("window", validate_budget(window, "window")),+ ("stride", validate_budget(stride, "stride")),+ ) if value is not None}+ # `task` picks a checkpoint by saying what the work is, so it means nothing once one is pinned:+ # same rule as `laya_predict` -- the router checks an explicit `model` first and never reaches+ # the task, and a checkpoint's `predict_long` does not accept the keyword at all.+ if model_name != AUTO and "task" in scan:+ raise ToolError(+ "invalid_task",+ "task routes between checkpoints; with a pinned model there is nothing to route",+ )+ auto_without_router = False++ def _run() -> Any:+ if model_name == "auto":+ if router is None:+ if agent is None:+ raise ToolError("models_not_ready", "Router is not loaded (auto mode)")+ # An Agent answers but does not route: run it directly and report+ # a null model below, instead of echoing 'auto' (#444).+ nonlocal auto_without_router+ auto_without_router = True+ return _scan(agent, state_d, questions_d, **scan)+ return _scan(router, state_d, questions_d, **scan)+ if agent is not None:+ return _scan(agent, state_d, questions_d, **scan)+ if router is None:+ raise ToolError("models_not_ready", "no agent/router loaded")+ return _scan(router, state_d, questions_d, model=model_name, **scan)++ started = time.perf_counter()+ result = _run()+ latency_ms = (time.perf_counter() - started) * 1000.0++ if not isinstance(result, dict):+ raise ToolError("internal_error", "predict_long returned non-object")+ answers = _normalize_answers(result.get("answers"))+ usage = result.get("usage") or {}+ windows = usage.get("windows", 0) if isinstance(usage, dict) else 0+ if auto_without_router:+ routing = {"model": None, "repo": None, "reason": "auto routing without router"}+ elif model_name == "auto":+ # A bare agent's scan carries no 'routing' key because the Agent itself does no+ # routing; 'auto' is a routing directive, not a checkpoint name (#444). A Router's+ # scan carries the decision it routed with.+ routing = (result.get("routing") or {"model": None, "repo": None,+ "reason": "auto routing without router"})+ else:+ routing = {"model": model_name, "repo": None, "reason": "explicit model"}+ device = None if auto_without_router else _reading_device(router, agent, model_name,+ result.get("routing"))+ out: dict[str, Any] = {+ "answers": answers,+ "routing": routing,+ "windows": windows,+ "latency_ms": round(latency_ms, 3),+ }+ if device:+ out["device"] = device+ return out+++def _scan(target: Any, state: Any, questions: Any, **kwargs: Any) -> Any:+ """Call ``predict_long`` on a router or agent, refusing clearly without it.++ A checkpoint old enough to predate the scan (or a hand-rolled stand-in) has no+ ``predict_long``; falling back to ``predict`` would silently answer from the first+ window, which is exactly what this tool exists to avoid.+ """+ fn = getattr(target, "predict_long", None)+ if not callable(fn):+ raise ToolError("internal_error", "%s has no predict_long() method"+ % type(target).__name__)+ return fn(state, questions, **kwargs)++def laya_preset(preset: Any,state: Any,diff --git a/tests/test_mcp.py b/tests/test_mcp.pyindex a0611990..5df5f798 100644--- a/tests/test_mcp.py+++ b/tests/test_mcp.py@@ -41,6 +41,7 @@ from laya.mcp.tools import ( # noqa: E402laya_decide,laya_predict,laya_predict_batch,+ laya_predict_long,laya_preset,laya_route,laya_route_batch,@@ -1450,6 +1451,133 @@ def test_shortlist_embed_cache():"calls=%d" % len(calls))+# --- long-document scan ----------------------------------------------------++LONG_QUESTIONS = {"refund": {"type": "noul", "instructions": "Does the user ask for a refund?"}}+++class LongAgent:+ device = "cpu"++ def __init__(self):+ self.seen = None++ def predict_long(self, state, questions, **kwargs):+ self.seen = kwargs+ return {"answers": {"refund": {"noul": 0.8, "confidence": 0.7,+ "window": {"index": 0, "token_start": 0,+ "token_end": 10, "count": 3}}},+ "usage": {"windows": 3}}+++class LongRouter:+ """Fake router with predict_long: records the scan kwargs, answers from window 0."""++ def __init__(self, routed="english"):+ self.routed = routed+ self.seen = None+ self._agents = {"english": LongAgent()}++ def predict_long(self, state, questions, **kwargs):+ self.seen = kwargs+ return {"answers": {"refund": {"noul": 0.8, "confidence": 0.7,+ "window": {"index": 0, "token_start": 0,+ "token_end": 10, "count": 3}}},+ "routing": {"model": kwargs.get("model", self.routed), "repo": "fake/repo",+ "reason": "unit-test scan"},+ "usage": {"windows": 3}}+++class NoScanAgent:+ device = "cpu"++ def predict(self, state, questions, **kwargs):+ raise AssertionError("predict must not answer a long-document call")+++def test_predict_long():+ expect_tool_error("long/state_bad",+ lambda: laya_predict_long([], LONG_QUESTIONS, router=LongRouter()),+ "invalid_state")+ expect_tool_error("long/questions_bad",+ lambda: laya_predict_long(STATE, {}, router=LongRouter()),+ "invalid_questions")+ expect_tool_error("long/model_bad",+ lambda: laya_predict_long(STATE, LONG_QUESTIONS, model="gpt4",+ router=LongRouter()),+ "invalid_model")+ for bad in (0, -3, True, 2.5, "256"):+ expect_tool_error("long/window_bad_%r" % (bad,),+ lambda b=bad: laya_predict_long(STATE, LONG_QUESTIONS, window=b,+ router=LongRouter()),+ "invalid_window")+ expect_tool_error("long/stride_bad_%r" % (bad,),+ lambda b=bad: laya_predict_long(STATE, LONG_QUESTIONS, stride=b,+ router=LongRouter()),+ "invalid_stride")+ expect_tool_error("long/task_with_pinned_model",+ lambda: laya_predict_long(STATE, LONG_QUESTIONS, model="english",+ task="triage", router=LongRouter()),+ "invalid_task")+ expect_tool_error("long/auto_needs_router",+ lambda: laya_predict_long(STATE, LONG_QUESTIONS), "models_not_ready")+ expect_tool_error("long/explicit_not_loaded",+ lambda: laya_predict_long(STATE, LONG_QUESTIONS, model="english"),+ "models_not_ready")+ expect_tool_error("long/no_scan_method",+ lambda: laya_predict_long(STATE, LONG_QUESTIONS, model="english",+ agent=NoScanAgent()),+ "internal_error")++ # Auto mode scans through the router: unset scan controls are not forwarded, so a+ # checkpoint that predates those keywords keeps working.+ router = LongRouter()+ out = laya_predict_long(STATE, LONG_QUESTIONS, router=router)+ ok("long/scan_kwargs_unset_absent", router.seen == {}, repr(router.seen))+ ok("long/answers", out["answers"]["refund"]["noul"] == 0.8, repr(out["answers"]))+ ok("long/window_attribution",+ out["answers"]["refund"]["window"] == {"index": 0, "token_start": 0,+ "token_end": 10, "count": 3},+ repr(out["answers"]))+ ok("long/windows", out["windows"] == 3, repr(out))+ ok("long/routing", out["routing"]["model"] == "english", repr(out["routing"]))+ ok("long/device", out.get("device") == "cpu", repr(out.get("device")))+ ok("long/latency", isinstance(out["latency_ms"], float))++ # Set values travel: window/stride size the scan, lang rides for calibration.+ router = LongRouter()+ laya_predict_long(STATE, LONG_QUESTIONS, window=256, stride=128, lang="de", router=router)+ ok("long/scan_kwargs_forwarded", router.seen == {"window": 256, "stride": 128, "lang": "de"},+ repr(router.seen))++ # Explicit model pins the scan: task would have nothing to route, the model rides along.+ router = LongRouter()+ out = laya_predict_long(STATE, LONG_QUESTIONS, model="english", task=None, router=router)+ ok("long/explicit_model_forwarded", router.seen == {"model": "english"}, repr(router.seen))+ ok("long/explicit_routing",+ out["routing"] == {"model": "english", "repo": None, "reason": "explicit model"},+ repr(out["routing"]))++ # Explicit model with an injected agent answers directly, device read off it.+ agent = LongAgent()+ out = laya_predict_long(STATE, LONG_QUESTIONS, model="english", agent=agent)+ ok("long/agent_answers", out["answers"]["refund"]["noul"] == 0.8, repr(out["answers"]))+ ok("long/agent_scan_kwargs", agent.seen == {}, repr(agent.seen))+ ok("long/agent_routing",+ out["routing"] == {"model": "english", "repo": None, "reason": "explicit model"},+ repr(out["routing"]))+ ok("long/agent_device", out.get("device") == "cpu", repr(out.get("device")))+ ok("long/agent_windows", out["windows"] == 3, repr(out))++ # Auto mode with a bare agent: no routing happened, so no model is named.+ agent = LongAgent()+ out = laya_predict_long(STATE, LONG_QUESTIONS, agent=agent)+ ok("long/bare_agent_routing",+ out["routing"] == {"model": None, "repo": None, "reason": "auto routing without router"},+ repr(out["routing"]))+ ok("long/bare_agent_no_device", "device" not in out, repr(out))++# --- per-call controls: task / lang / max_len / head_max_len -------------------class ControlRouter:@@ -1799,7 +1927,10 @@ def test_controls_signature_and_schema():controls = ["task", "lang", "lang_guess", "max_len", "head_max_len"]for fn, want in ((laya_predict, controls), (laya_shortlist, controls),- (laya_preset, controls), (laya_route, ["model", "task", "lang", "lang_guess"])):+ (laya_preset, controls), (laya_route, ["model", "task", "lang", "lang_guess"]),+ # predict_long sizes the scan by window/stride, not the single-window+ # budgets, so only the routing overrides are shared controls here.+ (laya_predict_long, ["task", "lang"])):params = inspect.signature(fn).parametersfor name in want:ok("signature/%s_has_%s" % (fn.__name__, name), name in params, repr(sorted(params)))@@ -1813,7 +1944,8 @@ def test_controls_signature_and_schema():by_name = {t.name: t for t in asyncio.run(mcp_server.list_tools())}for name, want in (("laya_predict", controls), ("laya_shortlist", controls),- ("laya_preset", controls), ("laya_route", ["model", "task", "lang"])):+ ("laya_preset", controls), ("laya_route", ["model", "task", "lang"]),+ ("laya_predict_long", ["task", "lang"])):tool = by_name[name]schema = tool.input_schema if hasattr(tool, "input_schema") else tool.inputSchemaprops = schema.get("properties", {})@@ -2280,7 +2412,7 @@ def test_timeout_removed():import laya.mcp.tools as tools_modfor fn in (laya_predict, laya_route, laya_preset, laya_shortlist,- laya_predict_batch, laya_route_batch, laya_decide):+ laya_predict_batch, laya_route_batch, laya_decide, laya_predict_long):ok("timeout/param_absent_%s" % fn.__name__, "timeout" not in inspect.signature(fn).parameters)ok("timeout/executor_absent", "ThreadPoolExecutor" not in inspect.getsource(tools_mod))@@ -2574,10 +2706,11 @@ def test_server_registration():tools = asyncio.run(mcp_server.list_tools())names = sorted(t.name for t in tools)ok("server/tool_names", names == ["laya_decide", "laya_predict", "laya_predict_batch",- "laya_preset", "laya_route", "laya_route_batch",- "laya_shortlist", "laya_status"], repr(names))+ "laya_predict_long", "laya_preset", "laya_route",+ "laya_route_batch", "laya_shortlist", "laya_status"],+ repr(names))decision = {"laya_predict", "laya_route", "laya_preset", "laya_shortlist",- "laya_predict_batch", "laya_route_batch", "laya_decide"}+ "laya_predict_batch", "laya_route_batch", "laya_decide", "laya_predict_long"}for t in tools:desc = (t.description or "").lower()ok("server/desc_%s_nonempty" % t.name, bool(desc.strip()), repr(desc))@@ -2769,6 +2902,7 @@ test_batch_route()test_decide()test_shortlist_lang_parity()test_shortlist_embed_cache()+test_predict_long()test_controls_validation()test_controls_predict()test_controls_route()