From text to data

Imagine your CRM receives hundreds of emails daily. Each contains a contact name, email, phone, company, and city buried in free-form text. Manually copying this data would take hours. With structured outputs, AI extracts it as clean JSON automatically.

From raw text to typed data

Structured outputs transform messy unstructured text into validated, schema-compliant data your code can use directly.

The structured output pipeline

Unstructured text goes in, validated structured data comes out.

json.loads() converts a JSON text string into a Python dictionary. The AI returns text (a string), but we need a dict to access individual fields. json.loads() does that conversion. The "loads" stands for "load string."

Ordering exercise: Steps for structured JSON extraction

Loading practice…

03-structured-outputs.ipynb
python
import json

def extract_json(
    prompt: str,
    system_message: str = None,
    temperature: float = 0.3
) -> dict:
    """Extract structured data as JSON."""
    messages = []

    if system_message:
        messages.append({"role": "system", "content": system_message})

    messages.append({"role": "user", "content": prompt})

    response = completion(
        model=DEFAULT_MODEL,
        messages=messages,
        temperature=temperature,
        response_format={"type": "json_object"}  # Force JSON!
    )

    return json.loads(response.choices[0].message.content)

The key addition: response_format={"type": "json_object"} guarantees the AI returns valid JSON syntax. No more parsing random text!

Let us put extract_json() to work. We will extract structured contact information from a free-form email, telling the AI exactly which fields we want.

03-structured-outputs.ipynb
python
email_text = """
Hi, I'm Sarah Chen from TechCorp in San Francisco.
You can reach me at [email protected] or
call me at (415) 555-0123. Looking forward to
discussing the partnership!
"""

prompt = f"""Extract contact info as JSON with fields:
name, email, phone, company, city

Text: {email_text}"""

contact = extract_json(prompt)
print(json.dumps(contact, indent=2))
# {
#   "name": "Sarah Chen",
#   "email": "[email protected]",
#   "phone": "(415) 555-0123",
#   "company": "TechCorp",
#   "city": "San Francisco"
# }

JSON mode extracts clean, structured data from free-form text. The prompt tells the AI exactly which fields to extract.

AI prompt: Try it with AI

Loading practice…

Quiz: Quiz

Loading practice…

That's exactly the problem JSON mode alone doesn't solve. The JSON will parse fine, but the fields might be named differently or have wrong types. That's why we add a second layer: Pydantic validation. It checks that every field exists, has the right type, and meets your constraints.

You now understand the structured output pipeline: prompt engineering plus JSON mode plus validation. Next, we will build that validation layer with Pydantic and get truly reliable AI outputs.