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(langchain): send max_len/head_max_len to laya-serve instead of refusing them

Nandakishor588766b7051d
diff --git a/docs/langchain.md b/docs/langchain.md
index 639fc89e..da3b9655 100644
--- a/docs/langchain.md
+++ b/docs/langchain.md
@@ -1,53 +1,3 @@
-
----
-
-## 5. Widening the Token Budget for Many Options
-
-Every runnable takes `max_len` and `head_max_len`, the two per-request knobs the core API accepts.
-A choice question's options share the checkpoint's *option* budget -- `head_max_len`, 192 tokens on
-`laya` and 256 on `laya-multilingual` -- and each option carries its own description, so past
-roughly 20 options every label is trimmed to fit and similar labels start reaching the model as the
-same text. See the README's [Honest limits](https://github.com/NandhaKishorM/laya#honest-limits)
-for the same effect measured on Banking77.
-
-Two situations call for it. A routing node with many branches overflows the *option* budget, and
-a long document overflows the *state* budget -- the README's own long-document guidance is literally
-`router.predict(long_document, questions, model="multilingual", max_len=8192)`, which until now was
-unspeakable from a chain step. Both go through the same two arguments:
-
-```python
-router = LayaRouter(
- criteria=queue_criteria, # 48 queues, each with a description
- instructions="Which support queue owns this ticket?",
- max_len=1024, # total window
- head_max_len=512, # tokens shared by the option prompt
-)
-```
-
-Measured on `laya` (Apple silicon, one forward pass per state, scored on the chosen label) with
-queue labels a state names explicitly, so ground truth is exact. Each cell is the count over the
-full set, and all three repeats of every row gave the identical count:
-
-| Options | Default budget | `max_len=1024, head_max_len=512` |
-|---|---|---|
-| 24 | 24/24 | 20/24 |
-| 48 | 1/48 | 43/48 |
-| 72 | 1/72 | 63/72 |
-
-Both directions of that table matter. Past about 40 options the default budget collapses the
-decision, and widening it recovers most of it. Below that, widening it costs a few: at 24 options
-the labels already fit the default budget and four answers move. The docs do not claim to know why
-the wider collation changes those four -- it is enough that it can. That is why the two arguments
-are opt-in per node: set the knob to fix a question that does not fit, not to sharpen one that does.
-
-The same override applies to `LayaGuardrail`, `LayaTriage` and `LayaEvaluator`.
-It is per node, so a chain can give its wide routing step room while every other node keeps the
-checkpoint's defaults, which is the point of not raising `agent.cfg["head_max_len"]` process-wide.
-
-**Remote mode rejects it.** A budget override is applied by the local runner, and `laya-serve`
-neither accepts nor needs the field, so `max_len` or `head_max_len` on a node with a `base_url`
-raises `ValueError` instead of quietly doing nothing. Raise the budget on the server that runs
-inference.
# LangChain & LangGraph Integration
Laya provides fast, non-autoregressive decision components for **LangChain** and **LangGraph** (single-question latency measured at **32.8 ms** with `laya-multilingual` and **39.5 ms** with `laya` on a Tesla T4 GPU; 193–464 ms on CPU):
@@ -60,64 +10,6 @@ Laya provides fast, non-autoregressive decision components for **LangChain** and
Every node also takes core's five per-call prediction-hook arguments (`hooks`, `on_predict_start`, `on_predict_end`, `hooks_raise`, `hooks_timeout`).
----
-
-## 5. Prediction Hooks on a Single Node
-
-Every runnable takes the five per-call hook arguments the core API takes -- `hooks`,
-`on_predict_start`, `on_predict_end`, `hooks_raise`, `hooks_timeout` -- so the caching, audit and
-gating patterns from [Prediction hooks](hooks/index.md) can be attached to one node in a graph
-instead of to the whole agent. See [Patterns and anti-patterns](hooks/patterns.md) for the cache
-pair this is built around.
-
-```python
-from laya.integrations.langchain import LayaRouter
-
-class Memo:
- def __init__(self):
- self.cache = {}
-
- def on_predict_start(self, ctx):
- hit = self.cache.get(str(ctx.states[0]))
- if hit is not None:
- ctx.skip([hit]) # the forward pass is skipped; end hooks still run
-
- def on_predict_end(self, ctx):
- if ctx.results:
- self.cache[str(ctx.states[0])] = ctx.results[0]
-
-
-router = LayaRouter(
- criteria={"billing": "invoices, charges, refunds", "technical": "bugs, errors, outage"},
- hooks=[Memo()],
- hooks_timeout=0.25,
-)
-```
-
-Leave an argument out and it is not sent at all, so the node keeps whatever the runner was built
-with. `hooks=[]` and `hooks_raise=False` are decisions rather than absences and are forwarded as
-given: the first means "no hooks for this call" even on an agent that has some, the second means
-"keep deciding after a hook fails". Both belong to [the error contract in hooks/errors.md](hooks/errors.md).
-
-**What it buys.** On `laya` (Apple silicon) a 24-state pass over 4 distinct tickets, median of 3
-runs, scored on the returned route label:
-
-| Node | Forward passes | Wall clock |
-|---|---|---|
-| no hooks | 24 | 2109 ms |
-| `hooks=[Memo(), Counter()]`, cold cache | 4 | 330 ms |
-| `hooks=[Memo(), Counter()]`, warm cache | 0 | 0.3 ms |
-
-All 24 routes were identical to the hook-free node's. The cold run is 4 forwards rather than 24
-because the distinct tickets are the only ones that can miss; a warm cache answers the whole pass
-from memory, which is the point of the pattern and not a speedup of the model. The same pair wired
-through `on_predict_start=`/`on_predict_end=` instead of `hooks=` measured 359 ms cold.
-
-**Remote mode refuses them.** A hook is a Python callable that runs inside `predict`, and
-`laya-serve` has no way to receive or run one, so a node with a `base_url` and any of the five set
-raises `ValueError` naming the arguments rather than reporting success for a cache that never ran.
-Install hooks on the process that runs inference.
-
Supports both **local in-process inference** (`Agent` or `Router`) and **remote HTTP inference** against your own `laya-serve` without requiring PyTorch on edge clients.
---
@@ -409,3 +301,110 @@ guard `LayaGuardrail`: 4173 ms vs **2329 ms** (**1.8x**). Route labels and guard
identical to the one-by-one loop in every run (0/16 and 0/24 changes). On CPU the same workloads are
2.2x to 2.4x over the one-by-one loop, but only 1.1x to 1.5x over the thread pool, which already
overlaps cores -- the MPS case is where `batch()` was not just slower but unusable.
+
+---
+
+## 7. Widening the Token Budget for Many Options
+
+Every runnable takes `max_len` and `head_max_len`, the two per-request knobs the core API accepts.
+A choice question's options share the checkpoint's *option* budget -- `head_max_len`, 192 tokens on
+`laya` and 256 on `laya-multilingual` -- and each option carries its own description, so past
+roughly 20 options every label is trimmed to fit and similar labels start reaching the model as the
+same text. See the README's [Honest limits](https://github.com/NandhaKishorM/laya#honest-limits)
+for the same effect measured on Banking77.
+
+Two situations call for it. A routing node with many branches overflows the *option* budget, and
+a long document overflows the *state* budget -- the README's own long-document guidance is literally
+`router.predict(long_document, questions, model="multilingual", max_len=8192)`, which until now was
+unspeakable from a chain step. Both go through the same two arguments:
+
+```python
+router = LayaRouter(
+ criteria=queue_criteria, # 48 queues, each with a description
+ instructions="Which support queue owns this ticket?",
+ max_len=1024, # total window
+ head_max_len=512, # tokens shared by the option prompt
+)
+```
+
+Measured on `laya` (Apple silicon, one forward pass per state, scored on the chosen label) with
+queue labels a state names explicitly, so ground truth is exact. Each cell is the count over the
+full set, and all three repeats of every row gave the identical count:
+
+| Options | Default budget | `max_len=1024, head_max_len=512` |
+|---|---|---|
+| 24 | 24/24 | 20/24 |
+| 48 | 1/48 | 43/48 |
+| 72 | 1/72 | 63/72 |
+
+Both directions of that table matter. Past about 40 options the default budget collapses the
+decision, and widening it recovers most of it. Below that, widening it costs a few: at 24 options
+the labels already fit the default budget and four answers move. The docs do not claim to know why
+the wider collation changes those four -- it is enough that it can. That is why the two arguments
+are opt-in per node: set the knob to fix a question that does not fit, not to sharpen one that does.
+
+The same override applies to `LayaGuardrail`, `LayaTriage` and `LayaEvaluator`.
+It is per node, so a chain can give its wide routing step room while every other node keeps the
+checkpoint's defaults, which is the point of not raising `agent.cfg["head_max_len"]` process-wide.
+
+**Remote mode forwards it.** A node with a `base_url` sends `max_len` / `head_max_len` in the
+request body, and `laya-serve` applies them up to its `LAYA_MAX_TOKEN_BUDGET` ceiling (8192 by
+default); a larger value comes back as a 422.
+
+---
+
+## 8. Prediction Hooks on a Single Node
+
+Every runnable takes the five per-call hook arguments the core API takes -- `hooks`,
+`on_predict_start`, `on_predict_end`, `hooks_raise`, `hooks_timeout` -- so the caching, audit and
+gating patterns from [Prediction hooks](hooks/index.md) can be attached to one node in a graph
+instead of to the whole agent. See [Patterns and anti-patterns](hooks/patterns.md) for the cache
+pair this is built around.
+
+```python
+from laya.integrations.langchain import LayaRouter
+
+class Memo:
+ def __init__(self):
+ self.cache = {}
+
+ def on_predict_start(self, ctx):
+ hit = self.cache.get(str(ctx.states[0]))
+ if hit is not None:
+ ctx.skip([hit]) # the forward pass is skipped; end hooks still run
+
+ def on_predict_end(self, ctx):
+ if ctx.results:
+ self.cache[str(ctx.states[0])] = ctx.results[0]
+
+
+router = LayaRouter(
+ criteria={"billing": "invoices, charges, refunds", "technical": "bugs, errors, outage"},
+ hooks=[Memo()],
+ hooks_timeout=0.25,
+)
+```
+
+Leave an argument out and it is not sent at all, so the node keeps whatever the runner was built
+with. `hooks=[]` and `hooks_raise=False` are decisions rather than absences and are forwarded as
+given: the first means "no hooks for this call" even on an agent that has some, the second means
+"keep deciding after a hook fails". Both belong to [the error contract in hooks/errors.md](hooks/errors.md).
+
+**What it buys.** On `laya` (Apple silicon) a 24-state pass over 4 distinct tickets, median of 3
+runs, scored on the returned route label:
+
+| Node | Forward passes | Wall clock |
+|---|---|---|
+| no hooks | 24 | 2109 ms |
+| `hooks=[Memo(), Counter()]`, cold cache | 4 | 330 ms |
+| `hooks=[Memo(), Counter()]`, warm cache | 0 | 0.3 ms |
+
+All 24 routes were identical to the hook-free node's. The cold run is 4 forwards rather than 24
+because the distinct tickets are the only ones that can miss; a warm cache answers the whole pass
+from memory, which is the point of the pattern and not a speedup of the model. The same pair wired
+through `on_predict_start=`/`on_predict_end=` instead of `hooks=` measured 359 ms cold.
+
+**Remote mode refuses them.** A hook is a Python callable that runs inside `predict`, and
+`laya-serve` has no way to receive or run one, so a node with a `base_url` and any of the five set
+raises `ValueError` naming the arguments rather than reporting success for a cache that never ran.
+Install hooks on the process that runs inference.
diff --git a/laya/integrations/langchain.py b/laya/integrations/langchain.py
index 390ff4b5..9285f04d 100644
--- a/laya/integrations/langchain.py
+++ b/laya/integrations/langchain.py
@@ -105,8 +105,14 @@ def _call_remote(
api_key: Optional[str] = None,
model: Optional[str] = None,
timeout: float = 10.0,
+ max_len: Optional[int] = None,
+ head_max_len: Optional[int] = None,
) -> Dict[str, Any]:
- """Send decision request to a remote laya-serve HTTP instance using standard library urllib."""
+ """Send decision request to a remote laya-serve HTTP instance using standard library urllib.
+
+ `max_len` / `head_max_len` travel in the body; laya-serve applies them up to its
+ `LAYA_MAX_TOKEN_BUDGET` ceiling and answers a larger value with 422.
+ """
url = base_url.rstrip("/")
if not url.endswith("/v1/systemone"):
url = f"{url}/v1/systemone"
@@ -114,6 +120,10 @@ def _call_remote(
payload: Dict[str, Any] = {"state": state, "questions": questions}
if model:
payload["model"] = model
+ if max_len is not None:
+ payload["max_len"] = max_len
+ if head_max_len is not None:
+ payload["head_max_len"] = head_max_len
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
@@ -146,22 +156,6 @@ def _get_default_router():
return _DEFAULT_ROUTER
-def _reject_remote_budget(max_len: Optional[int], head_max_len: Optional[int],
- base_url: Optional[str]) -> None:
- """Refuse a budget override on a remote node rather than dropping it silently.
-
- `laya-serve` has no budget field of its own -- it answers within the checkpoint's defaults and
- rejects an oversized question with 413. The budget decides how many tokens each option gets, so
- ignoring it can change the label the model returns; a caller must not be told it applied when
- it could not.
- """
- if base_url and (max_len is not None or head_max_len is not None):
- raise ValueError(
- "max_len/head_max_len are applied by the local runner and cannot be sent to a "
- "laya-serve endpoint; raise the budget where serve runs, or drop the override"
- )
-
-
def _predict_kwargs(model: Optional[str] = None, max_len: Optional[int] = None,
head_max_len: Optional[int] = None) -> Dict[str, Any]:
"""The per-request overrides a local runner accepts, with the unset ones omitted."""
@@ -221,9 +215,11 @@ def _execute_decision(
) -> Dict[str, Any]:
hook_kwargs = _hook_kwargs(hooks, on_predict_start, on_predict_end, hooks_raise, hooks_timeout)
if base_url:
- _reject_remote_budget(max_len, head_max_len, base_url)
_reject_remote_hooks(hook_kwargs, base_url)
- return _call_remote(base_url, state, questions, api_key=api_key, model=model)
+ # Only what was set, so a stand-in `_call_remote` without the budget keywords still works.
+ budget = {k: v for k, v in (("max_len", max_len), ("head_max_len", head_max_len))
+ if v is not None}
+ return _call_remote(base_url, state, questions, api_key=api_key, model=model, **budget)
runner = agent if agent is not None else _get_default_router()
kwargs = _predict_kwargs(model, max_len, head_max_len)
kwargs.update(hook_kwargs)
diff --git a/tests/test_langchain.py b/tests/test_langchain.py
index 2083c234..45bf3e51 100644
--- a/tests/test_langchain.py
+++ b/tests/test_langchain.py
@@ -4,6 +4,7 @@ Tests verify routing logic, confidence threshold fallback gating, guardrail filt
state extraction, schema-driven decisions, and LangGraph callable conventions without requiring
model downloads or GPU.
"""
+import json
import os
import sys
@@ -815,13 +816,14 @@ for name, build in BUDGET_NODES:
{"model": "laya-multilingual", "head_max_len": 256})
-# `laya-serve` has no budget field, so a remote node must refuse rather than drop the override.
+# `laya-serve` accepts `max_len` / `head_max_len` (#566), so a remote node forwards the override
+# in the request body instead of dropping it.
budget_remote_calls = []
_budget_real_call_remote = langchain_module._call_remote
-def budget_spy_call_remote(base_url, state, questions, api_key=None, model=None):
- budget_remote_calls.append({"model": model})
+def budget_spy_call_remote(base_url, state, questions, api_key=None, model=None, **budget):
+ budget_remote_calls.append(dict({"model": model}, **budget))
return {"answers": {"route": {"type": "choice", "choice": "billing", "confidence": 0.9}}}
@@ -833,18 +835,45 @@ try:
check("budget/remote still sends model", budget_remote_calls[-1], {"model": None})
for field in ("max_len", "head_max_len"):
- raised, message = False, ""
- try:
- LayaRouter(BUDGET_CRITERIA, base_url="http://laya:8000", **{field: 512}).invoke("x")
- except ValueError as e:
- raised, message = True, str(e)
- check_true("budget/remote refuses %s" % field, raised)
- check_true("budget/remote %s names the endpoint" % field, "laya-serve" in message)
-
- check("budget/remote made no extra call", len(budget_remote_calls), 1)
+ LayaRouter(BUDGET_CRITERIA, base_url="http://laya:8000", **{field: 512}).invoke("x")
+ check("budget/remote forwards %s" % field, budget_remote_calls[-1],
+ {"model": None, field: 512})
finally:
langchain_module._call_remote = _budget_real_call_remote
+# ...and the real `_call_remote` puts them in the JSON body.
+_sent = {}
+
+
+class _FakeResponse:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def read(self):
+ return b'{"answers": {}}'
+
+
+class _FakeOpener:
+ def open(self, req, timeout=None):
+ _sent["body"] = json.loads(req.data.decode("utf-8"))
+ return _FakeResponse()
+
+
+_real_build_opener = langchain_module.urllib.request.build_opener
+langchain_module.urllib.request.build_opener = lambda *a, **k: _FakeOpener()
+try:
+ langchain_module._call_remote("http://laya:8000", "x", {}, max_len=1024, head_max_len=384)
+ check("budget/_call_remote sends max_len", _sent["body"].get("max_len"), 1024)
+ check("budget/_call_remote sends head_max_len", _sent["body"].get("head_max_len"), 384)
+ langchain_module._call_remote("http://laya:8000", "x", {})
+ check_true("budget/_call_remote omits an unset budget",
+ "max_len" not in _sent["body"] and "head_max_len" not in _sent["body"])
+finally:
+ langchain_module.urllib.request.build_opener = _real_build_opener
+
# --------------------------------------------------------------- 7. Prediction hooks
from laya.integrations import langchain as langchain_module # noqa: E402