Lesson 30 — Beginner

Structured Outputs — JSON & Schemas

Production code ko chahiye guaranteed parse-able data — JSON jo hamesha schema fit ho. Is lesson mein hum "sirf JSON do" prompt ki limit, schema-constrained generation, JSON mode, Pydantic schemas aur generate → validate → repair workflow dekhenge.

⏱ 20 min• Beginner• LangChain Fundamentals

Structured output kya hai

WHAT

Structured output matlab model ka jawab ek fixed shape mein — keys, types, enums — taki tum seedha code mein use kar sako. Prompt mein "sirf JSON" likhne se better hai: schema-constrained generation API level par enforce hoti hai.

WHEN

Jab bhi downstream code parse kare — DB insert, UI render, routing, API response. Free-text aaya toh poora pipeline toot jaata hai.

WHERE

Classification labels, field extraction (invoice, resume), ticket triage, agent tool arguments — lagbhag har data-returning call yahin se guzarti hai.

Level teen hain: prompt-level ("sirf JSON likho" — koi guarantee nahi), JSON mode (syntax valid hoga, schema nahi), schema-constrained (jawab diye gaye schema mein hi banega). Production ke liye aakhri wala.

Schemas — JSON Schema aur Pydantic

from pydantic import BaseModel, Field
from typing import Optional
from enum import Enum

class Urgency(str, Enum):
    low = "low"
    medium = "medium"
    high = "high"

class Ticket(BaseModel):
    ticket_id: str                       # required
    category: str                        # required
    urgency: Urgency                     # enum — sirf 3 values chalengi
    summary: str
    needs_human: bool = False            # optional with default
    tags: list[str] = []                 # list
    customer: Optional[dict] = None      # nested, optional

print(Ticket.model_json_schema())       # provider ko yahi chahiye
Pro Tip: model_json_schema() print karke khud dekho — yahi JSON provider ko jaata hai. Schema samajhne ka sabse tez tareeka hai, documentation se bhi tez.

JSON mode vs schema-constrained

# LEVEL 2 — JSON mode: syntax valid JSON milega, schema ki guarantee nahi
resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    response_format={"type": "json_object"},
)

# LEVEL 3 — schema-constrained: jawab diye gaye schema mein hi banega
schema = Ticket.model_json_schema()
resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "ticket", "schema": schema, "strict": True},
    },
)

# LANGCHAIN — same cheez ek line mein
structured_llm = llm.with_structured_output(Ticket)
ticket = structured_llm.invoke("Refund wala ticket: ORD-4821, urgent")
Syntactic vs semantic: Schema force karne se JSON sahi SHAPE ka hota hai — lekin uske andar likha fact galat ho sakta hai. Validation shape check karti hai, sach nahi. Dono chahiye.

Generate → validate → accept / repair / reject

from pydantic import ValidationError

def generate_ticket(text, retries=2):
    messages = [{"role": "user", "content": f"Classify: {text}"}]
    for attempt in range(retries + 1):
        raw = call_structured(messages)               # schema-forced call
        try:
            return Ticket.model_validate_json(raw)     # ACCEPT
        except ValidationError as e:
            if attempt == retries:
                break                                  # REJECT
            messages.append({"role": "assistant", "content": raw})
            messages.append({"role": "user", "content":
                f"Ye JSON schema se match nahi hua:\n{e}\nSahi karo."})  # REPAIR
    raise ValueError("schema ke bahar jawab — fallback bhejo")
Workflow yaad rakho: generate → validate → accept / repair / reject. Schema ke baad bhi validation karo, aur har rejection ko log karo — warna production mein chup-chaap bad data jaata rehta hai.

Exercise

Question: Python mein model class se schema define karne ki popular library kaunsi hai?

Question: JSON mode kya guarantee deta hai — valid syntax ya schema ki guarantee?

Question: JSON sahi shape ka ho par andar ka data galat ho — is farq ko syntactic validity aur kya kehte hain?

Question: Validate fail hone par output ko dobara theek karwane ko kya kehte hain? (ek word)

Common mistakes

Desi example: Bank form vs chitthi

Bank form mein har box ka naam aur type fix hai — galat cheez uske bahar nahi ja sakti. Khuli chitthi mein sab kuch likh sakte ho — padhne wala khud guess karta hai. Schema wahi form hai:

python
# Chitthi (prompt-only): tum khud padho, tum khud guess karo
line = "Urgency high hai, billing issue, jaldi dekho"

# Form (schema): har box ka naam aur type fix
form = {"ticket_id": "T-42", "category": "BILLING", "urgency": "high"}
Ticket.model_validate(form)   # box ke bahar kuch nahi ja sakta
Interview angle — yahan se sawaal aate hain
  • Q: JSON mode aur schema-constrained output mein farq? — JSON mode sirf valid syntax deta hai; schema mode diye gaye structure mein hi generate karwata hai.
  • Q: Pydantic model ka faayda kya hai? — Schema ek hi jagah define hota hai — validation, SDK call aur docs teeno isi se bante hain.
  • Q: Valid JSON hone ke baad bhi output kyun galat ho sakta hai? — Syntactic validity alag hai semantic correctness se; business rules alag se check karo.
  • Q: Invalid output aaye toh kya karoge? — Raw log karo, error de kar repair call, limited retries, phir reject ya fallback.
Lesson complete?

Structured outputs clear. Agla lesson — Function & Tool Calling — mein dekhenge model ko asli kaam karwane ke liye tools kaise dete hain.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course