Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fix Decision API validation and TypeSafe SDK metadata (#12186)

Wasim Yousef Said06911b705cae
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.py
index f0fa855c50c..ad7bf68f000 100644
--- a/studio/backend/core/systemone/laya_runtime.py
+++ b/studio/backend/core/systemone/laya_runtime.py
@@ -475,7 +475,8 @@ def _predict(agent, state, questions: dict[str, dict[str, Any]]) -> tuple[dict[s
heads.append(_head(agent, questions[name], max_len, head_max_len))
except ValueError:
raise ValueError(
- "question %r options exceed head_max_len=%d" % (name, head_max_len)
+ f"Question {name!r} options exceed the Laya context window ({max_len} tokens). "
+ "Use fewer or shorter criteria."
) from None
room = max(0, max_len - min(len(ids) for ids, _, _ in heads))
state_ids, state_cut = _state_ids(agent.tok, state, room)
@@ -635,7 +636,7 @@ def _decide(checkpoint: Checkpoint, state, questions: dict[str, dict[str, Any]])
try:
result, truncated = _predict(agent, state, laya_questions)
except ValueError as exc:
- raise Unavailable(400, "invalid_request_error", str(exc)) from None
+ raise Unavailable(422, "invalid_request_error", str(exc)) from None
finally:
_run_lock.release()
return {
diff --git a/studio/backend/main.py b/studio/backend/main.py
index c8398e4babf..1bf1be0f993 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1625,6 +1625,7 @@ app.add_middleware(
expose_headers = [
"X-Unsloth-Conflict-Kind",
"X-Unsloth-Refusal",
+ "x-typesafe-request-id",
*_hub_endpoint_proxy.EXPOSED_HEADERS,
],
# is_allowed_origin closes the moment the tunnel URL clears, but a preflight already cached by the browser
diff --git a/studio/backend/routes/systemone.py b/studio/backend/routes/systemone.py
index 4dbbc7698c6..20a2b19efc6 100644
--- a/studio/backend/routes/systemone.py
+++ b/studio/backend/routes/systemone.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import json
import math
from typing import Any, Optional, Union
+from uuid import uuid4
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import JSONResponse
@@ -64,13 +65,13 @@ def _error(
def _validate(name: str, question: QuestionIn) -> None:
if len(name) + len(json.dumps(question.model_dump(), ensure_ascii = False)) > MAX_QUESTION_CHARS:
raise _error(
- 400,
+ 422,
"invalid_request_error",
f"Question is longer than {MAX_QUESTION_CHARS} characters",
)
if question.type not in _TYPES:
raise _error(
- 400, "api_usage_error", f'Question "{name}" has unknown type "{question.type}"'
+ 422, "api_usage_error", f'Question "{name}" has unknown type "{question.type}"'
)
criteria = question.criteria
if question.type == "noul":
@@ -78,25 +79,34 @@ def _validate(name: str, question: QuestionIn) -> None:
not isinstance(criteria, dict) or set(criteria) - {"true", "false"}
):
raise _error(
- 400,
+ 422,
"invalid_request_error",
f'Noul "{name}" criteria may only have "true" and "false"',
)
elif question.type == "choice":
if not isinstance(criteria, dict) or not criteria:
raise _error(
- 400, "invalid_request_error", f'Choice "{name}" needs criteria naming its options'
+ 422, "invalid_request_error", f'Choice "{name}" needs criteria naming its options'
)
if len(criteria) > MAX_CHOICES:
raise _error(
- 400, "invalid_request_error", f'Choice "{name}" has more than {MAX_CHOICES} options'
+ 422, "invalid_request_error", f'Choice "{name}" has more than {MAX_CHOICES} options'
)
elif not isinstance(criteria, list) or not 1 <= len(criteria) <= MAX_SCORE_LEVELS:
raise _error(
- 400,
+ 422,
"invalid_request_error",
f'Score "{name}" needs 1 to {MAX_SCORE_LEVELS} criteria levels',
)
+ if criteria is not None:
+ entries = criteria.items() if isinstance(criteria, dict) else enumerate(criteria)
+ for key, value in entries:
+ if value is not None and not isinstance(value, (str, dict, list)):
+ raise _error(
+ 422,
+ "invalid_request_error",
+ f'Question "{name}" criteria[{key!r}] must be text, an object, an array or null',
+ )
@router.post("/systemone")
@@ -136,10 +146,10 @@ def system_one(
)
if state_chars > MAX_STATE_CHARS:
raise _error(
- 400, "invalid_request_error", f"State is longer than {MAX_STATE_CHARS} characters"
+ 422, "invalid_request_error", f"State is longer than {MAX_STATE_CHARS} characters"
)
if len(payload.questions) > MAX_QUESTIONS:
- raise _error(400, "invalid_request_error", f"At most {MAX_QUESTIONS} questions per request")
+ raise _error(422, "invalid_request_error", f"At most {MAX_QUESTIONS} questions per request")
for name, question in payload.questions.items():
_validate(name, question)
@@ -149,5 +159,10 @@ def system_one(
except laya_runtime.Unavailable as exc:
raise _error(exc.status, exc.error_type, exc.message, exc.retry_after) from None
if result.pop("truncated"):
- raise _error(422, "invalid_request_error", "State exceeds the Laya context window")
- return JSONResponse(result)
+ raise _error(
+ 422,
+ "invalid_request_error",
+ "State and questions exceed the Laya context window. "
+ "Shorten the state or use fewer/shorter criteria.",
+ )
+ return JSONResponse(result, headers = {"x-typesafe-request-id": str(uuid4())})
diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.py
index ab576c8327a..32c992492da 100644
--- a/studio/backend/tests/test_middleware.py
+++ b/studio/backend/tests/test_middleware.py
@@ -1447,6 +1447,27 @@ class TestRemoteAccessCORS:
any page the user had open could read the local API's unauthenticated responses.
"""
+ def test_configured_cors_exposes_typesafe_request_id(self, main_module):
+ cors = next(
+ middleware
+ for middleware in main_module.app.user_middleware
+ if middleware.cls is main_module.RemoteAccessCORSMiddleware
+ )
+ app = FastAPI()
+ app.add_middleware(cors.cls, **{**cors.kwargs, "remote_access_state": app.state})
+
+ @app.get("/decision")
+ async def decision():
+ return Response(headers = {"x-typesafe-request-id": "decision-request"})
+
+ response = TestClient(app).get("/decision", headers = {"Origin": "tauri://localhost"})
+ assert response.status_code == 200
+ assert response.headers["access-control-allow-origin"] in ("*", "tauri://localhost")
+ assert response.headers["x-typesafe-request-id"] == "decision-request"
+ exposed = response.headers["access-control-expose-headers"].lower().split(",")
+ assert "x-typesafe-request-id" in {header.strip() for header in exposed}
+
+
TUNNEL = "https://demo-abc.trycloudflare.com"
@staticmethod
diff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.py
index 16e222479ba..02f0adef3a9 100644
--- a/studio/backend/tests/test_systemone.py
+++ b/studio/backend/tests/test_systemone.py
@@ -164,6 +164,38 @@ def test_answers_in_jev_wire_format(client, runtime):
assert runtime == ["laya-multilingual"]
+def test_sdk_request_ids_are_present_and_unique(client):
+ from uuid import UUID
+
+ first = _post(client).headers["x-typesafe-request-id"]
+ second = _post(client).headers["x-typesafe-request-id"]
+ assert UUID(first).version == UUID(second).version == 4
+ assert first != second
+
+
[email protected]("kind", ["noul", "choice", "score"])
[email protected]("value", [42, 1.5, False])
+def test_invalid_criterion_values_are_rejected_before_loading(client, runtime, kind, value):
+ criteria = [value, "high"] if kind == "score" else {"true": value, "false": None}
+ response = _post(client, questions = {"q": {"type": kind, "criteria": criteria}})
+ assert response.status_code == 422, response.text
+ assert "q" in response.json()["detail"]["message"]
+ assert "criteria" in response.json()["detail"]["message"]
+ assert runtime == []
+
+
[email protected]("kind", ["noul", "choice", "score"])
+def test_sdk_structured_and_null_criteria_remain_supported(client, kind):
+ values = [None, "plain text", {"weight": 3}, ["nested", False]]
+ for value in values:
+ criteria = [value, "high"] if kind == "score" else {"true": value, "false": None}
+ response = _post(client, questions = {"q": {"type": kind, "criteria": criteria}})
+ assert response.status_code == 200, response.text
+ assert laya_runtime._agent.calls[-1][1]["q"]["criteria"] == criteria
+ if kind == "score":
+ assert response.json()["answers"]["q"]["legend"]["0"] == value
+
+
def test_model_loaded_once_and_questions_forwarded(client, runtime):
_post(client)
_post(client, state = {"subject": "Charged twice"}, questions = {"q": {"type": "noul"}})
@@ -185,23 +217,23 @@ def test_named_checkpoint_swaps_the_resident_model(client, runtime):
"body, status, error_type",
[
({"model": "gpt-4"}, 400, "api_usage_error"),
- ({"questions": {"q": {"type": "maybe"}}}, 400, "api_usage_error"),
- ({"questions": {"q": {"type": "choice"}}}, 400, "invalid_request_error"),
- ({"questions": {"q": {"type": "choice", "criteria": {}}}}, 400, "invalid_request_error"),
+ ({"questions": {"q": {"type": "maybe"}}}, 422, "api_usage_error"),
+ ({"questions": {"q": {"type": "choice"}}}, 422, "invalid_request_error"),
+ ({"questions": {"q": {"type": "choice", "criteria": {}}}}, 422, "invalid_request_error"),
(
{"questions": {"q": {"type": "score", "criteria": [str(i) for i in range(11)]}}},
- 400,
+ 422,
"invalid_request_error",
),
(
{"questions": {"q": {"type": "noul", "criteria": {"yes": "x"}}}},
- 400,
+ 422,
"invalid_request_error",
),
({"images": ["data:image/png;base64,AAAA"]}, 400, "api_usage_error"),
(
{"questions": {f"q{i}": {"type": "noul"} for i in range(65)}},
- 400,
+ 422,
"invalid_request_error",
),
],
@@ -220,7 +252,7 @@ def test_malformed_requests_are_validation_errors(client, body):
assert _post(client, **body).status_code == 422
-def test_laya_refusal_becomes_a_bad_request(client, monkeypatch):
+def test_laya_refusal_becomes_a_validation_error(client, monkeypatch):
def refuse(state, questions):
raise ValueError("question 'team' options exceed head_max_len=256")
@@ -228,7 +260,7 @@ def test_laya_refusal_becomes_a_bad_request(client, monkeypatch):
laya_runtime, "_load_checkpoint", lambda c: (SimpleNamespace(predict = refuse), "cpu")
)
response = _post(client)
- assert response.status_code == 400
+ assert response.status_code == 422
assert "head_max_len" in response.json()["detail"]["message"]
@@ -239,6 +271,8 @@ def test_truncated_state_is_rejected(client, monkeypatch):
response = _post(client)
assert response.status_code == 422
assert "context window" in response.json()["detail"]["message"]
+ assert "shorten" in response.json()["detail"]["message"].lower()
+ assert "answers" not in response.json()
def test_failed_load_backs_off_and_reports_why(client, monkeypatch):
@@ -576,7 +610,7 @@ def test_misspelled_model_setting_is_not_fetched_from_the_hub(client, monkeypatc
def test_oversized_state_is_refused(client, runtime):
response = _post(client, state = "x" * (systemone.MAX_STATE_CHARS + 1))
- assert response.status_code == 400
+ assert response.status_code == 422
assert runtime == []
@@ -877,11 +911,11 @@ def test_route_module_imports_without_pep604_aliases():
def test_oversized_question_text_is_refused_before_the_model(client, runtime):
questions = {"q": {"type": "noul", "instructions": "x" * systemone.MAX_QUESTION_CHARS}}
response = _post(client, questions = questions)
- assert response.status_code == 400
+ assert response.status_code == 422
assert "longer than" in response.json()["detail"]["message"]
criteria = {f"option {i}": "y" * 200 for i in range(200)}
assert (
- _post(client, questions = {"q": {"type": "choice", "criteria": criteria}}).status_code == 400
+ _post(client, questions = {"q": {"type": "choice", "criteria": criteria}}).status_code == 422
)
assert runtime == []
assert _post(client).status_code == 200
@@ -908,6 +942,21 @@ def test_real_laya_answers_through_the_route(client, monkeypatch):
long_response = _post(client, state = "word " * 3000)
assert long_response.status_code == 422
assert "context window" in long_response.json()["detail"]["message"]
+ options_response = _post(
+ client,
+ questions = {
+ "route": {
+ "type": "choice",
+ "instructions": "Choose the best option",
+ "criteria": {f"option {i} zero one": None for i in range(255)},
+ },
+ },
+ )
+ assert options_response.status_code == 422
+ message = options_response.json()["detail"]["message"]
+ assert "route" in message and "context window" in message and "criteria" in message
+ assert "answers" not in options_response.json()
+ assert _post(client).status_code == 200
class WordTokenizer: