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(integrations): forward the two Router-only controls task and lang_guess

Aashish13d5d537c038
diff --git a/laya/integrations/_controls.py b/laya/integrations/_controls.py
index 5731fbe3..f1acb539 100644
--- a/laya/integrations/_controls.py
+++ b/laya/integrations/_controls.py
@@ -5,14 +5,19 @@ Every integration wrapper ends at one of two places: a local `runner.predict(sta
rule, and three independent copies of it drift -- this module is the copy the LangChain, CrewAI
and LlamaIndex wrappers import.
-The names are listed once, in `PREDICT_CONTROLS` and `HOOK_CONTROLS`, and the signatures below
-are checked against them by `tests/test_langchain.py`, `tests/test_crewai.py` and
-`tests/test_llamaindex.py`, which also assert every wrapper's constructor accepts all of them. A
-control added here without reaching a wrapper's `__init__` fails that wrapper's suite rather than
-being dropped silently.
+The names are listed once, in `PREDICT_CONTROLS`, `HOOK_CONTROLS`, `DECISION_CONTROLS` and
+`ROUTER_ONLY_CONTROLS`, and the signatures below are checked against them by
+`tests/test_langchain.py`, `tests/test_crewai.py` and `tests/test_llamaindex.py`, which also assert
+every wrapper's constructor accepts all of them. A control added here without reaching a wrapper's
+`__init__` fails that wrapper's suite rather than being dropped silently.
+
+The last list is the one that needs a rule rather than a splat: two of these controls are read by a
+`Router` and by no `Agent`, and a wrapper's runner can be either, so `require_router_controls` asks
+the signature of the call about to be made.
"""
from __future__ import annotations
+import inspect
from typing import Any, Dict, Optional
# The token-budget overrides `Agent.predict` / `Router.predict` take per call, and that
@@ -31,6 +36,13 @@ DECISION_CONTROLS = ("lang", "min_confidence")
# they exist only on the local path -- see `reject_remote_hooks`.
HOOK_CONTROLS = ("hooks", "on_predict_start", "on_predict_end", "hooks_raise", "hooks_timeout")
+# The routing hints. `Router.route` reads both -- `task` names the checkpoint that answers, the way
+# `model` does, and `lang_guess` decides English vs multilingual before core's own script detection
+# runs -- and `Agent.predict` reads neither, because an Agent has no routing step: it answers on the
+# checkpoint it was built with. So these two go to a runner that reads them and are refused by name
+# at one that does not -- see `require_router_controls`.
+ROUTER_ONLY_CONTROLS = ("task", "lang_guess")
+
def budget_kwargs(max_len: Optional[int] = None,
head_max_len: Optional[int] = None) -> Dict[str, Any]:
@@ -97,3 +109,76 @@ def reject_remote_hooks(given: Dict[str, Any], base_url: Optional[str]) -> None:
"%s run in the local runner and cannot be sent to a laya-serve endpoint; "
"install them where serve runs, or drop them" % ", ".join(sorted(given))
)
+
+
+def router_kwargs(task: Optional[str] = None, lang_guess: Optional[Any] = None) -> Dict[str, Any]:
+ """The routing hints, with the unset ones omitted.
+
+ Absent rather than `None`, for the same reason as the budgets: `Router(task=...)` and
+ `Router(lang_guess=...)` are hints a deployment installs for every request, and an explicit
+ `None` here would replace the deployment's own hint with nothing for this one call. A blank
+ `lang_guess` is core's documented "no usable hint, fall through to detection", so it is
+ forwarded rather than treated as an absence.
+ """
+ return {key: value for key, value in (("task", task), ("lang_guess", lang_guess))
+ if value is not None}
+
+
+def _reads(target: Any, name: str) -> bool:
+ """Whether the entry point about to be called can read `name` as a keyword argument."""
+ try:
+ params = inspect.signature(target).parameters
+ except (TypeError, ValueError):
+ # Not introspectable (a C callable, a class with a hand-written __call__ signature): let
+ # core decide. Refusing a call on a guess would block a runner this module cannot see.
+ return True
+ if any(p.kind is p.VAR_KEYWORD for p in params.values()):
+ return True
+ return name in params
+
+
+def require_router_controls(runner: Any, entry_point: str, given: Dict[str, Any]) -> Dict[str, Any]:
+ """Return `given` when the runner's entry point reads it, else raise naming what it does not.
+
+ `task` and `lang_guess` route, and only a Router routes -- `Agent` takes neither, and its two
+ batch entry points do not either. Forwarding them anyway is a `TypeError` from inside core on
+ the way to the answer, and dropping them quietly is the silence this module exists to break: the
+ caller asked for the typed-decisions checkpoint or for German text to be read as German, and got
+ the deployment's defaults instead.
+
+ Read from the signature of the call about to be made (`entry_point`) rather than from a list of
+ runner classes, because `predict`, `predict_batch` and a stand-in each accept a different set,
+ and a wrapper declared `**kwargs` takes everything. A runner with no such method at all -- a
+ duck-typed stand-in that routes somewhere else -- is not refused either: this cannot tell, and
+ guessing wrong would block a call that works.
+ """
+ if not given:
+ return {}
+ target = getattr(runner, entry_point, None)
+ unread = [name for name in ROUTER_ONLY_CONTROLS if name in given and not _reads(target, name)]
+ if unread:
+ raise ValueError(
+ "%s %s a routing hint, and %s.%s does not read it: this runner answers on the checkpoint "
+ "it was built with. Pass a Router as `agent=`, or drop %s."
+ % (", ".join(unread), "is" if len(unread) == 1 else "are",
+ type(runner).__name__, entry_point,
+ "it" if len(unread) == 1 else "them")
+ )
+ return given
+
+
+def reject_remote_lang_guess(given: Dict[str, Any], base_url: Optional[str]) -> None:
+ """Refuse a non-string `lang_guess` on a remote node rather than sending a body serve rejects.
+
+ `Router` reads `lang_guess` as a language code *or* as a callable taking the state, and only the
+ code has a wire form: `laya-serve` validates it as a string and answers 422 to anything else, so
+ a callable would fail as an HTTP status after the request went out. Naming the argument here
+ says what to do instead -- install the callable on the Router where serve runs, or pass a code.
+ """
+ value = given.get("lang_guess")
+ if base_url and value is not None and not isinstance(value, str):
+ raise ValueError(
+ "lang_guess=%r cannot be sent to a laya-serve endpoint: only a language code string "
+ "such as \"de\" crosses HTTP. Install the callable on the Router where serve runs, or "
+ "pass a code" % (value,)
+ )
diff --git a/laya/integrations/crewai.py b/laya/integrations/crewai.py
index 4d045e54..73ac94b8 100644
--- a/laya/integrations/crewai.py
+++ b/laya/integrations/crewai.py
@@ -59,6 +59,9 @@ from ._controls import decision_kwargs as _decision_kwargs # noqa: E402
from ._controls import predict_kwargs as _predict_kwargs, reject_remote_hooks as _reject_remote_hooks # noqa: E402
from ._guard import score_violation_probability as _score_violation_probability # noqa: E402
from ..confidence import _gate_confidence # noqa: E402
+from ._controls import reject_remote_lang_guess as _reject_remote_lang_guess # noqa: E402
+from ._controls import require_router_controls as _require_router_controls # noqa: E402
+from ._controls import router_kwargs as _router_kwargs # noqa: E402
# One class for every integration, so `except LayaLowConfidenceError` catches all of them.
from ._errors import LayaLowConfidenceError # noqa: E402
@@ -151,13 +154,18 @@ def _call_remote(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[str] = None,
) -> Dict[str, Any]:
"""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. `lang` / `min_confidence`
ride in the same body (they are laya-serve `BODY_CONTROLS` too): the language codes the state
- is routed and answered in, and core's abstention gate.
+ is routed and answered in, and core's abstention gate. `task` names the checkpoint that answers
+ and `lang_guess` is the language code routing reads before its own detection -- both are
+ laya-serve body controls too, and only `lang_guess`'s string form has a wire representation
+ (`reject_remote_lang_guess` refuses the callable before the request).
"""
url = base_url.rstrip("/")
if not url.endswith("/v1/systemone"):
@@ -174,6 +182,10 @@ def _call_remote(
payload["lang"] = lang
if min_confidence is not None:
payload["min_confidence"] = min_confidence
+ if task is not None:
+ payload["task"] = task
+ if lang_guess is not None:
+ payload["lang_guess"] = lang_guess
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
@@ -217,6 +229,8 @@ def _execute_decision(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -229,14 +243,17 @@ def _execute_decision(
LlamaIndex wrappers -- they end at the same `predict` call and the same request body.
"""
hook_kwargs = _hook_kwargs(hooks, on_predict_start, on_predict_end, hooks_raise, hooks_timeout)
+ router_kwargs = _router_kwargs(task, lang_guess)
if base_url:
_reject_remote_hooks(hook_kwargs, base_url)
+ _reject_remote_lang_guess(router_kwargs, base_url)
budget = _budget_kwargs(max_len, head_max_len)
decision = _decision_kwargs(lang, min_confidence)
return _call_remote(base_url, state, questions, api_key=api_key, model=model,
- **budget, **decision)
+ **budget, **decision, **router_kwargs)
runner = agent if agent is not None else _get_default_router()
kwargs = _predict_kwargs(model, max_len, head_max_len, lang, min_confidence)
+ kwargs.update(_require_router_controls(runner, "predict", router_kwargs))
kwargs.update(hook_kwargs)
return runner.predict(state, questions, **kwargs)
@@ -262,6 +279,8 @@ class LayaCrewRouter:
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -280,6 +299,8 @@ class LayaCrewRouter:
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -318,6 +339,10 @@ class LayaCrewRouter:
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ # `task` here is core's checkpoint selector, not the CrewAI task being decided on --
+ # `task_str` above is that one. Both are on this call, and only one routes.
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -443,6 +468,8 @@ class LayaTaskGuard:
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -463,6 +490,8 @@ class LayaTaskGuard:
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -490,6 +519,10 @@ class LayaTaskGuard:
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ # `task` here is core's checkpoint selector, not the CrewAI task being decided on --
+ # `task_str` above is that one. Both are on this call, and only one routes.
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
diff --git a/laya/integrations/langchain.py b/laya/integrations/langchain.py
index 5d7bbadd..ddbe9430 100644
--- a/laya/integrations/langchain.py
+++ b/laya/integrations/langchain.py
@@ -34,6 +34,8 @@ from ._controls import budget_kwargs as _budget_kwargs, hook_kwargs as _hook_kwa
from ._controls import decision_kwargs as _decision_kwargs
from ._controls import predict_kwargs as _predict_kwargs
from ._controls import reject_remote_hooks as _reject_remote_hooks
+from ._controls import reject_remote_lang_guess as _reject_remote_lang_guess
+from ._controls import require_router_controls as _require_router_controls, router_kwargs as _router_kwargs
from ._guard import score_violation_probability as _score_violation_probability
@@ -162,13 +164,18 @@ def _call_remote(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[str] = None,
) -> Dict[str, Any]:
"""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. `lang` / `min_confidence`
ride in the same body (they are laya-serve `BODY_CONTROLS` too): the language codes the state
- for routing and calibration, and the abstention gate flags a low-confidence answer.
+ for routing and calibration, and the abstention gate flags a low-confidence answer. `task` names
+ the checkpoint that answers and `lang_guess` is the language code routing reads before its own
+ detection -- both are laya-serve body controls too, and only `lang_guess`'s string form has a
+ wire representation (`reject_remote_lang_guess` refuses the callable before the request).
"""
url = base_url.rstrip("/")
if not url.endswith("/v1/systemone"):
@@ -185,6 +192,10 @@ def _call_remote(
payload["lang"] = lang
if min_confidence is not None:
payload["min_confidence"] = min_confidence
+ if task is not None:
+ payload["task"] = task
+ if lang_guess is not None:
+ payload["lang_guess"] = lang_guess
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
@@ -228,6 +239,8 @@ def _execute_decision(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -235,14 +248,17 @@ def _execute_decision(
hooks_timeout: Optional[float] = None,
) -> Dict[str, Any]:
hook_kwargs = _hook_kwargs(hooks, on_predict_start, on_predict_end, hooks_raise, hooks_timeout)
+ router_kwargs = _router_kwargs(task, lang_guess)
if base_url:
_reject_remote_hooks(hook_kwargs, base_url)
+ _reject_remote_lang_guess(router_kwargs, base_url)
budget = _budget_kwargs(max_len, head_max_len)
decision = _decision_kwargs(lang, min_confidence)
return _call_remote(base_url, state, questions, api_key=api_key, model=model,
- **budget, **decision)
+ **budget, **decision, **router_kwargs)
runner = agent if agent is not None else _get_default_router()
kwargs = _predict_kwargs(model, max_len, head_max_len, lang, min_confidence)
+ kwargs.update(_require_router_controls(runner, "predict", router_kwargs))
kwargs.update(hook_kwargs)
return runner.predict(state, questions, **kwargs)
@@ -274,6 +290,8 @@ def _execute_batch(
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
hook_kwargs: Optional[Dict[str, Any]] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
) -> List[Dict[str, Any]]:
"""Evaluate one question set over many states, packing them into shared forward passes.
@@ -281,18 +299,24 @@ def _execute_batch(
and `Router` disagree about how `predict_batch` is called (states plus one question
set, versus one request dict each), so both forms are built here. The token budget,
`lang` and `min_confidence` ride the same way they do on `_execute_decision`, so
- `.batch()` answers identically to `.invoke()` instead of silently dropping them.
+ `.batch()` answers identically to `.invoke()` instead of silently dropping them --
+ and so do the two routing hints, which a Router lifts off each request dict.
"""
runner = agent if agent is not None else _get_default_router()
+ router_kwargs = _router_kwargs(task, lang_guess)
if hasattr(runner, "route_batch"):
# Router: `lang` is a per-request control it lifts off each item, `min_confidence` is a
# call-level argument -- the same split laya-serve's batch endpoint makes between
- # BATCH_BODY_ITEM_CONTROLS and BATCH_BODY_CALL_CONTROLS.
+ # BATCH_BODY_ITEM_CONTROLS and BATCH_BODY_CALL_CONTROLS. `task` and `lang_guess` are
+ # per-request as well, which is why they are checked against `route`, the signature
+ # that reads them, rather than against `predict_batch`.
item_overrides = _predict_kwargs(model, max_len, head_max_len, lang)
+ item_overrides.update(_require_router_controls(runner, "route", router_kwargs))
requests = [dict({"state": state, "questions": questions}, **item_overrides) for state in states]
return runner.predict_batch(requests, **_decision_kwargs(None, min_confidence))
# Agent: `lang` and `min_confidence` are both call-level keyword arguments of `predict_batch`.
overrides = _predict_kwargs(model, max_len, head_max_len, lang, min_confidence)
+ overrides.update(_require_router_controls(runner, "predict_batch", router_kwargs))
return runner.predict_batch(list(states), questions, **overrides, **(hook_kwargs or {}))
@@ -362,6 +386,7 @@ class _BatchedRunnable:
states, self._questions(), agent=self.agent, model=self.model,
max_len=self.max_len, head_max_len=self.head_max_len,
lang=getattr(self, "lang", None), min_confidence=getattr(self, "min_confidence", None),
+ task=self.task, lang_guess=self.lang_guess,
hook_kwargs=hook_kwargs,
)
return [self._finish(result, item) for result, item in zip(results, inputs)]
@@ -408,6 +433,8 @@ class LayaRouter(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None
lang: Optional[str] = None
min_confidence: Optional[float] = None
+ task: Optional[str] = None
+ lang_guess: Optional[Any] = None
hooks: Optional[Any] = None
on_predict_start: Optional[Any] = None
on_predict_end: Optional[Any] = None
@@ -435,6 +462,8 @@ class LayaRouter(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -457,6 +486,8 @@ class LayaRouter(_BatchedRunnable, RunnableSerializable):
head_max_len=head_max_len,
lang=lang,
min_confidence=min_confidence,
+ task=task,
+ lang_guess=lang_guess,
hooks=hooks,
on_predict_start=on_predict_start,
on_predict_end=on_predict_end,
@@ -478,6 +509,8 @@ class LayaRouter(_BatchedRunnable, RunnableSerializable):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -527,6 +560,8 @@ class LayaRouter(_BatchedRunnable, RunnableSerializable):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -568,6 +603,8 @@ class LayaGuardrail(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None
lang: Optional[str] = None
min_confidence: Optional[float] = None
+ task: Optional[str] = None
+ lang_guess: Optional[Any] = None
hooks: Optional[Any] = None
on_predict_start: Optional[Any] = None
on_predict_end: Optional[Any] = None
@@ -593,6 +630,8 @@ class LayaGuardrail(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -617,6 +656,8 @@ class LayaGuardrail(_BatchedRunnable, RunnableSerializable):
head_max_len=head_max_len,
lang=lang,
min_confidence=min_confidence,
+ task=task,
+ lang_guess=lang_guess,
hooks=hooks,
on_predict_start=on_predict_start,
on_predict_end=on_predict_end,
@@ -638,6 +679,8 @@ class LayaGuardrail(_BatchedRunnable, RunnableSerializable):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -726,6 +769,8 @@ class LayaGuardrail(_BatchedRunnable, RunnableSerializable):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -755,6 +800,8 @@ class LayaTriage(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None
lang: Optional[str] = None
min_confidence: Optional[float] = None
+ task: Optional[str] = None
+ lang_guess: Optional[Any] = None
hooks: Optional[Any] = None
on_predict_start: Optional[Any] = None
on_predict_end: Optional[Any] = None
@@ -776,6 +823,8 @@ class LayaTriage(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -794,6 +843,8 @@ class LayaTriage(_BatchedRunnable, RunnableSerializable):
head_max_len=head_max_len,
lang=lang,
min_confidence=min_confidence,
+ task=task,
+ lang_guess=lang_guess,
hooks=hooks,
on_predict_start=on_predict_start,
on_predict_end=on_predict_end,
@@ -811,6 +862,8 @@ class LayaTriage(_BatchedRunnable, RunnableSerializable):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -856,6 +909,8 @@ class LayaTriage(_BatchedRunnable, RunnableSerializable):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -885,6 +940,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None
lang: Optional[str] = None
min_confidence: Optional[float] = None
+ task: Optional[str] = None
+ lang_guess: Optional[Any] = None
hooks: Optional[Any] = None
on_predict_start: Optional[Any] = None
on_predict_end: Optional[Any] = None
@@ -907,6 +964,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -926,6 +985,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
head_max_len=head_max_len,
lang=lang,
min_confidence=min_confidence,
+ task=task,
+ lang_guess=lang_guess,
hooks=hooks,
on_predict_start=on_predict_start,
on_predict_end=on_predict_end,
@@ -944,6 +1005,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -964,6 +1027,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -991,6 +1056,8 @@ class LayaEvaluator(_BatchedRunnable, RunnableSerializable):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
diff --git a/laya/integrations/llamaindex.py b/laya/integrations/llamaindex.py
index dd017199..de423407 100644
--- a/laya/integrations/llamaindex.py
+++ b/laya/integrations/llamaindex.py
@@ -66,6 +66,9 @@ except ImportError:
from ._controls import budget_kwargs as _budget_kwargs, hook_kwargs as _hook_kwargs # noqa: E402
from ._controls import decision_kwargs as _decision_kwargs # noqa: E402
from ._controls import predict_kwargs as _predict_kwargs, reject_remote_hooks as _reject_remote_hooks # noqa: E402
+from ._controls import reject_remote_lang_guess as _reject_remote_lang_guess # noqa: E402
+from ._controls import require_router_controls as _require_router_controls # noqa: E402
+from ._controls import router_kwargs as _router_kwargs # noqa: E402
# One class for every integration, so `except LayaLowConfidenceError` catches all of them.
from ._errors import LayaLowConfidenceError # noqa: E402
@@ -147,13 +150,18 @@ def _call_remote(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[str] = None,
) -> Dict[str, Any]:
"""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. `lang` / `min_confidence`
ride in the same body (they are laya-serve `BODY_CONTROLS` too): the language codes the state
- is routed and answered in, and core's abstention gate.
+ is routed and answered in, and core's abstention gate. `task` names the checkpoint that answers
+ and `lang_guess` is the language code routing reads before its own detection -- both are
+ laya-serve body controls too, and only `lang_guess`'s string form has a wire representation
+ (`reject_remote_lang_guess` refuses the callable before the request).
"""
url = base_url.rstrip("/")
if not url.endswith("/v1/systemone"):
@@ -170,6 +178,10 @@ def _call_remote(
payload["lang"] = lang
if min_confidence is not None:
payload["min_confidence"] = min_confidence
+ if task is not None:
+ payload["task"] = task
+ if lang_guess is not None:
+ payload["lang_guess"] = lang_guess
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
@@ -213,6 +225,8 @@ def _execute_decision(
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -225,14 +239,17 @@ def _execute_decision(
CrewAI wrappers -- they end at the same `predict` call and the same request body.
"""
hook_kwargs = _hook_kwargs(hooks, on_predict_start, on_predict_end, hooks_raise, hooks_timeout)
+ router_kwargs = _router_kwargs(task, lang_guess)
if base_url:
_reject_remote_hooks(hook_kwargs, base_url)
+ _reject_remote_lang_guess(router_kwargs, base_url)
budget = _budget_kwargs(max_len, head_max_len)
decision = _decision_kwargs(lang, min_confidence)
return _call_remote(base_url, state, questions, api_key=api_key, model=model,
- **budget, **decision)
+ **budget, **decision, **router_kwargs)
runner = agent if agent is not None else _get_default_router()
kwargs = _predict_kwargs(model, max_len, head_max_len, lang, min_confidence)
+ kwargs.update(_require_router_controls(runner, "predict", router_kwargs))
kwargs.update(hook_kwargs)
return runner.predict(state, questions, **kwargs)
@@ -259,6 +276,8 @@ class LayaSingleSelector(BaseSelector):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -277,6 +296,8 @@ class LayaSingleSelector(BaseSelector):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -315,6 +336,8 @@ class LayaSingleSelector(BaseSelector):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -405,6 +428,8 @@ class LayaMultiSelector(BaseSelector):
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -423,6 +448,8 @@ class LayaMultiSelector(BaseSelector):
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -460,6 +487,8 @@ class LayaMultiSelector(BaseSelector):
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,
@@ -560,6 +589,8 @@ class LayaQueryRouter:
head_max_len: Optional[int] = None,
lang: Optional[str] = None,
min_confidence: Optional[float] = None,
+ task: Optional[str] = None,
+ lang_guess: Optional[Any] = None,
hooks: Optional[Any] = None,
on_predict_start: Optional[Any] = None,
on_predict_end: Optional[Any] = None,
@@ -579,6 +610,8 @@ class LayaQueryRouter:
self.head_max_len = head_max_len
self.lang = lang
self.min_confidence = min_confidence
+ self.task = task
+ self.lang_guess = lang_guess
self.hooks = hooks
self.on_predict_start = on_predict_start
self.on_predict_end = on_predict_end
@@ -613,6 +646,8 @@ class LayaQueryRouter:
head_max_len=self.head_max_len,
lang=self.lang,
min_confidence=self.min_confidence,
+ task=self.task,
+ lang_guess=self.lang_guess,
hooks=self.hooks,
on_predict_start=self.on_predict_start,
on_predict_end=self.on_predict_end,