Structured Data

Generate structured JSON-style outputs by prompting models to return specific fields.

This page demonstrates a lightweight technique to request structured outputs without relying on external SDK helpers. You can instruct the model to return a strict JSON object and then validate it on your side.

Python

1import os
2import json
3import requests
4
5API_KEY = os.getenv("ASI_ONE_API_KEY")
6ENDPOINT = "https://api.asi1.ai/v1/chat/completions"
7
8schema_hint = {
9 "name": "string",
10 "date": "string",
11 "participants": ["string"],
12}
13
14system = (
15 "You are a helpful assistant. Always return ONLY a single JSON object that matches the keys "
16 "and types in the provided schema hint. Do not include extra keys or commentary."
17)
18
19user = (
20 "Extract an event from this text and return JSON only.\n"
21 "Text: Alice and Bob are going to a science fair on Friday.\n"
22 f"Schema hint: {json.dumps(schema_hint)}"
23)
24
25payload = {
26 "model": "asi1-mini",
27 "messages": [
28 {"role": "system", "content": system},
29 {"role": "user", "content": user},
30 ],
31}
32
33headers = {
34 "Authorization": f"Bearer {API_KEY}",
35 "Content-Type": "application/json",
36}
37
38resp = requests.post(ENDPOINT, headers=headers, json=payload)
39resp.raise_for_status()
40content = resp.json()["choices"][0]["message"]["content"].strip()
41
42# Attempt to parse strictly as JSON
43try:
44 data = json.loads(content)
45 print(json.dumps(data, indent=2))
46except json.JSONDecodeError:
47 # Fallback: try to recover JSON substring if needed
48 start = content.find("{")
49 end = content.rfind("}")
50 if start != -1 and end != -1 and end > start:
51 recovered = content[start : end + 1]
52 print(json.dumps(json.loads(recovered), indent=2))
53 else:
54 raise

Example Output

1{
2 "name": "science fair",
3 "date": "Friday",
4 "participants": ["Alice", "Bob"]
5}

Notes

  • The model is instructed to return JSON only. Still, validate and sanitize on your side.
  • For production, enforce schemas server-side and reject invalid JSON.