weightsapi.INFERENCEConsole
Navigation
Validated structured output

Validated structured output

A strict schema plus independent validation.

Requirements#

Python 3.11 or newer. No additional packages. Set WEIGHTSAPI_API_KEY to your own key. AI access requires sign-in, one confirmed top-up of at least USD 100, an authorized API key and enough available credit for the request. Each later top-up also has a USD 100 minimum; smaller remaining balances stay usable when they cover the request. Credit requires transaction verification. Check service status for model availability before sending traffic.

Run the recipe#

import os, json, urllib.request
BASE = os.environ.get("WEIGHTSAPI_BASE_URL", "https://weightsapi.com/v1")
KEY = os.environ["WEIGHTSAPI_API_KEY"]
def chat(messages, model="Qwen/Qwen3-32B", **options):
    payload = dict(model=model, messages=messages, max_tokens=512, **options)
    req = urllib.request.Request(BASE+"/chat/completions", json.dumps(payload).encode(),
        {"Authorization": "Bearer "+KEY, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=120) as response:
        return json.load(response)
schema = {"type":"object","properties":{"language":{"type":"string"},"summary":{"type":"string"}},
          "required":["language","summary"],"additionalProperties":False}
r = chat([{"role":"user","content":"Summarize: Bonjour, je construis une API."}],
    response_format={"type":"json_schema","json_schema":{"name":"summary","strict":True,"schema":schema}})
choice = r["choices"][0]
if choice["finish_reason"] != "stop": raise ValueError("Incomplete output")
value = json.loads(choice["message"]["content"])
if set(value) != {"language","summary"} or not all(isinstance(v,str) for v in value.values()):
    raise ValueError("Schema validation failed")
print(value)

Before production#

Bound concurrency and retries, validate outputs, and handle errors before exposing the workflow to users.