█

AI/TLDR

मुझे पिलाएं कॉफ़ी
मुझे एक कॉफ़ी पिलाएँ

LLM में Structured Outputs क्या है?

समझें कि JSON mode और schema-constrained generation कैसे LLM के जवाब को भरोसेमंद structured data मानने देते हैं, जिसे आपका code सीधे इस्तेमाल कर सके।

मध्यम13 मिनट पढ़ेंअपडेट 12 जून 2026

सरल भाषा में

जब आप चैट विंडो में LLM से कोई सवाल पूछते हैं, तो सामान्य भाषा में दिया गया जवाब बिल्कुल ठीक होता है। लेकिन जब आपके code को जवाब पढ़ना होता है — उसे parse करना हो, database में store करना हो, या किसी दूसरे function को देना हो — तो सादा पैराग्राफ़ सिरदर्द बन जाता है। आपको एक अनुमानित ढांचा चाहिए: ऐसा JSON object जिसमें तय keys हों, तय value types हों, और कोई अनपेक्षित बात न हो।

LLMs में Structured Outputs — diagram
LLMs में Structured Outputs — agentic-engineer.com

Structured outputs उन features का सामूहिक नाम है जो model को ऐसा text लिखने पर मजबूर करते हैं जो आपके बताए machine-readable format में हो। सबसे आम target JSON है। model अपने आप valid JSON लिखेगा, इस उम्मीद पर रहने के बजाय (आमतौर पर लिखता है, पर हमेशा नहीं), आप API को एक schema देते हैं — हर field और उसके type का सटीक विवरण — और API गारंटी देता है कि response उससे मेल खाएगा।

इसे ऐसे समझें जैसे काउंटर पर फ़ॉर्म भरकर sandwich ऑर्डर करना बनाम शेफ़ को ज़ोर से बोलकर ऑर्डर देना। फ़ॉर्म में, ऑर्डर जाने से पहले हर खाना सही तरीके से भरना पड़ता है। ज़ोर से बोलने पर शायद बात लगभग सही पहुंचे — पर कभी-कभी शेफ़ "no onions" को "extra onions" सुन लेता है और आपका code रात 2 बजे टूट जाता है।

यह क्यों मायने रखता है

LLM reasoning और text generate करने में बेहतरीन हैं, लेकिन उनका आउटपुट स्वाभाविक रूप से unstructured होता है। जब LLM application logic चलाता है — किसी document से data निकालना, support tickets को classify करना, form की values generate करना — तो कुछ भी आगे होने से पहले आपको उसका आउटपुट parse करना पड़ता है। Structured outputs के बिना यह parsing नाज़ुक होती है।

Structured outputs के बिना आम गड़बड़ियों में शामिल हैं: missing keys जिन्हें model "भूल" गया, hallucinated enum values जो आपकी allowlist में नहीं हैं, nested fields जो कभी दिखते हैं कभी नहीं, और closing brace के बाद बचा हुआ सादा text जो JSON.parse को तोड़ देता है। इन सबके लिए defensive code और retries चाहिए, जिनमें समय और पैसा दोनों लगते हैं।

व्यावसायिक असर भी असली है। अनुमानित output schemas production pipelines में runtime errors की पूरी श्रेणियां खत्म कर देते हैं, retry का खर्च घटाते हैं, और defensive parsing वाले boilerplate को छोड़ना सुरक्षित बना देते हैं। OpenAI के case studies के अनुसार, Shopify, Zapier और Retool की टीमों ने structured outputs अपनाने के बाद API parsing errors में 90%+ की कमी दर्ज की।

Structured outputs उपयोग के मामलों की पूरी श्रेणी भी खोलते हैं: data extraction pipelines, automated form filling, multi-step agent workflows जो चरणों के बीच structured नतीजे पास करते हैं, और function calling जहां tool arguments को एक सटीक interface से मेल खाना पड़ता है। इन सभी में, schema की गारंटी ही भरोसेमंद product और नाज़ुक prototype के बीच का फ़र्क है।

यह कैसे काम करता है

Structured outputs बनाने में दो पूरक तरीके इस्तेमाल होते हैं: server side पर constrained decoding, और client side पर schema validation। दोनों को समझने से आपको सही तरीका चुनने और failures debug करने में मदद मिलती है।

Constrained decoding

हर step पर LLM सभी संभावित अगले tokens पर एक probability distribution बनाता है। आमतौर पर sampler उस distribution में से स्वतंत्र रूप से चुनता है। Constrained decoding में inference engine हर ऐसे token को mask कर देता है जो output को schema के खिलाफ ले जाए। अगर schema कहता है कि अगली value true या false होनी चाहिए, तो "hello" जैसे tokens sampling से पहले distribution में शून्य कर दिए जाते हैं। Model को कभी गलत value आज़माने का मौका ही नहीं मिलता।

यह JSON schema से निकाले गए formal grammar के ज़रिए लागू होता है। grammar output की हर position पर देखती है कि कौन-से characters valid हैं — {"status": के बाद grammar जानती है कि सिर्फ string या number आ सकता है, इसलिए कोई और token कभी sample नहीं होता। नतीजा यह है कि output निर्माण से ही structurally valid होता है, बाद में filtering करके नहीं।

API surface: response_format

API की ओर, schema को response_format parameter में पास किया जाता है। OpenAI का तरीका (मौजूदा GPT models पर उपलब्ध) पूरे JSON Schema object के साथ type: "json_schema" इस्तेमाल करता है:

OpenAI Python SDK — schema-constrained outputpython
from openai import OpenAI
import json

client = OpenAI()  # reads OPENAI_API_KEY from env

response = client.chat.completions.create(
    model="gpt-5.5",
    messages=[
        {"role": "system", "content": "Extract the event details from the user message."},
        {"role": "user", "content": "Team standup on Friday at 10am in the Hudson room."}
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "Event",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "title":    {"type": "string"},
                    "day":      {"type": "string"},
                    "time":     {"type": "string"},
                    "location": {"type": "string"}
                },
                "required": ["title", "day", "time", "location"],
                "additionalProperties": False
            }
        }
    }
)

event = json.loads(response.choices[0].message.content)
print(event)  # {"title": "Team standup", "day": "Friday", ...}

Pydantic और Zod: आपके types से schema

JSON Schema हाथ से लिखना उबाऊ और गलती की आशंका वाला काम है। आधिकारिक SDKs आपको वही type system इस्तेमाल करके schema घोषित करने देते हैं, जो आप पहले से इस्तेमाल कर रहे हैं। Python में सीधे Pydantic model class पास करें; SDK उसे अपने आप JSON Schema में serialize कर देता है। TypeScript में Zod का इस्तेमाल करें। आउटपुट पहले से parsed और type-safe आता है — JSON.parse की ज़रूरत नहीं:

OpenAI + Pydantic — type-safe structured outputpython
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()

class Event(BaseModel):
    title: str
    day: str
    time: str
    location: str

# parse() sends the schema and parses the response in one call.
response = client.beta.chat.completions.parse(
    model="gpt-5.5",
    messages=[
        {"role": "system", "content": "Extract event details."},
        {"role": "user",   "content": "Team standup on Friday at 10am in the Hudson room."}
    ],
    response_format=Event,
)

event: Event = response.choices[0].message.parsed
print(event.title, event.day)  # already typed — no dict key access needed

Anthropic: structured output के रूप में tool use

Anthropic का Claude API दो रास्तों से structured outputs सपोर्ट करता है। पहला है tool call को मजबूर करना: एक tool परिभाषित करें जिसका input schema आपका वांछित JSON ढांचा हो, फिर model को उसे कॉल करने के लिए tool_choice सेट करें। Tool के arguments ही structured output हैं — हमेशा valid JSON, हमेशा schema से मेल खाते हुए। दूसरा रास्ता एक समर्पित beta header (anthropic-beta: structured-outputs-2025-11-13) है, जो direct JSON output के लिए OpenAI जैसे तरीके से मिलता-जुलता response_format सक्षम करता है।

Anthropic Python SDK — structured output के रूप में forced tool callpython
import anthropic, json

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env

extract_tool = {
    "name": "extract_event",
    "description": "Extract event details from the message.",
    "input_schema": {
        "type": "object",
        "properties": {
            "title":    {"type": "string"},
            "day":      {"type": "string"},
            "time":     {"type": "string"},
            "location": {"type": "string"}
        },
        "required": ["title", "day", "time", "location"]
    }
}

message = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=1024,
    tools=[extract_tool],
    tool_choice={"type": "tool", "name": "extract_event"},  # force the call
    messages=[{"role": "user", "content": "Team standup on Friday at 10am in the Hudson room."}]
)

event = message.content[0].input  # already a dict, not raw JSON string
print(event["title"], event["day"])

Provider तुलना और सीमाएं

हर बड़ा LLM provider किसी न किसी रूप में structured output सपोर्ट करता है, पर गारंटी और syntax अलग-अलग हैं। इन कमियों को जानने से production में हैरानी से बचा जा सकता है।

प्रोवाइडरFeature का नामकार्यप्रणालीSchema formatसख़्त गारंटी?
OpenAI GPT-5 familyStructured OutputsConstrained decodingresponse_format के ज़रिए JSON Schemaहां, strict: true के साथ
Anthropic ClaudeTool use / structured outputs betaConstrained decoding (beta) या forced tool callTool input के रूप में JSON Schemaहां (beta) / हां (tool use)
Google GeminiControlled generationConstrained decodingresponse_mime_type के ज़रिए JSON Schemaहां
MistralJSON modeSampling guidanceresponse_format: json_objectValid JSON, कोई schema नहीं
CohereStructured OutputsConstrained decodingresponse_format के ज़रिए JSON Schemaहां

जानने योग्य schema सीमाएं

हर provider का constrained decoder JSON Schema की हर सुविधा सपोर्ट नहीं करता। ध्यान रखने योग्य आम सीमाएं:

  • additionalProperties: false आमतौर पर ज़रूरी है — इसके बिना OpenAI का strict mode चालू नहीं होगा।
  • Recursive schemas (जैसे कोई tree node जो खुद को refer करता हो) reject हो सकते हैं या depth limits लग सकते हैं।
  • anyOf / oneOf / if-then-else आंशिक रूप से सपोर्ट होते हैं; इन पर भरोसा करने से पहले provider docs देखें।
  • सभी properties required के अंतर्गत सूचीबद्ध होनी चाहिए जब OpenAI का strict: true इस्तेमाल हो — optional fields के लिए इसके बजाय null के साथ union इस्तेमाल करना होगा।
  • $ref और $defs साझा sub-schemas के लिए OpenAI पर काम करते हैं, पर दूसरी जगह सपोर्ट न हों।

Structured outputs बनाम function calling

दोनों features आपस में मिलते हैं, पर उनके उद्देश्य अलग हैं। Structured outputs (सीधे response_format) content field में JSON response देते हैं — तब काम आते हैं जब आपको सिर्फ़ data वापस चाहिए। Function calling (tool use) LLM को एक agent के रूप में दिखाता है जो structured arguments के साथ एक function कॉल करता है — तब उपयोगी है जब model तय करता है कि कौन-सा action लेना है और किन parameters के साथ। अंदरूनी तौर पर, कई providers structured outputs को function calling वाले उसी constrained decoding engine से लागू करते हैं। वैचारिक अंतर यह है: आपको data extraction चाहिए (structured outputs) या action dispatch (function calling)?

और गहराई में

परफ़ॉर्मेंस के ट्रेडऑफ़

Constrained decoding हर token step में थोड़ा overhead जोड़ता है — token mask निकालने के लिए grammar automaton को चलाना पड़ता है। सरल flat schemas के लिए यह नगण्य है। कई enum values वाले गहरे nested schemas के लिए automaton बड़ा हो सकता है और पहले token की latency नापने लायक बढ़ती है। व्यवहार में यह overhead उस retry की लागत से कहीं कम है जो अमान्य आउटपुट से होता है; यह ट्रेडऑफ़ लगभग हमेशा schema enforcement के पक्ष में जाता है।

Structured outputs से reasoning को नुकसान कब होता है

सख़्त structure थोपने से model की किसी समस्या पर reasoning करने की क्षमता कट सकती है। जो model तुरंत {"answer": "..."} बनाने पर मजबूर हो, उसके पास जवाब पक्का करने से पहले step by step सोचने की जगह नहीं होती। स्थापित पैटर्न है पहले chain-of-thought, आख़िर में schema: model से एक free-text reasoning field में (या अलग message में) सोचने को कहें, फिर structured जवाब बनवाएं। कुछ schemas इसी के लिए एक reasoning string field साफ़ तौर पर शामिल करते हैं। chain-of-thought पैटर्न structured outputs के साथ स्वाभाविक रूप से जुड़ता है, क्योंकि सोच को ही एक schema field बनाया जा सकता है।

Streaming और partial JSON

आप streaming को structured outputs के साथ जोड़ सकते हैं — model JSON को token दर token emit करता है। ट्रेडऑफ़ यह है कि आंशिक रूप से मिला JSON object valid JSON नहीं होता और stream पूरा होने तक parse नहीं किया जा सकता। कुछ libraries (जैसे Python के लिए instructor) incremental JSON parsers लागू करती हैं, जो fields आते ही आंशिक रूप से पूरे objects emit करती हैं, जिससे UI progressively अपडेट हो सकता है। यह एक उन्नत पैटर्न है; ज़्यादातर use cases के लिए parse करने से पहले पूरा stream इकट्ठा करें।

instructor लाइब्रेरी

Python developers के लिए, open-source instructor लाइब्रेरी OpenAI और Anthropic clients को लपेटती है, ताकि structured outputs और भी आसानी से इस्तेमाल हो सकें। यह schema serialization संभालती है, request भेजती है, response parse करती है, और अगर model का आउटपुट मेल न खाए तो validation error के फ़ीडबैक के साथ अपने आप retry करती है (उन providers के लिए उपयोगी जिनमें native constrained decoding नहीं है)। यह व्यापक रूप से अपनाई जाती है और भारी data extraction काम के लिए अच्छा शुरुआती बिंदु है।

Schema design की सर्वोत्तम प्रथाएं

  • जहां संभव हो schemas को flat रखें — nested objects constrained-decoding के edge cases की संभावना बढ़ाते हैं।
  • श्रेणीगत fields के लिए enums इस्तेमाल करें — enums पूरी तरह constrained होते हैं; खुले strings फिर भी अप्रत्याशित values गढ़ सकते हैं।
  • हर field में description जोड़ें — model field descriptions को निर्देश की तरह पढ़ता है; constrained decoding होने पर भी ये गुणवत्ता तय करती हैं।
  • प्रतिकूल inputs से test करें — जटिल schemas latency spikes या refusals ला सकते हैं; production से पहले उन्हें परखें।
  • Schemas को version करें — जैसे-जैसे application बदलती है, पुराने सहेजे गए outputs नए schema से मेल नहीं खा सकते; migration की योजना बनाएं।

अक्सर पूछे जाने वाले प्रश्न

JSON mode और structured outputs में क्या फ़र्क है?

JSON mode (पुराना "response_format": {"type": "json_object"}) model से syntactically valid JSON बनवाता है, पर यह नहीं रोकता कि कौन-सी keys या types आएं। Structured outputs इससे आगे जाते हैं: आप JSON Schema देते हैं, और API गारंटी देता है कि response उससे बिल्कुल मेल खाए — सही field नाम, सही types, कोई required key गायब नहीं। Structured outputs सख़्ती से ज़्यादा मज़बूत हैं।

LLM से JSON लौटाने के लिए उसे कैसे मजबूर करें?

OpenAI के साथ, अपनी API call में strict: true के साथ response_format={"type": "json_schema", "json_schema": {...}} पास करें। Anthropic के साथ, या तो एक tool परिभाषित करें जिसका input schema आपका वांछित ढांचा हो और tool_choice से model को उसे कॉल करने पर मजबूर करें, या structured-outputs beta header इस्तेमाल करें। Gemini के साथ response_mime_type को application/json सेट करें और schema दें। तीनों तरीके valid, schema से मेल खाने वाले JSON की गारंटी देते हैं।

क्या structured output Pydantic या Zod के साथ काम करता है?

हां। OpenAI Python SDK में client.beta.chat.completions.parse() method है, जो सीधे Pydantic model class स्वीकार करता है — यह class को JSON Schema में serialize करता है, request भेजता है, और response को पहले से typed Pydantic object के रूप में parse करके लौटाता है। TypeScript SDK Zod schemas के साथ यही करता है। production इस्तेमाल के लिए यही अनुशंसित रास्ता है।

क्या structured outputs optional fields संभाल सकते हैं?

हां, पर syntax उल्टा-सा लगता है। OpenAI के strict: true में हर property required array में होनी चाहिए। व्यवहार में किसी field को optional बनाने के लिए उसका type ["string", "null"] घोषित करें (null के साथ union) — तब value न होने पर model null emit कर सकता है। Strict mode में किसी field को required से बाहर छोड़ने की अनुमति नहीं है।

क्या structured outputs इस्तेमाल करने से model की reasoning गुणवत्ता घटती है?

घट सकती है, अगर आप model को तुरंत एक कसकर संरचित जवाब देने पर मजबूर करें। इसका समाधान है अपने schema में पहली property के रूप में एक reasoning field (type: string) रखना, ताकि अंतिम जवाब वाली fields भरने से पहले model सोच सके। वैकल्पिक रूप से, दो-call पैटर्न अपनाएं: पहली call free-text reasoning बनाए, दूसरी call उसी reasoning से structured extraction तैयार करे।

क्या मैं structured outputs को token दर token stream कर सकता हूं?

तकनीकी रूप से हां — model JSON के characters एक बार में एक token emit करता है। पर आंशिक रूप से मिली JSON string अमान्य होती है और stream पूरा होने तक unparseable रहती है। ज़्यादातर use cases के लिए पूरा response आने तक इंतज़ार करना चाहिए। अगर progressive UI अपडेट चाहिए, तो instructor जैसी library इस्तेमाल करें जो incremental JSON parsing लागू करती है, या अपना schema ऐसा बनाएं कि अर्थपूर्ण fields object में जल्दी आएं।

आगे पढ़ें