Structured JSON output from LLMs: schema validation and repair loops

Structured JSON output from LLMs: schema validation and repair loops

This article was prepared by the SiberAI team.

Teams often ask a chat model for “JSON only” and then parse the string as if it were a typed API. That works until a trailing comma, a markdown fence, or a truncated completion breaks the parser. With an OpenAI-compatible client pointed at SiberAI (API base path /api/siberai/v1 on siberai.net, model siber-v3), treat structured output as your contract: validate locally, repair with a bounded loop, and never trust a single completion as schema-perfect.

What the chat API guarantees (and does not)

SiberAI Chat Completions accepts a non-empty messages array, max_tokens in 1–8192 (default 4096), optional stream, and sampling fields. Extra SDK fields are not a promise that every model behaviour exists; unexpected fields are not forwarded wholesale to the inner service. A client-side “JSON mode” flag in an SDK does not by itself mean the gateway enforced your schema.

Always set model to siber-v3 and send application/json (quickstart).

Schema first, prompt second

  1. Define a JSON Schema (or equivalent) in code.
  2. Ask the model for an object that matches it—no prose wrapper.
  3. Parse; on failure, run a repair turn that includes the validator error only (not new secrets).
  4. Cap repair attempts (for example two). Then fail to a human or a safe default.
import json

def try_parse(text):
    text = text.strip()
    if text.startswith("```"):
        text = text.strip("`")
        if text.startswith("json"):
            text = text[4:].strip()
    return json.loads(text)

# On JSONDecodeError / schema error: one repair message with the error string,
# same max_tokens budget, then stop. Do not infinite-loop on 400/401.

Tie repairs to error classes

Use the error reference: do not retry 401/400 with the same bad key or body; wait on 429; after an interrupted call check usage before repeating—fully idempotent automatic production retries are not promised. A “repair” that resends a huge prompt on every 429 is a cost and rate-limit problem.

Keep keys as Bearer sai_ide_… secrets (authentication). Do not log raw completions that may contain customer data (security).

Failure modes worth testing

Broken JSON after a length cap looks like a model quality issue but is often just max_tokens. Raise the ceiling slightly or shrink the schema. Dual fields (“answer” plus “notes”) tempt the model into prose; keep one structured object. When using streams, never validate on partial buffers.

Document the repair budget in the same service runbook as your 429 policy so on-call engineers do not open unbounded loops during an incident. Pair schema ids with prompt template ids in logs (without message bodies) to debug mismatches quickly.

Validate schema version in CI with a golden JSON fixture. When the model returns markdown fences, strip them once in a shared helper so every service behaves the same. Measure how often repair loops fire; a high rate usually means the prompt or schema is unclear, not that you need more retries.

Keep repair prompts free of new customer data. If the original request was already borderline on size, a repair that re-sends the full corpus will hurt latency and cost. Prefer sending the validator error and a short reminder of the schema id.

Track repair rate as a product metric next to latency. Product home: SiberAI.

FAQ

Q: Does SiberAI guarantee schema-valid JSON on every call?
A: Treat validity as a client responsibility. Validate and use a bounded repair loop; do not assume undocumented SDK flags are enforced server-side.

Q: Should repair reuse the same API key as production traffic?
A: Prefer a staging key for experiments. Production keys should stay scoped and revocable per authentication docs.

Q: What if parsing fails after the attempt budget?
A: Fail closed: return an application error, alert, and avoid executing side effects on partial data.

Sources

Yorumlar

Bu blogdaki popüler yayınlar

SiberAI’de Chat Completions mi, Responses mi?

Связь с нативным движком SiberAI: приватный IPC, не публичный API расширений

KVKK perspektifinden yapay zeka API'lerine veri gönderirken dikkat edilecekler