Validate structured inference output on DGX Spark
The inference API is already returning answers, yet the RAG page occasionally cites documents that do not exist, and automated tasks treat the string "false" as true. These failures do not necessarily come from model loading or computation. They can arise in the integration layer, where “can be parsed” is mistaken for “safe to use.” After deploying an inference service on DGX Spark, establish a structured output contract before letting results feed retrieval displays or business decisions.
Define the integration boundary
IronStp’s DGX Spark comes with NVIDIA GB10 Grace Blackwell, 128GB of LPDDR5x unified memory, and 4TB NVMe, running NVIDIA DGX OS. This article uses only the Python standard library to validate response text. It does not depend on a particular inference framework or require any additional model installation. After payment, view the connection credentials in the console and run the tests over SSH.
Divide the pipeline into three stages: receive the complete response, validate its structure and business constraints, and commit the result. Streaming output can provide a preview in the interface, but unfinished text must not trigger business actions. If a request is canceled, the connection drops, or the output is truncated, the pipeline must not reach the commit stage.
Valid JSON establishes only that the syntax is correct. It does not establish that citations are real or fields are trustworthy, much less grant the model permission to execute anything. Passing validation is no substitute for business authorization.
Start with a result containing exactly three fields: answer holds the answer, source_ids holds identifiers from the current request’s retrieval results, and needs_review indicates whether review is required. Field names, types, and length limits are defined by the server; the model response cannot extend them on its own.
Freeze the field contract
Limit the answer to 2000 characters, citations to at most 8 entries, and the complete response to 16 KiB. These are the test budgets used in this article, not hardware limits. In production, adjust them to match the display requirements, retrieval count, and request budget, and ensure that upstream and downstream components share the same contract.
The allowed source set must come from documents actually retrieved for the current request, not the entire knowledge base. Even if a document identifier exists, reject it unless it belongs to the current request’s allowed set. This prevents evidence from being carried over between requests.
Duplicate keys are another pitfall. Common JSON parsing behavior keeps the last occurrence of a field, creating ambiguity between the text visible in an audit and the value the application reads. Reject duplicates during parsing, rather than waiting until the data has been converted to a dictionary.
Save the following as output_contract.py:
import json
MAX_BYTES = 16 * 1024
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate key")
result[key] = value
return result
def reject_constant(value):
raise ValueError("Invalid JSON constant")
def validate_output(text, allowed_sources):
if not isinstance(text, str):
raise ValueError("Text required")
if len(text.encode("utf-8")) > MAX_BYTES:
raise ValueError("Response too large")
try:
obj = json.loads(
text,
object_pairs_hook=unique_object,
parse_constant=reject_constant
)
except (ValueError, RecursionError) as exc:
raise ValueError("Invalid JSON response") from exc
expected = {"answer", "source_ids", "needs_review"}
if type(obj) is not dict or set(obj) != expected:
raise ValueError("Unexpected fields")
if type(obj["answer"]) is not str:
raise ValueError("Invalid answer type")
if not obj["answer"].strip() or len(obj["answer"]) > 2000:
raise ValueError("Invalid answer length")
ids = obj["source_ids"]
if type(ids) is not list or len(ids) > 8:
raise ValueError("Invalid source list")
if any(type(item) is not str for item in ids):
raise ValueError("Invalid source type")
if len(set(ids)) != len(ids):
raise ValueError("Repeated source")
if not set(ids).issubset(set(allowed_sources)):
raise ValueError("Unknown source")
if type(obj["needs_review"]) is not bool:
raise ValueError("Invalid review flag")
if not ids and not obj["needs_review"]:
raise ValueError("Review required without sources")
return obj
There is deliberately no type coercion here. Neither the string "false" nor the integer 0 can stand in for a Boolean. An empty answer must not become a success by inserting default text, and extra fields must not be silently discarded. Strict rejection helps reveal changes to model templates or interface adapters early.
Run negative tests
A valid sample proves only that one path works. Acceptance testing must also cover duplicate keys, incorrect types, extra fields, unknown citations, truncated text, and exceeded length limits. Save the following as test_output_contract.py in the same directory as the validator.
import json
import unittest
from output_contract import validate_output
class ContractTests(unittest.TestCase):
def setUp(self):
self.base = {
"answer": "Use the retrieved procedure.",
"source_ids": ["doc-a"],
"needs_review": False
}
def test_valid(self):
result = validate_output(json.dumps(self.base), {"doc-a"})
self.assertEqual(result, self.base)
def test_rejections(self):
bad = []
for key, value in (
("needs_review", "false"),
("source_ids", ["doc-b"]),
("source_ids", ["doc-a", "doc-a"]),
("answer", ""),
("answer", "x" * 2001),
("extra", True)
):
item = dict(self.base)
item[key] = value
bad.append(json.dumps(item))
raw = json.dumps(self.base)
bad.extend([
'{"answer":"a","answer":"b"}',
raw[:-1],
"```json\n" + raw + "\n```",
raw + raw,
" " * 16385,
'{"answer":NaN}'
])
for text in bad:
with self.subTest(text=text[:80]):
with self.assertRaises(ValueError):
validate_output(text, {"doc-a"})
def test_review_without_sources(self):
item = dict(self.base, source_ids=[], needs_review=True)
self.assertEqual(validate_output(json.dumps(item), set()), item)
item["needs_review"] = False
with self.assertRaises(ValueError):
validate_output(json.dumps(item), set())
if __name__ == "__main__":
unittest.main()
Run python3 -m unittest -v. All tests should pass. Here, “pass” includes confirming that invalid samples are rejected; it does not mean every input must produce an answer. Next, temporarily remove the duplicate-key check from the validator. A test should fail. Restore the code and confirm that the tests pass again. This demonstrates that the tests actually exercise the intended validation branch.
Close off failure paths
When connecting a real inference API, place the validation function before the business commit point. A validation exception must produce a distinct failure status, not an empty dictionary or a reused answer from the previous request. Each request must carry its own allowed source set rather than relying on a mutable global set.
Reject automatic repair
Do not use a regular expression to extract the first pair of braces, and do not automatically strip code fences. These transformations hide drift in the output contract and may accidentally select an example object from explanatory text. If retries are allowed, set a fixed upper limit, regenerate the complete response, and apply exactly the same validation to the new response.
To enforce the size limit, the receiving component must also count bytes as it accumulates the response and stop receiving as soon as the limit is reached. The limit inside the function protects only the commit boundary; it cannot prevent an upstream component from first loading an enormous response into memory. Configure the server-side output token budget separately as well. A character count is not a direct substitute.
Retain acceptance evidence
Record the request identifier, model and template versions, contract version, response size in bytes, and failure category. If you need to link a record to the original response, you can store a content hash. Whether to retain the original text should depend on the business data access rules, so that retrieved material or sensitive prompts do not end up directly in ordinary logs.
Before going live, complete three checks: valid answers are committed only once; no category of invalid response reaches the business commit point; and canceled or truncated requests leave no residual results. Separately check the routing for needs_review=true to ensure that it enters the review workflow, rather than merely displaying a flag on the page and then continuing automatic execution.
Finally, preserve the semantic boundary: a valid citation identifier does not mean the cited source supports the answer, and correct field types do not mean the content is factually accurate. Structural acceptance makes the integration deterministic; fact-checking and business authorization still need to happen independently. Keeping these boundaries separate makes it possible to pinpoint the source of regressions after changing the model, template, or inference framework.
Frequently asked questions
Does JSON mode remove the need for application validation?
No. JSON mode does not replace field allowlists, type checks or citation scope checks. Validate the complete response before passing it to application logic.
Can the validator strip Markdown fences automatically?
This contract rejects fenced output rather than extracting text between braces. Failures go to bounded retries or manual review and must not become apparent successes.
AMD EPYC 7543P Dedicated Server
From $446/month