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(sdk): add Python HTTP batch predictions

xp8836bf68c944
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 240da7d3..ed15edb1 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -103,8 +103,49 @@ HTTP error details can be strings, objects or arrays. Error bodies are read up t
64 KiB; bodies that cannot be decoded as JSON are returned as text. The SDK does not log requests or credentials;
applications should handle server diagnostics according to their own logging policy.
-The first version exposes `predict` and `health`. It does not implement async,
-batch, local routing, model loading or Python prediction hooks.
+The client exposes `predict`, `predict_batch` and `health`. It does not implement
+async, local routing, model loading or Python prediction hooks.
+
+## Batch predictions
+
+`predict_batch` sends one `POST /v1/systemone/batch` request with a nonempty list
+of states and one shared question set:
+
+```python
+states = ["Please refund my order", {"message": "Where is my order?"}]
+questions = {
+ "refund": {"type": "noul", "instructions": "Is the customer requesting a refund?"},
+}
+batch = client.predict_batch(states, questions)
+for state, result in zip(states, batch["results"]):
+ print(state, result["answers"]["refund"]["noul"])
+print(batch["total_usage"])
+```
+
+The return type is `laya_client.types.BatchPrediction`, an ordinary dictionary
+with `results: list[Prediction]` and `total_usage: Usage`. Result at index `i`
+belongs to state at index `i`; the client preserves server order and unknown
+fields. It requires exactly one valid prediction per state and nonnegative
+integer `input_tokens` and `output_tokens` in `total_usage`. An invalid envelope,
+count or individual result raises `LayaResponseError`; no partial list is returned.
+
+All `predict` controls apply to the whole batch. The additional optional
+`batch_size` (positive integer) and `sort_by_length` (boolean) control server-side
+inference batching, not HTTP request splitting. Length sorting still returns
+results in input order. Changing inference batch shapes can change floating-point
+results; the client does not recalculate predictions or confidence.
+
+Omitted controls inherit server settings. Empty lists and invalid JSON inputs
+raise `LayaValidationError` before sending. Server limits remain authoritative:
+the current server accepts at most 64 states, with its existing per-state,
+question, token-budget and request-body limits. A larger list is sent once and
+the server's refusal (normally HTTP 413) is exposed as `LayaAPIError`.
+
+The batch endpoint fails the whole request; there is no per-item error contract.
+On a server without this endpoint, HTTP 404/405 raises `LayaAPIError` with the
+original status and detail. The SDK never falls back to individual requests,
+splits a request, or retries it, including after a timeout. Existing `predict`
+and `health` behavior is unchanged.
## Development and verification
diff --git a/sdk/python/src/laya_client/_validation.py b/sdk/python/src/laya_client/_validation.py
index 11e5c04c..fc012bd1 100644
--- a/sdk/python/src/laya_client/_validation.py
+++ b/sdk/python/src/laya_client/_validation.py
@@ -67,6 +67,22 @@ def expect(condition: bool, field: str) -> None:
raise LayaResponseError("Invalid Laya response: " + field)
+def batch_prediction(value: Any, questions: dict, count: int) -> None:
+ expect(isinstance(value, dict), "batch prediction object")
+ results = value.get("results")
+ expect(isinstance(results, list), "results")
+ expect(len(results) == count, "results count does not match states")
+ usage = value.get("total_usage")
+ expect(isinstance(usage, dict), "total_usage")
+ for key in ("input_tokens", "output_tokens"):
+ expect(type(usage.get(key)) is int and usage[key] >= 0, "total_usage." + key)
+ for i, result in enumerate(results):
+ try:
+ prediction(result, questions)
+ except LayaResponseError as exc:
+ raise LayaResponseError("Invalid Laya response: results[%d]: %s" % (i, exc)) from exc
+
+
def prediction(value: Any, questions: dict) -> None:
expect(isinstance(value, dict), "prediction object")
expect(isinstance(value.get("model"), str), "model")
diff --git a/sdk/python/src/laya_client/client.py b/sdk/python/src/laya_client/client.py
index ac80ca1b..50a799c7 100644
--- a/sdk/python/src/laya_client/client.py
+++ b/sdk/python/src/laya_client/client.py
@@ -6,9 +6,9 @@ import urllib.parse
import urllib.request
from typing import Any, Optional, cast
-from ._validation import expect, json_value, prediction, probability, questions_value, timeout_value
+from ._validation import batch_prediction, expect, json_value, prediction, probability, questions_value, timeout_value
from .errors import LayaAPIError, LayaConnectionError, LayaResponseError, LayaTimeoutError, LayaValidationError
-from .types import Health, MinConfidence, Prediction, Questions, State
+from .types import BatchPrediction, Health, MinConfidence, Prediction, Questions, State
class _NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -57,8 +57,45 @@ class LayaClient:
"""Predict choice, score and noul answers; omitted controls inherit server settings."""
if not isinstance(state, (str, dict, list)):
raise LayaValidationError("state must be text, a JSON object or an array")
+ body = self._prediction_body(questions, model, task, lang, lang_guess, max_len, head_max_len, min_confidence)
+ body["state"] = state
+ result = self._request("/v1/systemone", body, timeout)
+ prediction(result, questions)
+ return cast(Prediction, result)
+
+ def predict_batch(self, states: list[State], questions: Questions, *, model: Optional[str] = None,
+ task: Optional[str] = None, lang: Optional[str] = None, lang_guess: Optional[str] = None,
+ max_len: Optional[int] = None, head_max_len: Optional[int] = None,
+ min_confidence: Optional[MinConfidence] = None, batch_size: Optional[int] = None,
+ sort_by_length: Optional[bool] = None, timeout: Optional[float] = None) -> BatchPrediction:
+ """Predict a nonempty list of states with shared questions, preserving input order.
+
+ Sends one batch request. Server limits and unsupported endpoints raise LayaAPIError;
+ there is no automatic splitting or fallback to single predictions.
+ """
+ if not isinstance(states, list) or not states:
+ raise LayaValidationError("states must be a nonempty list")
+ for i, state in enumerate(states):
+ if not isinstance(state, (str, dict, list)):
+ raise LayaValidationError("states[%d] must be text, a JSON object or an array" % i)
+ body = self._prediction_body(questions, model, task, lang, lang_guess, max_len, head_max_len, min_confidence)
+ body["states"] = states
+ if batch_size is not None:
+ if type(batch_size) is not int or batch_size <= 0:
+ raise LayaValidationError("batch_size must be a positive integer")
+ body["batch_size"] = batch_size
+ if sort_by_length is not None:
+ if type(sort_by_length) is not bool:
+ raise LayaValidationError("sort_by_length must be a boolean")
+ body["sort_by_length"] = sort_by_length
+ result = self._request("/v1/systemone/batch", body, timeout)
+ batch_prediction(result, questions, len(states))
+ return cast(BatchPrediction, result)
+
+ @staticmethod
+ def _prediction_body(questions, model, task, lang, lang_guess, max_len, head_max_len, min_confidence):
questions_value(questions)
- body: dict[str, Any] = {"state": state, "questions": questions}
+ body: dict[str, Any] = {"questions": questions}
for key, value in (("model", model), ("task", task), ("lang", lang), ("lang_guess", lang_guess)):
if value is not None:
if not isinstance(value, str) or not value.strip():
@@ -76,9 +113,7 @@ class LayaClient:
if not probability(min_confidence) and not valid_map:
raise LayaValidationError("min_confidence must be a threshold in [0, 1] or a nonempty threshold map")
body["min_confidence"] = min_confidence
- result = self._request("/v1/systemone", body, timeout)
- prediction(result, questions)
- return cast(Prediction, result)
+ return body
def health(self, *, timeout: Optional[float] = None) -> Health:
"""Read liveness; a minimal response does not prove authentication or model readiness."""
diff --git a/sdk/python/src/laya_client/types.py b/sdk/python/src/laya_client/types.py
index ea802700..8616327d 100644
--- a/sdk/python/src/laya_client/types.py
+++ b/sdk/python/src/laya_client/types.py
@@ -61,5 +61,10 @@ class Prediction(_PredictionExtensions):
usage: Usage
+class BatchPrediction(TypedDict):
+ results: List[Prediction]
+ total_usage: Usage
+
+
class Health(TypedDict):
status: Literal["ok"]
diff --git a/sdk/python/tests/integration.py b/sdk/python/tests/integration.py
index 9394aabf..812cf799 100644
--- a/sdk/python/tests/integration.py
+++ b/sdk/python/tests/integration.py
@@ -13,12 +13,77 @@ import time
from laya_client import LayaAPIError, LayaClient, LayaConnectionError
+def check_batch(result, expected, strict=False):
+ assert len(result["results"]) == len(expected)
+ for item, direct in zip(result["results"], expected):
+ if strict:
+ fields = {"choice": ("type", "choice", "probabilities", "confidence"),
+ "score": ("type", "score", "probabilities", "confidence", "legend"),
+ "noul": ("type", "noul")}
+ projected = {
+ "model": direct["model"],
+ "answers": {qid: {k: answer[k] for k in fields[answer["type"]]}
+ for qid, answer in direct["answers"].items()},
+ "usage": {k: direct["usage"][k] for k in ("input_tokens", "output_tokens")},
+ }
+ assert item == projected, (item, projected)
+ else:
+ assert item["model"] == direct["model"]
+ for qid, answer in direct["answers"].items():
+ for key, value in answer.items():
+ assert item["answers"][qid][key] == value, (qid, key)
+ for key, value in direct["usage"].items():
+ assert item["usage"][key] == value, key
+ assert item["routing"] == direct["routing"]
+ for key in ("input_tokens", "output_tokens"):
+ assert result["total_usage"][key] == sum(item["usage"][key] for item in expected), key
+
+
+def check_batch_http(client, anonymous, fixture, strict, legacy):
+ questions = fixture["questions"]
+ if legacy:
+ # v0.4.7 has a batch endpoint. One-state passes give its unchanged fixture a parity oracle.
+ states = ["hello", fixture["state"], ["hello"]]
+ expected = [client.predict(state, questions, model="english") for state in states]
+ check_batch(client.predict_batch(states, questions, model="english", batch_size=1), expected)
+ check_batch(client.predict_batch(states[:1], questions, model="english"), expected[:1])
+ else:
+ for case in fixture["batch_cases"]:
+ result = client.predict_batch(case["states"], questions, model="english", **case["controls"])
+ check_batch(result, case["expected"], strict)
+ labels = {str(i): "Option %d" % i for i in range(5)}
+ large = {"large": {"type": "choice", "instructions": "Pick one", "criteria": labels}}
+ states = fixture["batch_cases"][0]["states"]
+ # Tournament execution is per state on the server, even when batch shape controls are set.
+ expected = [client.predict(state, large, model="english") for state in states]
+ check_batch(client.predict_batch(states, large, model="english",
+ batch_size=2, sort_by_length=True), expected, strict)
+
+ small = {"refund": questions["refund"]}
+ result = client.predict_batch(["hello"] * 64, small, model="english", batch_size=8)
+ assert len(result["results"]) == 64
+ for key in ("input_tokens", "output_tokens"):
+ assert result["total_usage"][key] == sum(item["usage"][key] for item in result["results"])
+ for caller, states, controls, status in (
+ (client, ["hello"] * 65, {}, 413),
+ (client, ["hello", "x" * 50_001], {}, 413),
+ (client, ["hello"], {"model": "unpublished/checkpoint"}, 422),
+ (anonymous, ["hello"], {}, 401),
+ ):
+ try:
+ caller.predict_batch(states, small, **controls)
+ except LayaAPIError as error:
+ assert error.status_code == status, (error.status_code, status, error.detail)
+ else:
+ raise AssertionError("Batch request should have failed with HTTP %d" % status)
+
+
def run(server_python, fixture_path, strict=False, legacy=False):
with tempfile.TemporaryDirectory(prefix="laya-sdk-live-") as directory:
root = Path(directory)
command = [str(server_python), "-u", str(fixture_path)]
if not legacy:
- command.append("--tournament")
+ command.extend(["--tournament", "--batch"])
if strict:
command.append("--strict")
env = dict(os.environ)
@@ -111,7 +176,8 @@ def run(server_python, fixture_path, strict=False, legacy=False):
assert error.status_code == 413
else:
raise AssertionError("Server request limit was bypassed")
- print("PASS real HTTP inference, controls, auth and limits: "
+ check_batch_http(client, anonymous, fixture, strict, legacy)
+ print("PASS real HTTP single and batch inference, order, controls, auth and limits: "
+ ("legacy fixture" if legacy else "strict" if strict else "extended/tournament"), flush=True)
except BaseException:
stderr.flush()
diff --git a/sdk/python/tests/test_api.py b/sdk/python/tests/test_api.py
index f3f83a7b..da1d7dda 100644
--- a/sdk/python/tests/test_api.py
+++ b/sdk/python/tests/test_api.py
@@ -27,7 +27,19 @@ class APITests(unittest.TestCase):
self.assertEqual(parameters[name].kind, inspect.Parameter.KEYWORD_ONLY)
self.assertIsNone(parameters[name].default)
self.assertEqual(list(inspect.signature(LayaClient.health).parameters), ["self", "timeout"])
- self.assertFalse(hasattr(LayaClient, "predict_batch"))
+
+ def test_predict_batch_parameters(self):
+ from laya_client.types import BatchPrediction
+ signature = inspect.signature(LayaClient.predict_batch)
+ parameters = signature.parameters
+ self.assertEqual(list(parameters), ["self", "states", "questions", "model", "task", "lang",
+ "lang_guess", "max_len", "head_max_len", "min_confidence",
+ "batch_size", "sort_by_length", "timeout"])
+ for name in list(parameters)[3:]:
+ self.assertEqual(parameters[name].kind, inspect.Parameter.KEYWORD_ONLY)
+ self.assertIsNone(parameters[name].default)
+ self.assertIs(signature.return_annotation, BatchPrediction)
+ self.assertEqual(BatchPrediction.__required_keys__, {"results", "total_usage"})
def test_constructor_defaults(self):
parameters = inspect.signature(LayaClient).parameters
diff --git a/sdk/python/tests/test_batch.py b/sdk/python/tests/test_batch.py
new file mode 100644
index 00000000..6d5f7e20
--- /dev/null
+++ b/sdk/python/tests/test_batch.py
@@ -0,0 +1,187 @@
+import copy
+import json
+import unittest
+
+from laya_client import (
+ LayaAPIError, LayaClient, LayaConnectionError, LayaResponseError,
+ LayaTimeoutError, LayaValidationError,
+)
+from _support import PREDICTION, QUESTIONS, Server
+
+
+def batch_payload(count=2):
+ results = []
+ for i in range(count):
+ result = copy.deepcopy(PREDICTION)
+ result["usage"]["input_tokens"] += i
+ result["answers"]["refund"]["noul"] = (i + 1) / (count + 1)
+ results.append(result)
+ return {
+ "results": results,
+ "total_usage": {"input_tokens": sum(r["usage"]["input_tokens"] for r in results), "output_tokens": 0},
+ }
+
+
+class BatchTests(unittest.TestCase):
+ def test_batch_request_and_order(self):
+ states = ["hello नमस्ते", {"text": "billing", "flag": False}, ["technical", {"count": 0}]]
+ payload = batch_payload(3)
+ with Server(payload) as server:
+ result = LayaClient(base_url=server.url + "/proxy/", api_key="batch-token").predict_batch(
+ states, QUESTIONS)
+ self.assertEqual(result, payload)
+ self.assertEqual(len(server.requests), 1)
+ method, path, headers, body = server.requests[0]
+ self.assertEqual((method, path), ("POST", "/proxy/v1/systemone/batch"))
+ self.assertEqual(headers["Authorization"], "Bearer batch-token")
+ self.assertEqual(headers["Content-Type"], "application/json")
+ self.assertEqual(headers["Accept"], "application/json")
+ self.assertEqual(json.loads(body), {"states": states, "questions": QUESTIONS})
+ self.assertEqual([r["usage"]["input_tokens"] for r in result["results"]], [123, 124, 125])
+
+ def test_singleton_and_current_server_boundary(self):
+ # The server owns its limit. The client sends each list once, without chunking.
+ for count in (1, 64, 65):
+ with self.subTest(count=count), Server(batch_payload(count)) as server:
+ result = LayaClient(base_url=server.url).predict_batch(["hello"] * count, QUESTIONS)
+ self.assertEqual(len(result["results"]), count)
+ self.assertEqual(len(server.requests), 1)
+ self.assertEqual(len(json.loads(server.requests[0][3])["states"]), count)
+
+ def test_controls_are_forwarded_without_reordering_states(self):
+ controls = {"model": "custom", "task": "email", "lang": "en", "lang_guess": "de",
+ "max_len": 128, "head_max_len": 64, "min_confidence": {"default": 0.0},
+ "batch_size": 1, "sort_by_length": True}
+ states = ["a longer state", "short"]
+ with Server(batch_payload()) as server:
+ result = LayaClient(base_url=server.url).predict_batch(states, QUESTIONS, **controls, timeout=2)
+ self.assertEqual(result, batch_payload())
+ self.assertEqual(json.loads(server.requests[0][3]), {"states": states, "questions": QUESTIONS, **controls})
+ with Server(batch_payload()) as server:
+ LayaClient(base_url=server.url).predict_batch(states, QUESTIONS, sort_by_length=False, min_confidence=0)
+ self.assertIs(json.loads(server.requests[0][3])["sort_by_length"], False)
+
+ def test_invalid_states_never_send(self):
+ cyclic = []
+ cyclic.append(cyclic)
+ cases = [None, [], "hello", {}, ("hello",), [None], [True], [1], [1.5], [object()],
+ ["valid", None], [{"nested": float("nan")}], [{"nested": float("inf")}],
+ [{1: "key"}], [{"nested": (1, 2)}], [cyclic], ["\ud800"]]
+ with Server() as server:
+ client = LayaClient(base_url=server.url)
+ for i, states in enumerate(cases):
+ with self.subTest(case=i), self.assertRaises(LayaValidationError):
+ client.predict_batch(states, QUESTIONS)
+ self.assertEqual(server.requests, [])
+
+ def test_invalid_questions_and_controls_never_send(self):
+ with Server() as server:
+ client = LayaClient(base_url=server.url)
+ for questions in (None, [], {}, {"x": None}, {"x": {"type": "choice"}}):
+ with self.subTest(questions=questions), self.assertRaises(LayaValidationError):
+ client.predict_batch(["hello"], questions)
+ cases = [{"model": ""}, {"task": 1}, {"lang": False}, {"lang_guess": ""},
+ {"max_len": True}, {"head_max_len": 0}, {"min_confidence": True},
+ {"min_confidence": {}}, {"min_confidence": {"default": 1.1}},
+ *({"batch_size": v} for v in (True, False, 0, -1, 1.5, "2")),
+ *({"sort_by_length": v} for v in (0, 1, "false", [])),
+ *({"timeout": v} for v in (False, 0, -1, float("inf"), float("nan")))]
+ for controls in cases:
+ with self.subTest(controls=controls), self.assertRaises(LayaValidationError):
+ client.predict_batch(["hello"], QUESTIONS, **controls)
+ with self.assertRaises(TypeError):
+ client.predict_batch(["hello"], QUESTIONS, hooks=[])
+ self.assertEqual(server.requests, [])
+
+ def test_response_envelope_and_count_are_validated(self):
+ cases = [[], {}, {"count": 2, "results": []}]
+ for key, value in (("results", None), ("results", {}), ("results", []),
+ ("results", [PREDICTION]), ("results", [PREDICTION] * 3),
+ ("total_usage", None), ("total_usage", []), ("total_usage", {})):
+ payload = batch_payload()
+ payload[key] = value
+ cases.append(payload)
+ for payload in cases:
+ with self.subTest(payload=payload), Server(payload) as server:
+ with self.assertRaises(LayaResponseError):
+ LayaClient(base_url=server.url).predict_batch(["first", "second"], QUESTIONS)
+ self.assertEqual(len(server.requests), 1)
+
+ def test_total_usage_is_validated(self):
+ for key in ("input_tokens", "output_tokens"):
+ for value in (None, True, -1, 1.5, "1"):
+ payload = batch_payload()
+ payload["total_usage"][key] = value
+ with self.subTest(key=key, value=value), Server(payload) as server:
+ with self.assertRaises(LayaResponseError):
+ LayaClient(base_url=server.url).predict_batch(["first", "second"], QUESTIONS)
+
+ def test_invalid_item_is_not_dropped_or_returned_as_partial_success(self):
+ bad_answer = copy.deepcopy(PREDICTION)
+ bad_answer["answers"]["refund"]["noul"] = True
+ bad_usage = copy.deepcopy(PREDICTION)
+ bad_usage["usage"]["input_tokens"] = -1
+ for item in (None, [], {}, {"error": "inference failed"}, bad_answer, bad_usage):
+ payload = batch_payload()
+ payload["results"][1] = item
+ with self.subTest(item=item), Server(payload) as server:
+ with self.assertRaisesRegex(LayaResponseError, r"results\[1\]"):
+ LayaClient(base_url=server.url).predict_batch(["first", "second"], QUESTIONS)
+ self.assertEqual(len(server.requests), 1)
+
+ def test_strict_and_extended_results_are_preserved(self):
+ payload = batch_payload()
+ payload["future"] = {"value": None}
+ payload["total_usage"]["new_measurement"] = 7
+ extended = payload["results"][1]
+ extended["routing"] = {"model": "custom", "future": [1, False]}
+ extended["answers"]["team"].update(
+ probabilities={"billing": 1.0, "technical": 0.0}, confidence=0.0, answer_confidence=1.0,
+ x_tournament={"finalists": ["billing"]}, abstention="passed", abstention_threshold=0.8)
+ with Server(payload) as server:
+ result = LayaClient(base_url=server.url).predict_batch(["first", "second"], QUESTIONS, min_confidence=0.8)
+ self.assertEqual(result, payload)
+ self.assertNotIn("abstention", result["results"][0]["answers"]["team"])
+
+ def test_invalid_json_is_a_response_error(self):
+ for raw in (b"not json", b"null", b'{"results": NaN}', b"\xff"):
+ with self.subTest(raw=raw), Server(raw=raw) as server:
+ with self.assertRaises(LayaResponseError):
+ LayaClient(base_url=server.url).predict_batch(["hello"], QUESTIONS)
+
+ def test_http_errors_and_unsupported_endpoints_do_not_retry_or_fall_back(self):
+ for status in (400, 401, 404, 405, 413, 422, 500, 503):
+ detail = {"message": "batch refused", "status": status}
+ with self.subTest(status=status), Server({"detail": detail}, status=status) as server:
+ with self.assertRaises(LayaAPIError) as caught:
+ LayaClient(base_url=server.url).predict_batch(["hello"], QUESTIONS)
+ self.assertEqual(caught.exception.status_code, status)
+ self.assertEqual(caught.exception.detail, detail)
+ self.assertEqual([r[1] for r in server.requests], ["/v1/systemone/batch"])
+
+ def test_redirect_does_not_replay_batch_or_forward_credentials(self):
+ with Server(batch_payload(1)) as destination:
+ with Server({}, status=307, headers={"Location": destination.url}) as source:
+ with self.assertRaises(LayaAPIError) as caught:
+ LayaClient(base_url=source.url, api_key="batch-token").predict_batch(["hello"], QUESTIONS)
+ self.assertEqual(caught.exception.status_code, 307)
+ self.assertEqual(len(source.requests), 1)
+ self.assertEqual(destination.requests, [])
+
+ def test_timeouts_do_not_retry_or_fall_back(self):
+ for overrides in ({}, {"timeout": 0.05}):
+ with self.subTest(overrides=overrides), Server(batch_payload(1), slow=True) as server:
+ client = LayaClient(base_url=server.url, timeout=0.05 if not overrides else 2)
+ with self.assertRaises(LayaTimeoutError):
+ client.predict_batch(["hello"], QUESTIONS, **overrides)
+ self.assertEqual(len(server.requests), 1)
+
+ def test_interrupted_response_is_a_connection_error(self):
+ with Server(batch_payload(1), truncated=True) as server:
+ with self.assertRaises(LayaConnectionError):
+ LayaClient(base_url=server.url).predict_batch(["hello"], QUESTIONS)
+ self.assertEqual(len(server.requests), 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/sdk_server_fixture.py b/tests/sdk_server_fixture.py
index cc475ec0..60ffae1e 100644
--- a/tests/sdk_server_fixture.py
+++ b/tests/sdk_server_fixture.py
@@ -17,6 +17,7 @@ import uvicorn # noqa: E402
from safetensors.torch import save_file # noqa: E402
from tokenizers import Tokenizer # noqa: E402
from tokenizers.models import WordLevel # noqa: E402
+from tokenizers.pre_tokenizers import WhitespaceSplit # noqa: E402
from transformers import BertConfig, BertModel, PreTrainedTokenizerFast # noqa: E402
from laya import Router, load # noqa: E402
from laya.common import DecisionModel # noqa: E402
@@ -27,6 +28,7 @@ def main():
parser = argparse.ArgumentParser()
parser.add_argument("--strict", action="store_true")
parser.add_argument("--tournament", action="store_true")
+ parser.add_argument("--batch", action="store_true")
args = parser.parse_args()
torch.manual_seed(7)
torch.set_num_threads(1)
@@ -42,6 +44,9 @@ def main():
pad_token="[PAD]", unk_token="[UNK]", cls_token="[CLS]",
sep_token="[SEP]", mask_token="[MASK]",
)
+ if args.batch:
+ # Give the batch fixture distinct token lengths without changing existing SDK fixtures.
+ tokenizer.backend_tokenizer.pre_tokenizer = WhitespaceSplit()
tokenizer.save_pretrained(root / "tokenizer")
save_file(DecisionModel(BertModel(cfg), head_layers=1).state_dict(), root / "model.safetensors")
(root / "rl_agent_config.json").write_text(json.dumps({
@@ -63,6 +68,30 @@ def main():
# model invocation and numeric parity, not pretrained model quality.
for name in ["english", "multilingual", "typed-decisions"]:
router.attach(name, agent)
+ batch_cases = []
+ if args.batch:
+ states = ["hello " * 9, "hello", {"text": "hello " * 4}, ["hello", "hello"]]
+ for name, inputs, controls in (
+ ("default", states, {}),
+ ("singleton", states[:1], {}),
+ ("serial", states, {"batch_size": 1, "sort_by_length": True}),
+ ("sorted", states, {"batch_size": 2, "sort_by_length": True}),
+ ("controls", states, {"batch_size": 2, "sort_by_length": True, "task": "typed-decisions",
+ "lang": "en", "lang_guess": "fr", "max_len": 128, "head_max_len": 64,
+ "min_confidence": {"default": 0.0}}),
+ ):
+ item_controls = {key: value for key, value in controls.items()
+ if key not in ("batch_size", "sort_by_length", "min_confidence")}
+ call_controls = {key: value for key, value in controls.items()
+ if key in ("batch_size", "sort_by_length", "min_confidence")}
+ results = router.predict_batch(
+ [dict(state=s, questions=questions, model="english", **item_controls) for s in inputs],
+ **call_controls,
+ )
+ if name == "default":
+ # Otherwise a reordered response could pass the parity checks by coincidence.
+ assert len({r["usage"]["input_tokens"] for r in results}) == len(inputs)
+ batch_cases.append({"name": name, "states": inputs, "controls": controls, "expected": results})
os.environ["LAYA_API_KEY"] = "integration-test"
# This fixture exercises the default HTTP contract, including its confidence extension.
os.environ["LAYA_JEV_STRICT"] = "1" if args.strict else "0"
@@ -73,6 +102,7 @@ def main():
print("LAYA_TEST_SERVER=" + json.dumps({
"baseURL": "http://127.0.0.1:%d" % listener.getsockname()[1],
"questions": questions, "state": state, "expected": expected,
+ "batch_cases": batch_cases,
}), flush=True)
uvicorn.Server(uvicorn.Config(app, log_level="warning")).run(sockets=[listener])
diff --git a/tests/test_hooks_api.py b/tests/test_hooks_api.py
index 1a5840d9..4afe1525 100644
--- a/tests/test_hooks_api.py
+++ b/tests/test_hooks_api.py
@@ -71,6 +71,7 @@ HOOK_KEYS = {
# --------------------------------------------------------------- constructors
check("HTTP SDK stays outside core exports", "LayaClient" in laya.__all__, False)
+check("HTTP batch response stays outside core exports", "BatchPrediction" in laya.__all__, False)
check("core does not import the HTTP SDK", "laya_client" in sys.modules, False)
for label, fn in (("Agent.__init__", Agent.__init__), ("load", load),