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(serve): add batch decision endpoint (/v1/systemone/batch)

Siradj Mounir Lamri3ae9a33b1abb
diff --git a/README.md b/README.md
index 4aadb0c4..9367a88a 100644
--- a/README.md
+++ b/README.md
@@ -489,6 +489,22 @@ curl -s localhost:8000/v1/systemone -H 'content-type: application/json' -d '{
}'
```
+To evaluate multiple states in a single call, send a `states` array to `POST /v1/systemone/batch` (capped at 64 states):
+
+```bash
+curl -s localhost:8000/v1/systemone/batch -H 'content-type: application/json' -d '{
+ "states": [
+ {"body": "billed twice, refund please"},
+ {"body": "cannot login, getting 500 error"}
+ ],
+ "questions": {"dept": {"type": "choice", "instructions": "which team?",
+ "criteria": {"billing": "refunds", "tech": "bugs"}}}
+}'
+```
+
+The endpoint shares forward passes via `Router.predict_batch` and returns an array of `results` in matching order along with aggregated `total_usage`.
+
+
Configuration is by environment variable: `LAYA_HOST`, `LAYA_PORT`,
`LAYA_DEVICE`, `LAYA_PRELOAD`, `LAYA_MODELS` (comma list to preload),
`LAYA_THREADS` (cap torch intra-op threads for CPU inference — keep at or below
diff --git a/laya/serve.py b/laya/serve.py
index ed08d39a..58a10516 100644
--- a/laya/serve.py
+++ b/laya/serve.py
@@ -66,6 +66,7 @@ _KNOWN_MODELS = {"english", "multilingual", "typed-decisions"}
# the single-worker pool means one large request would also starve /health.
MAX_QUESTIONS = 64
MAX_STATE_CHARS = 50000
+MAX_BATCH_STATES = 64
MAX_BODY_BYTES = 2 * 1024 * 1024
# HTTP-only amplification guard; the library keeps its head_max_len-aware budget.
MAX_CHOICE_OPTIONS = 100
@@ -254,6 +255,21 @@ def _check_request_limits(state: Any, questions: Any) -> None:
detail="state too large (%d > %d chars)" % (state_len, MAX_STATE_CHARS))
+def _check_batch_limits(states: Any, questions: Any) -> None:
+ """Validate batch states and questions before inference (400/413)."""
+ from fastapi import HTTPException
+
+ if not isinstance(states, list) or len(states) == 0:
+ raise HTTPException(status_code=400, detail="'states' must be a non-empty list")
+ if len(states) > MAX_BATCH_STATES:
+ raise HTTPException(
+ status_code=413,
+ detail="too many states in batch (%d > %d)" % (len(states), MAX_BATCH_STATES),
+ )
+ for state in states:
+ _check_request_limits(state, questions)
+
+
async def _read_body_capped(request: Any) -> bytes:
"""Read the request body, refusing to buffer more than ``MAX_BODY_BYTES``.
@@ -280,6 +296,23 @@ async def _read_body_capped(request: Any) -> bytes:
return b"".join(chunks)
+async def _read_json_body(request: Any) -> Any:
+ """Read the request body and decode JSON, enforcing size caps and parse error guards."""
+ from fastapi import HTTPException
+
+ if request.headers.get("content-length"):
+ try:
+ if int(request.headers["content-length"]) > MAX_BODY_BYTES:
+ raise HTTPException(status_code=413, detail="request body too large")
+ except ValueError:
+ pass
+ raw = await _read_body_capped(request)
+ try:
+ return json.loads(raw)
+ except (ValueError, RecursionError):
+ raise HTTPException(status_code=400, detail="request body must be valid JSON")
+
+
def _apply_thread_limit():
"""Honour LAYA_THREADS by capping torch's intra-op thread count for CPU
inference. Returns the value applied, or None if unset/invalid. torch is
@@ -422,10 +455,9 @@ def create_app(router: Optional[Any] = None):
"cpu_fallbacks": fallbacks,
}
- @app.post("/v1/systemone")
- async def systemone(request: Request, authorization: Optional[str] = Header(default=None)):
- nonlocal gate, admission
- _check_auth(authorization)
+ @asynccontextmanager
+ async def _admit():
+ nonlocal admission
if admission is None:
admission = asyncio.Semaphore(max_concurrent)
if admission.locked():
@@ -437,30 +469,19 @@ def create_app(router: Optional[Any] = None):
headers={"Retry-After": "1"})
await admission.acquire()
try:
- return await _systemone_inner(request)
+ yield
finally:
admission.release()
+ @app.post("/v1/systemone")
+ async def systemone(request: Request, authorization: Optional[str] = Header(default=None)):
+ _check_auth(authorization)
+ async with _admit():
+ return await _systemone_inner(request)
+
async def _systemone_inner(request: Request):
nonlocal gate
- # A declared length over the cap is rejected before anything is read; the
- # streaming cap below is what actually enforces it, for bodies that declare
- # no length or understate it.
- if request.headers.get("content-length"):
- try:
- if int(request.headers["content-length"]) > MAX_BODY_BYTES:
- raise HTTPException(status_code=413, detail="request body too large")
- except ValueError:
- pass
- raw = await _read_body_capped(request)
- try:
- # A client can cause ValueError (JSONDecodeError for malformed/empty/truncated
- # bodies, UnicodeDecodeError for invalid UTF-8) or RecursionError (deeply nested
- # arrays/objects). A broader catch would also swallow ClientDisconnect and
- # Starlette's own stream errors, reporting a transport or server fault as the client's.
- body = json.loads(raw)
- except (ValueError, RecursionError):
- raise HTTPException(status_code=400, detail="request body must be valid JSON")
+ body = await _read_json_body(request)
if not isinstance(body, dict) or "questions" not in body:
raise HTTPException(status_code=400, detail="request body must be an object with a 'questions' field")
state = body.get("state")
@@ -515,6 +536,61 @@ def create_app(router: Optional[Any] = None):
str(model).replace("\n", "\\n").replace("\r", "\\r"))
raise HTTPException(status_code=500, detail="inference failed")
+ @app.post("/v1/systemone/batch")
+ async def systemone_batch(request: Request, authorization: Optional[str] = Header(default=None)):
+ _check_auth(authorization)
+ async with _admit():
+ return await _systemone_batch_inner(request)
+
+ async def _systemone_batch_inner(request: Request):
+ nonlocal gate
+ body = await _read_json_body(request)
+ if not isinstance(body, dict) or "questions" not in body or "states" not in body:
+ raise HTTPException(
+ status_code=400,
+ detail="request body must be an object with 'states' and 'questions' fields",
+ )
+ states = body["states"]
+ questions = body["questions"]
+ _check_batch_limits(states, questions)
+ model = _resolve_model(body.get("model"))
+ if gate is None:
+ gate = asyncio.Lock()
+ try:
+ async with gate:
+ loop = asyncio.get_running_loop()
+
+ def _do_batch():
+ if hasattr(router, "predict_batch"):
+ reqs = [{"state": s, "questions": questions, "model": model} for s in states]
+ results = router.predict_batch(reqs)
+ else:
+ results = [router.predict(s, questions, model=model) for s in states]
+ total_tokens = sum(r.get("usage", {}).get("input_tokens", 0) for r in results)
+ return {
+ "results": results,
+ "total_usage": {"input_tokens": total_tokens, "output_tokens": 0},
+ }
+
+ t0 = time.perf_counter()
+ batch_res = await loop.run_in_executor(pool, _do_batch)
+ infer_ms = (time.perf_counter() - t0) * 1000.0
+ from fastapi.responses import JSONResponse
+ return JSONResponse(
+ content=batch_res,
+ headers={
+ "Server-Timing": f"inference;dur={infer_ms:.2f}",
+ "X-Inference-Time-Ms": f"{infer_ms:.2f}"
+ }
+ )
+ except HTTPException:
+ raise
+ except ValueError as e:
+ raise HTTPException(status_code=422, detail=str(e))
+ except Exception: # noqa: BLE001
+ _log.exception("batch inference failed")
+ raise HTTPException(status_code=500, detail="inference failed")
+
return app
diff --git a/tests/test_serve.py b/tests/test_serve.py
index dab066ab..fa1b6fba 100644
--- a/tests/test_serve.py
+++ b/tests/test_serve.py
@@ -941,3 +941,168 @@ def test_resolve_max_token_budget_fallback(monkeypatch, caplog):
assert "invalid LAYA_MAX_TOKEN_BUDGET" in caplog.text
assert "LAYA_MAX_TOKEN_BUDGET must be positive" in caplog.text
+BATCH_REQ = {
+ "states": ["first state", "second state"],
+ "questions": REQ["questions"],
+}
+
+
+def test_batch_happy_path(monkeypatch):
+ client, fake = _client(monkeypatch)
+ r = client.post("/v1/systemone/batch", json=BATCH_REQ)
+ assert r.status_code == 200, r.text
+ data = r.json()
+ assert "results" in data
+ assert len(data["results"]) == 2
+ assert "total_usage" in data
+ assert data["total_usage"]["input_tokens"] == sum(
+ res["usage"]["input_tokens"] for res in data["results"]
+ )
+ assert len(fake.calls) == 2
+ assert "Server-Timing" in r.headers
+ assert "X-Inference-Time-Ms" in r.headers
+
+
+def test_batch_missing_state_in_list_returns_400(monkeypatch):
+ """A None state inside states list must be rejected with 400 'state' is required."""
+ client, _ = _client(monkeypatch)
+ bad_req = {"states": [None, "hello"], "questions": REQ["questions"]}
+ r = client.post("/v1/systemone/batch", json=bad_req)
+ assert r.status_code == 400
+ assert "'state' is required" in r.json()["detail"]
+
+
+def test_batch_too_many_options_returns_413(monkeypatch):
+ """Questions with more than MAX_CHOICE_OPTIONS must be rejected with 413."""
+ client, _ = _client(monkeypatch)
+ bad_questions = {
+ "dept": {
+ "type": "choice",
+ "instructions": "which?",
+ "criteria": {f"opt_{i}": f"desc_{i}" for i in range(101)},
+ }
+ }
+ r = client.post("/v1/systemone/batch", json={"states": ["state"], "questions": bad_questions})
+ assert r.status_code == 413
+ assert "too many choice options" in r.json()["detail"]
+
+
+def test_batch_empty_states_returns_400(monkeypatch):
+ client, _ = _client(monkeypatch)
+ r = client.post("/v1/systemone/batch", json={"states": [], "questions": REQ["questions"]})
+ assert r.status_code == 400
+ assert "states" in r.json()["detail"]
+
+
+def test_batch_missing_states_returns_400(monkeypatch):
+ client, _ = _client(monkeypatch)
+ r = client.post("/v1/systemone/batch", json={"questions": REQ["questions"]})
+ assert r.status_code == 400
+
+
+def test_batch_missing_questions_returns_400(monkeypatch):
+ client, _ = _client(monkeypatch)
+ r = client.post("/v1/systemone/batch", json={"states": ["state 1"]})
+ assert r.status_code == 400
+
+
+def test_batch_too_many_states_returns_413(monkeypatch):
+ client, _ = _client(monkeypatch)
+ from laya.serve import MAX_BATCH_STATES
+ oversized = {"states": ["state"] * (MAX_BATCH_STATES + 1), "questions": REQ["questions"]}
+ r = client.post("/v1/systemone/batch", json=oversized)
+ assert r.status_code == 413
+ assert "too many states" in r.json()["detail"]
+
+
+def test_batch_individual_oversized_state_returns_413(monkeypatch):
+ client, _ = _client(monkeypatch)
+ from laya.serve import MAX_STATE_CHARS
+ bad_req = {
+ "states": ["ok", "X" * (MAX_STATE_CHARS + 10)],
+ "questions": REQ["questions"],
+ }
+ r = client.post("/v1/systemone/batch", json=bad_req)
+ assert r.status_code == 413
+ assert "state too large" in r.json()["detail"]
+
+
+def test_batch_auth_required_when_key_set(monkeypatch):
+ client, _ = _client(monkeypatch, api_key="secret123")
+ r = client.post("/v1/systemone/batch", json=BATCH_REQ)
+ assert r.status_code == 401
+ ok = client.post(
+ "/v1/systemone/batch",
+ json=BATCH_REQ,
+ headers={"Authorization": "Bearer secret123"},
+ )
+ assert ok.status_code == 200
+
+
+def test_batch_admission_bound_refuses_with_503(monkeypatch):
+ """Batch endpoint must respect the admission bound and return 503 when busy."""
+ import asyncio
+ import httpx
+
+ monkeypatch.delenv("LAYA_API_KEY", raising=False)
+ monkeypatch.setenv("LAYA_MAX_CONCURRENT", "1")
+ fake = GatedRouter()
+ app = create_app(router=fake)
+ seen = {}
+
+ async def drive():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as client:
+ first = asyncio.ensure_future(client.post("/v1/systemone", json=REQ))
+ for _ in range(200):
+ if fake.entered.is_set():
+ break
+ await asyncio.sleep(0.05)
+ assert fake.entered.is_set(), "first request never reached inference"
+ await asyncio.sleep(0.2)
+ seen["batch_second"] = (await client.post("/v1/systemone/batch", json=BATCH_REQ)).status_code
+ fake.release.set()
+ seen["first"] = (await first).status_code
+
+ asyncio.run(drive())
+
+ assert seen["batch_second"] == 503, seen
+ assert seen["first"] == 200, seen
+
+
+class BatchCapableFakeRouter(FakeRouter):
+ """FakeRouter that implements predict_batch."""
+
+ def __init__(self):
+ super().__init__()
+ self.batch_calls = []
+
+ def predict_batch(self, requests, batch_size=None):
+ self.batch_calls.append(requests)
+ return [
+ {
+ "model": "laya-rl-agent",
+ "answers": {
+ "dept": {
+ "type": "choice",
+ "choice": "billing",
+ "probabilities": {"billing": 0.94, "tech": 0.06},
+ "confidence": 0.94,
+ }
+ },
+ "usage": {"input_tokens": 42, "output_tokens": 0},
+ "routing": {"model": "english", "reason": "English Latin text"},
+ }
+ for _ in requests
+ ]
+
+
+def test_batch_uses_predict_batch_when_available(monkeypatch):
+ monkeypatch.delenv("LAYA_API_KEY", raising=False)
+ fake = BatchCapableFakeRouter()
+ client = TestClient(create_app(router=fake))
+ r = client.post("/v1/systemone/batch", json=BATCH_REQ)
+ assert r.status_code == 200, r.text
+ assert len(fake.batch_calls) == 1
+ assert len(fake.batch_calls[0]) == 2
+ assert len(fake.calls) == 0 # Confirms no sequential predict() fallback calls were made