अध्याय 8 · Application engineering 8.3
Structured output aur function calling: JSON mode se constrained decoding tak
Program se model output reliably use karane ke liye: prompt agreement, JSON mode, constrained decoding aur validation + retry. Yeh page vocabulary mask se format guarantee, function calling ke round-trips, aur format constraints ka reasoning par asar batata hai।
यह पृष्ठ पूरा करने पर आप
- Bataayein prompt agreement, JSON mode, constrained decoding aur "validation + retry" chaar tiers har ek kya guarantee karte hain, kya nahi।
- Samjhayein constrained decoding vocabulary mask se format kaise guarantee karti hai, aur standard library se step-by-step ek chalne wala constrainer likhein।
- Strict-mode rules ke mutabiq JSON Schema likhein, aur jaanein format constraints inference kyun dheema kar sakte hain।
- Function calling ke message round-trips likhein, aur ek chalne wala minimal calling loop banayein।
इस पृष्ठ पर
- Chaar tiers
- Constrained decoding
- Har step sirf valid tokens
- Rules allowed set kaise bante hain
- Khud karein: mask step-by-step
- Standard library se likha ja sakta hai
- Step-by-step mask distribution badal deta hai
- Schema likhna: strict mode ke rules aur design
- Types se schema generate karein, kuch traps pakdein
- Constraint sirf format dekhta hai
- Format constraints reasoning ko dheema karti hain?
- Function calling
- Do providers ke message shapes
- Ek chalne wala minimal loop
- Practice checklist
- Do checks se synthetic structured data validate karna
- Summary aur exercises
- Exercises
- Aage padhein
- अक्सर पूछे जाने वाले सवाल
Program se model output reliably use karane ke liye sirf prompt mein “JSON output karo” kaafi nahi. Strong guarantee decoding phase se aati hai: har token se pehle format todne wale tokens mask kar do - ise constrained decoding kehte hain. Function calling uske upar ek message protocol jodta hai: model sirf function name aur JSON parameters likhta hai, aapka code execute karta hai, result wapas model ko. Yaad rakhne wali boundary: format valid = content sahi, aisa nahi hai; sakht format constraints reasoning ko bhi dheema kar sakte hain - isliye validation, retry aur evaluation teeno zaroori hain।
Chaar tiers
Neeche ke chaar tiers alag cheezein guarantee karte hain; combine bhi ho sakte hain:
| Tier | Kaise | Guarantee | Guarantee nahi |
|---|---|---|---|
| Prompt agreement | Prompt mein format likho, ek-do examples do | Sirf probability badhta hai, koi guarantee nahi | Mismatched brackets, extra pleasantries, missing fields, wrong types |
| JSON mode | API ka JSON switch on karo (OpenAI json_object) | Output valid JSON hai | Aapke schema ke conform ka guarantee nahi |
| Schema constraint | JSON Schema do; decoding mein sirf valid tokens (OpenAI Structured Outputs aur strict function calls; Anthropic strict tools) | Valid JSON, supported schema subset ke conform | Values sahi hain ya nahi; truncate/refuse par valid output nahi |
| Validation + retry | Parse ke baad schema aur business rules se check; fail par error wapas model ko, retry | Syntax aur semantic errors pakde aur fix ho sakte hain | Ek call extra; retry ka safalta guarantee nahi |
OpenAI docs pehle do ka farq saaf likhte hain: dono valid JSON guarantee karte hain, par sirf Structured Outputs schema guarantee karta hai; jahan ho sake wahan Structured Outputs. JSON mode ki ek aur trap: conversation mein JSON explicitly manga hona chahiye, warna model khaali likhta reh sakta hai token limit tak (context mein “JSON” shabd hi na ho to API error deti hai)।
Selection order: schema constraint ho sake to wahi; model/API support na kare ya format supported JSON Schema subset se bahar ho to JSON mode; har tier mein validation aur retry rakhein - aage dikhega, constraint sirf format dekhta hai।
Constrained decoding
Har step sirf valid tokens
Language model har step poore vocabulary ke logits deta hai; softmax aur probability sampling. Constrained decoding sirf ek cheez extra karti hai: target format aur ab tak ka text se is step ka allowed token set nikaalo, set ke bahar ke logits ko , phir softmax aur sampling. Normalization ke baad:
Har step sirf se sample hota hai, isliye output hamesha target format ka valid prefix - beech mein galat nahi likh sakta. Asli engineering dikkat: jaldi kaise mile।
Rules allowed set kaise bante hain
Regex aur fixed templates character-level finite state machine (DFA) mein compile ho sakte hain. Ek token ek string hai: state se shuru karke uske characters ek-ek karke chal sake (har character ka edge ho) to token allowed hai; chalne ke baad naya state।
Dhyan: token = character nahi. Ek token ek saath syntax ke kai elements likh sakta hai - jaise ": " key ka closing quote, colon, space aur value ka opening quote, sab ek saath - isliye automaton ko poora token chalana hota hai, sirf pehla character dekh kar nahi।
“Har state ke allowed tokens aur landing states” pehle se ek index mein - yehi Outlines (Willard aur Louf, 2023) karta hai: index sirf grammar aur vocabulary par nirbhar - ek baar banana kaafi; har step current state se lookup, average cost constant. Naive tareeka har step poore vocabulary ko ek-ek karke check karta - aur vocabulary 128k tak ho sakti hai (Llama 3.1; XGrammar paper se)।
JSON arbitrary nesting allow karta hai; bracket pairing ke liye stack chahiye - regex/DFA ki power se bahar; context-free grammar (CFG) + pushdown automaton chahiye; stack content ke combinations itne ki sab precompute nahi ho sakta. XGrammar (Dong adi, 2024) ka tareeka: vocabulary do classes mein - stack-independent tokens preprocessing mein check karke cache; stack-dependent tokens runtime par check; persistent stack, aur grammar computation ko GPU computation ke saath overlap. Paper report: Llama-3.1 ke JSON grammar par stack-dependent tokens 1% se kam (128k mein sirf 1134); existing solutions se max 100x speedup; inference engines ke saath structured generation ka overhead lagbhag zero।
API ke JSON Schema ko bhi pehle aise structures mein process kiya jaata hai. Anthropic docs kehte hain strict tool ka input_schema grammar mein compile hota hai; compile result max 24 hours cache (last use se); OpenAI docs yaad dilate hain ki kisi bhi schema ki pehli request par extra processing latency hai, same schema ki aage ki requests par nahi. Isliye har request mein alag schema dynamically na banao - schema stable rakhein।
Khud karein: mask step-by-step
Neeche wale widget mein vocabulary sirf 30 tokens, target format {"name": "<lowercase letters>+", "age": <digits>+}. Language model ke scores hand-set illustrative values hain, real model se nahi aaye।
Yeh try karein:
- “Constrained decoding” on karke baar-baar “next token” - dekhein har step kaun se tokens kat-te hain, bachi hui probability kaise renormalize hoti hai।
- Constraint off karke kai baar generate - common deviations dekhein: greeting se shuru, number English word mein,
}ke baad code fence। - “1000x run” - alag temperatures par validity rate compare. Temperature jitna high, model illegal tokens ko utni zyada probability - bina constraint validity utni fast girti hai।
- “Index sigma” expand karein - har state ke paas kaun se tokens hain।
Standard library se likha ja sakta hai
Wahi mechanism sirf standard library se. Target format aur vocabulary widget jaise hi; “language model” pure random logits - validity poori tarah mask par nirbhar।
import json
import math
import random
from collections import Counter
# target format: {"name": "<lowercase>+", "age": <digits>+"} - "fixed text + char class" se bana
SEGMENTS = [
("lit", '{"name": "'),
("cls", "abcdefghijklmnopqrstuvwxyz"),
("lit", '", "age": '),
("cls", "0123456789"),
("lit", "}"),
]
def build_dfa(segments):
"""returns (edges, accept): edges[state][char] = next state; missing edge = illegal."""
edges, cur = [{}], 0
for kind, spec in segments:
if kind == "lit":
for ch in spec:
edges.append({})
edges[cur][ch] = len(edges) - 1
cur = len(edges) - 1
else: # char class, kam se kam ek baar: ek self-loop state mein ruk jaata hai
edges.append({})
loop = len(edges) - 1
for ch in spec:
edges[cur][ch] = loop
edges[loop][ch] = loop
cur = loop
return edges, cur
VOCAB = ['{', '{"', '"', 'name', 'age', '":', '": ', '": "', '",', '", "', ' ', '}',
'al', 'ice', 'alice', 'bob', 'Bob', 'thirty', '30', '3', '7', '42',
'Sure', 'Here', '\n', '```', 'json', ',', ':', '<eos>']
def build_index(edges, accept, vocab):
"""index[state] = {token_id: state after eating this token}; sirf poore khane wale tokens."""
index = []
for state in range(len(edges)):
row = {}
for i, tok in enumerate(vocab):
if tok == "<eos>": # eos sirf "already complete" state mein allowed
if state == accept:
row[i] = state
continue
s = state
for ch in tok: # token ke kai characters - poora chalna hai
s = edges[s].get(ch)
if s is None:
break
if s is not None:
row[i] = s
index.append(row)
return index
edges, accept = build_dfa(SEGMENTS)
index = build_index(edges, accept, VOCAB)
print("DFA states:", len(edges), "vocab size:", len(VOCAB), "index entries:", sum(len(r) for r in index))
for state in (0, 1, 10, 21, 22, 23):
print(f"state {state:2d} allowed:", [VOCAB[i] for i in index[state]])
def sample(logits, allowed, rng):
"""NotAllowed tokens ka logit -inf, phir softmax aur sampling."""
masked = [z if i in allowed else -math.inf for i, z in enumerate(logits)]
top = max(masked)
weights = [math.exp(z - top) for z in masked]
return rng.choices(range(len(logits)), weights=weights)[0]
def generate(rng, constrained, max_steps):
state, out = 0, []
for _ in range(max_steps):
logits = [rng.gauss(0, 2) for _ in VOCAB] # kuch na jaanne wala "model": pure random logits
allowed = index[state].keys() if constrained else range(len(VOCAB))
token = sample(logits, allowed, rng)
if constrained:
state = index[state][token]
if VOCAB[token] == "<eos>":
break
out.append(VOCAB[token])
return "".join(out)
def judge(text):
"""complete / prefix (valid par incomplete) / invalid."""
s = 0
for ch in text:
s = edges[s].get(ch)
if s is None:
return "invalid"
if s == accept:
json.loads(text) # asli JSON parser bhi padh leta hai
return "complete"
return "prefix"
rng = random.Random(7)
for _ in range(3):
print(repr(generate(rng, True, 40)))
for constrained, budget in [(False, 40), (True, 40), (True, 80)]:
rng = random.Random(0)
tally = Counter(judge(generate(rng, constrained, budget)) for _ in range(2000))
print(f"constrained={constrained!s:5} max {budget} steps:", dict(tally))
DFA states: 24 vocab size: 30 index entries: 49
state 0 allowed: ['{', '{"']
state 1 allowed: ['"']
state 10 allowed: ['name', 'age', 'al', 'ice', 'alice', 'bob', 'thirty', 'json']
state 21 allowed: ['30', '3', '7', '42']
state 22 allowed: ['}', '30', '3', '7', '42']
state 23 allowed: ['<eos>']
'{"name": "agealage", "age": 3074273730423374233}'
'{"name": "alicealicealicebobicename", "age": 42}'
'{"name": "alicenameicebob", "age": 73307}'
constrained=False max 40 steps: {'invalid': 1928, 'prefix': 72}
constrained=True max 40 steps: {'complete': 1987, 'prefix': 13}
constrained=True max 80 steps: {'complete': 2000}
Note: numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।
Teen observations:
- 24 states x 30 tokens = 720 (state, token) combinations; sirf 49 chalte hain. Har step sirf
index[state]ke kuch tokens mein se sample hota hai। - Kuch na jaanne wala random “model”, bina constraint: 2000 mein ek bhi complete valid nahi - 1928 baar beech mein illegal character, baaki 72 baar likhne se pehle hi eos (unmein 68 baar shuru mein hi eos); bacha sirf valid prefix. Constraint ke saath 2000 mein sab valid prefix, unmein 1987 complete।
- Constraint ke saath bhi 13 incomplete - wajah: 40 steps khatam, likhna baaki. Random “model” letters/digits mein ghumta rehta hai, eos der se likhta hai. Limit 80 par 2000 mein sab complete. Constrained decoding har step valid karta hai, complete hona nahi guarantee karta; real API mein
max_tokenstruncation isi ka hai - aage phir।
Step-by-step mask distribution badal deta hai
Per-step mask sirf current step dekhta hai, aage nahi - isliye iski distribution “saare valid outputs mein model ki apni probability se sampling” se alag hai. Minimal example: pehle step par model A ya B, har ek 0.5. A ke baad sirf x valid, model use sirf 0.1 deta hai (baaki 0.9 illegal); B ke baad sirf y valid, model use 0.9।
| Sampling method | Ax ki probability | By ki probability |
|---|---|---|
| Do valid sequences mein model probability normalize | 10% | 90% |
| Per-step mask | 50% | 50% |
Do valid sequences ki model probabilities aur ; normalize karke 10% aur 90%. Per-step mask mein pehle step A aur B dono allowed, har ek 50%; doosre step par ek hi valid token - renormalize karke 1. Result 50-50।
Model “samajhta” hai ki A ke baad valid likhna lagbhag namumkin hai, par mask use wapas kheench leta hai. Park adi (2024) is phenomenon ko constrained decoding ki model distribution distortion kehte hain, aur sampling ko “grammar constraint ke andar wali model distribution” se align karne wala ASAp algorithm dete hain. Practical yaad: prompt aur field descriptions aise hon ki model khud valid content likhna chahe; mask aakhri safety net hai; jab forced low-probability branch mein jao, content quality gir sakti hai।
Schema likhna: strict mode ke rules aur design
Schema constraint JSON Schema ka sirf ek subset support karta hai; providers ki limits thodi alag. Neeche November 2026 mein dekhe gaye OpenAI docs ke strict: true requirements; exact limits official docs par dekhein; Anthropic ka strict tool bhi subset support karta hai, limits uske docs mein।
| Rule | Matlab |
|---|---|
additionalProperties | Har object mein additionalProperties: false; schema ke bahar keys allowed nahi |
required | properties ke saare fields required mein hon chahiye. Optional dikhana ho to type ko null ke saath union likhein, jaise ["string", "null"] |
| Root | Object hona chahiye; anyOf nahi (Zod discriminated unions sabse bahar anyOf banate hain - object mein wrap karein) |
| Supported types | string, number, integer, boolean, object, array, enum, anyOf; $defs aur recursive refs supported |
| Unsupported keywords | allOf, not, dependentRequired, dependentSchemas, if, then, else |
| Size limits | Max 5000 object properties, 10 nesting levels; property names, enum values waghera total 120,000 characters se kam |
| Key order | Output schema ke key order mein generate hota hai |
| Requirement fail | Request seedha error - testing mein hi pakad lete hain |
Types se schema generate karein, kuch traps pakdein
Hand-written JSON Schema code ke types se alag ho jaata hai; zyada safe: types se schema generate karein. Neeche Pydantic (pip install pydantic) plus ek minimal “validation + retry” loop, script real model ki jagah:
import json
from typing import Literal
from pydantic import BaseModel, ConfigDict, ValidationError
class Triage(BaseModel):
model_config = ConfigDict(extra="forbid") # generated schema mein additionalProperties: false aayega
reason: str # field order = schema ke properties ka order: pehle reason, phir conclusion
priority: Literal["low", "medium", "high"]
requires_human: bool
schema = Triage.model_json_schema()
print(json.dumps(schema, ensure_ascii=False))
print("field order:", list(schema["properties"]), "required:", schema["required"])
class Loose(BaseModel): # aam trap: default-generated schema strict mode ko satisfy nahi karta
reason: str
note: str | None = None
loose = Loose.model_json_schema()
print("extra='forbid' na ho to additionalProperties hai?", "additionalProperties" in loose)
print("default wala field required mein hai?", "note" in loose["required"])
class Fixed(BaseModel): # fix: optional field null-union, koi default nahi
model_config = ConfigDict(extra="forbid")
reason: str
note: str | None
fixed = Fixed.model_json_schema()
print("fixed: additionalProperties =", fixed["additionalProperties"], "| note required mein?", "note" in fixed["required"])
# script real model ki jagah: pehli baar extra pleasantries (valid JSON nahi), doosri valid JSON par schema se bahar, teesri sahi
replies = iter(
[
'Theek hai, result niche hai: {"priority": "high", "requires_human": true}',
'{"priority": "urgent", "requires_human": true}',
'{"reason": "charge ho gaya par order unpaid - money reconciliation", "priority": "high", "requires_human": true}',
]
)
def fake_model(messages):
return next(replies)
def ask(question, max_retries=3):
messages = [{"role": "user", "content": question}]
for attempt in range(max_retries + 1):
text = fake_model(messages)
try:
return Triage.model_validate_json(text)
except ValidationError as e:
errors = [f'{".".join(map(str, err["loc"])) or "<whole>"}: {err["msg"]}' for err in e.errors()]
print(f"attempt {attempt + 1} invalid:", errors)
messages += [
{"role": "assistant", "content": text},
{"role": "user", "content": "Output validation fail hua: " + "; ".join(errors) + ". Sirf schema ke conform JSON return karein।"},
]
raise RuntimeError("retries ke baad bhi invalid; human ko bhejo ya degrade")
print(ask("Order par charge ho gaya par unpaid dikha raha hai - kya karein?"))
{"additionalProperties": false, "properties": {"reason": {"title": "Reason", "type": "string"}, "priority": {"enum": ["low", "medium", "high"], "title": "Priority", "type": "string"}, "requires_human": {"title": "Requires Human", "type": "boolean"}}, "required": ["reason", "priority", "requires_human"], "title": "Triage", "type": "object"}
field order: ['reason', 'priority', 'requires_human'] required: ['reason', 'priority', 'requires_human']
extra='forbid' na ho to additionalProperties hai? False
default wala field required mein hai? False
fixed: additionalProperties = False | note required mein? True
attempt 1 invalid: ['<whole>: Invalid JSON: expected value at line 1 column 1']
attempt 2 invalid: ['reason: Field required', "priority: Input should be 'low', 'medium' or 'high'"]
reason='charge ho gaya par order unpaid - money reconciliation' priority='high' requires_human=True
Note: numbers original run se hain; sample strings Hindi/Latin transliteration mein badle gaye।
Output se padhne layak baatein:
extra="forbid"hiadditionalProperties: falsegenerate karta hai. Na likho to schema mein yeh key hi nahi - strict mode fail।- Default-value wala field
requiredmein nahi jaata - strict mode fail hi. Optional fieldstr | Noneaur koi default nahi (jaiseFixed): yeh null-union bhi hai aurrequiredmein bhi। - Field order = schema
propertieska order = model ke generate karne ka order.reasonkopriorityse pehle rakho to model pehle reason likhega, phir conclusion - agla section batata hai yeh kyun matter karta hai। - Retry loop ki kunji: specific errors wapas model ko. Pehli baar valid JSON hi nahi; doosri valid JSON par field missing aur enum se bahar value. Max retries limit; paar par degrade ya human।
Schema design ke kuch rules, OpenAI aur Anthropic docs plus upar wale experiment se:
- Key names clear; har field ka
description; jahan ho sake enum, free text nahi। - Model ko woh value na bhare do jo aap already jaante hain. Jaise order number code mein hai -
order_idparameter na banake model se dobara likhwana। - Irrelevant inputs ke liye exit do. Model schema satisfy karne ki koshish karta hai; off-task input par fields invent kar sakta hai -
null,unknownya dedicated error field allow karein। - Schema stable rakhein; alag structures ko eval set se compare karein, feeling se change na karein।
Constraint sirf format dekhta hai
Schema constraint on hai to bhi teen tarah ki problems khud handle karni hain:
| Problem | Symptom | Ilaj |
|---|---|---|
| Content wrong | Format valid, values galat: upar wale toy mein name/age - koi bhi valid value pass | Instructions clear, examples, task todo chhota; business rules se ranges/consistency validate; eval set se field-level accuracy naapo |
| Incomplete | max_tokens hit - sirf valid prefix (upar ke experiment mein 2000 mein 13); OpenAI response mein status = incomplete, incomplete_details.reason = max_output_tokens | Parse se pehle status check; output budget kaafi rakho; schema chhota rakho taaki output chhota ho |
| Refusal | Safety refusal par output refusal content hai, schema se conform nahi | Refusal ko normal branch samjho; parse se pehle refusal check |
Response parse karte waqt yeh order: response complete (na truncated, na content-filtered), refusal to nahi, parse ho raha hai, schema + business rules pass - kisi bhi step par fail ho to specific reason ke saath retry, count limit ke saath।
Format constraints reasoning ko dheema karti hain?
Kabhi-kabhi - haan. Tam adi (2024) ne GSM8K, Last Letter Concatenation, Shuffled Objects teen reasoning tasks par compare kiya: natural language (NL), prompt-required format (FRI), JSON mode, aur OpenAI ke naye Structured Outputs (paper mein JSON-Schema). Prompt sensitivity kam karne ke liye har approach 9 prompt combinations par evaluate hui. gpt-4o-mini-2024-07-18 ke exact-match scores (paper Table 2; %; brackets mein std):
| Task | Natural language | Prompt-required format | JSON mode | JSON Schema |
|---|---|---|---|---|
| GSM8K | 94.57 (3.95) | 87.17 (4.43) | 86.95 (1.36) | 91.71 (0.68) |
| Shuffled Objects | 82.85 (5.67) | 81.46 (3.71) | 76.43 (9.74) | 81.77 (6.86) |
| Last Letter | 83.11 (3.54) | 84.73 (2.99) | 76.00 (6.69) | 86.07 (3.33) |
Har cell ka std kaafi hai (0.68-9.74); kuch points ke andar ka farq over-read na karein. Jo saaf hai: JSON mode teeno tasks par sabse kharab - GSM8K par NL se 7.6 neeche; JSON Schema NL ke kareeb (GSM8K par 2.9 neeche, Shuffled Objects par 1.1 neeche, Last Letter par 3.0 upar). Is table aur paper ke baaki hisse se chaar baatein:
- Reasoning tasks mein format limits ki overall keemat hai. GSM8K par NL best, JSON mode worst; paper ka abstract: jitna strict format constraint, reasoning task mein utna zyada degradation aam taur par. Par JSON Schema JSON mode se kaafi behtar, Last Letter par NL se thoda upar (86.07 vs 83.11) - “constraint = zaroor kharab” nahi hai।
- Parse failures poora gap explain nahi karte. Paper parse error rates bhi dete hai: GPT-3.5 Turbo Last Letter JSON parse error 0; LLaMA 3 8B sirf 0.15% - phir bhi clearly worse. Kuch settings mein parse error high (Claude-3-Haiku GSM8K JSON par 60.07%) - woh retry se fix ho sakte hain; par parse-error-near-zero settings mein bhi scores gire।
- Field order ek key clue hai. Paper ne GPT-3.5 Turbo ke JSON mode outputs check kiye: 100% answers ne
answerkoreasonse pehle rakha - pehle answer, phir reason manufacture - CoT gayab; yehi Last Letter par bure performance ka kaaran। - Asar task par nirbhar. Classification-type tasks par JSON mode barabar ya behtar - paper ka guess: constraint ne answer space chhota kar diya; NL answer interference le sakta hai।
Kya karein:
- Reasoning field ko answer field se pehle rakhein. OpenAI docs ka math-tutor example yahi hai:
stepsfinal_answerse pehle, aur output schema ke key order mein banta hai। - Heavy-reasoning tasks do steps mein: pehle natural language answer, phir alag se format convert. Paper ise NL-to-Format kehta hai - zyada-tar models NL jaisa hi, kabhi conversion error se thoda kam (LLaMA 3 8B Instruct jaise)।
- Classification/extraction jaise finite answer space wale tasks par strict constraint bina dare lagao।
- Apne eval set par compare karein, paper ka conclusion copy na karein: yeh 2024 ka result hai, specific models/tasks. Eval method LLM evaluation methodology mein।
Function calling
Function calling ka essence ek structured output hai: model function name + JSON argument object deta hai; function waqai aapka code chalata hai, result naye message ke roop mein wapas, model isi par continue. Model kabhi kuch execute nahi karta - validation, auth, error handling sab aapki side।
Do providers ke message shapes
OpenAI ka function calling docs Responses API ke examples deta hai (Chat Completions abhi bhi hai, field names alag); Anthropic Messages API use karta hai. November 2026 ke official docs ke key shapes:
| Step | OpenAI (Responses API) | Anthropic (Messages API) |
|---|---|---|
| Tool define | {"type": "function", "name", "description", "parameters", "strict"} | {"name", "description", "input_schema"}, strict: true optional |
| Model call start | Output mein function_call item, call_id, name, arguments (JSON string) | Reply mein tool_use block, id, name, input (already object), stop_reason = tool_use |
| Result wapas | function_call_output append, same call_id, output string | Agle user message mein tool_result block, tool_use_id ke saath; error par is_error: true; tool_result message content ke sabse pehle hona chahiye |
| Calling control | tool_choice: auto (default), required, specific function, allowed_tools, none | tool_choice: auto (default), any, tool (specified), none |
| Parallel calls | Ek response mein kai calls; parallel_tool_calls: false se max ek | Parallel ho sakta hai; tool_choice mein disable_parallel_tool_use: true |
Kuch extras:
- OpenAI ka
argumentsstring hai - khudjson.loads; Anthropic kainputalready object. Strict mode on ho tab bhi parse kotrymein rakhein। - OpenAI docs kehte hain ek baar mein available functions 20 se kam achhe (docs khud kehte hain yeh soft advice hai), kyunki function definitions context mein count hote hain aur input tokens ke bill par।
- OpenAI ka
allowed_toolstool list badle bina is round ke callable tools seemit karta hai; docs ka reason: tool list same rakhne se prompt caching ka fayda max. Anthropic docs kehte hainanyaurtoolassistant message ko prefill karte hain - modeltool_usese pehle natural language nahi likhta; sab models/settings forced calling support nahi karte, support na ho to request error - tabauto+ strict tools। - Tool descriptions kaafi likhein. Anthropic docs: description tool performance ka “sabse important factor” hai; likhein tool kya karta hai, kab use ho (aur kab nahi), har parameter ka matlab, aur important limits (jaise tool kya return nahi karta); har tool kam se kam 3-4 sentences।
Ek chalne wala minimal loop
Neeche script model ki jagah - poora loop: model pehle parameter naam galat likhta hai (strict mode off jaisa), code error ko isi call ke result ke roop mein wapas deta hai, model dekh kar sudhaar leta hai, result milne par answer. Message shapes upar wali table ke OpenAI column se; real call mein sirf fake_model ko client.responses.create(...) se replace karein।
import json
TOOLS = [
{
"type": "function",
"name": "get_order_status",
"description": "Order number se order status poochho।",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string", "description": "order number, jaise A123"}},
"required": ["order_id"],
"additionalProperties": False,
},
"strict": True,
}
]
def get_order_status(order_id: str) -> dict:
return {"order_id": order_id, "status": "charged, awaiting confirmation"}
REGISTRY = {"get_order_status": get_order_status}
def fake_model(items):
"""Script model ki jagah: pehle ek call (parameter naam galat, strict-off jaisa),
error dekh kar sudhaar, phir result ke saath final answer."""
outputs = [x for x in items if x.get("type") == "function_call_output"]
if not outputs:
return [{"type": "function_call", "call_id": "call_1", "name": "get_order_status", "arguments": '{"order": "A123"}'}]
if "error" in json.loads(outputs[-1]["output"]):
return [{"type": "function_call", "call_id": "call_2", "name": "get_order_status", "arguments": '{"order_id": "A123"}'}]
status = json.loads(outputs[-1]["output"])["status"]
return [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": f"Order A123 ka current status: {status}।"}]}]
def run_tool(call):
"""Model ke parameters untrusted input hain: parse, dispatch, exceptions pakdo;
error bhi output banakar model ko wapas."""
try:
args = json.loads(call["arguments"])
result = REGISTRY[call["name"]](**args)
except (json.JSONDecodeError, KeyError, TypeError) as e:
result = {"error": f"{type(e).__name__}: {e}"}
return json.dumps(result, ensure_ascii=False)
def run(question, max_turns=5):
items = [{"role": "user", "content": question}]
for _ in range(max_turns):
output = fake_model(items) # real call: client.responses.create(model=..., input=items, tools=TOOLS)
items += output
calls = [x for x in output if x["type"] == "function_call"]
if not calls:
return output[-1]["content"][0]["text"], items
for call in calls:
items.append({"type": "function_call_output", "call_id": call["call_id"], "output": run_tool(call)})
raise RuntimeError("max turns paar")
answer, items = run("Order A123 ka status ab kya hai?")
for x in items:
kind = x.get("type", x.get("role"))
detail = x.get("arguments") or x.get("output") or x.get("content")
if kind == "message":
detail = detail[0]["text"]
print(f"{kind:20s} {detail}")
user Order A123 ka status ab kya hai?
function_call {"order": "A123"}
function_call_output {"error": "TypeError: get_order_status() got an unexpected keyword argument 'order'"}
function_call {"order_id": "A123"}
function_call_output {"order_id": "A123", "status": "charged, awaiting confirmation"}
message Order A123 ka current status: charged, awaiting confirmation।
Note: numbers original run se hain; sample strings Hindi/Latin transliteration mein badle gaye।
Is loop mein teen copy-layak practices:
- Error bhi result hai. Parameter parse fail ya function exception - explainable result banakar model ko wapas, poora request crash nahi. Anthropic docs guided error messages suggest karte hain - jaise “missing required parameter: location”, “failed” nahi।
- Turn limit. Loop ka max turns hona chahiye; paar par error ya human, warna model aur tools ek-doosre ko ghumaate rahenge।
- Parameters untrusted input hain. Yeh parameters model ne user ki baat se banaye - induce ho sakte hain. Strict mode sirf format, security nahi: permissions, amount limits, resource ownership backend mein check (dekhein agents aur tool calling)।
Tool returns bhi untrusted hain: web pages, emails, third-party API results mein instructions ho sakte hain (indirect prompt injection). Anthropic docs aise content ko tool_result block mein rakhne ko kehte hain - system prompt ya normal user text mein nahi।
Practice checklist
- Schema constraint ho sake to use karo, validation saath rakho: schema format, business rules semantics।
- Schema mein pehle reasoning field, phir conclusion field; har field ka description; enum ho sake to enum।
- Irrelevant inputs ke liye exit (
null,unknownya error field) - model schema satisfy karne ke liye invent na kare। - Parse se pehle status: truncated, content-filtered, refused?
- Failure par specific error ke saath retry, count limit, paar par degrade ya human।
- Parameters ko untrusted input samjho; auth aur limits backend mein।
- Schema stable, tools chhote, descriptions clear - kya karta hai, kab use ho, kya limits।
- Format-valid rate, field accuracy aur retry rate ko eval set mein daalo; alag constraint strengths ke results compare karein।
Do checks se synthetic structured data validate karna
Berkeley Scalable AI spring assignment 3 ka Structured Outputs notebook generator se schema, task aur structured response likhwata hai, phir programmatic verification. Aise flows se training data banate waqt do checks alag chahiye: fields valid hain? Field values input ke faithful hain? Multi-turn tool-call data ke liye simulated tools se parameters aur final state bhi check karein - sirf text ke “success” dawe par bharosa nahi।
Neeche 4 self-written responses se “3 log ke liye table book” ka output simulate. Hand-written field checks sirf is misaal ke constraints. Code Apple M2 Max par Python 3.14.3 se chala।
import json
responses = [
'{"count": 3}',
'{"count": 2}',
'{"count": true}',
'{"count": 3',
]
valid = correct = 0
for response in responses:
try:
obj = json.loads(response)
except json.JSONDecodeError:
continue
if not isinstance(obj, dict) or set(obj) != {"count"}:
continue
count = obj["count"]
if type(count) is not int or count < 1:
continue
valid += 1
correct += count == 3
assert (valid, correct) == (2, 1)
print(f"field valid: {valid}/{len(responses)}")
print(f"semantically correct: {correct}/{len(responses)}")
field valid: 2/4
semantically correct: 1/4
Note: numbers original run se hain; sample keys Hindi/Latin transliteration mein badle gaye।
Doosra response structure check pass karta hai par count galat. Python mein bool int ka subclass hai - isliye yahan explicit type() check, isinstance(count, int) nahi. Real project mein structure JSON Schema se, semantics human labels / business constraints / simulated environment se. Har gate ka pass rate aur failure samples alag record karein - phir decide decode constraint fix karna hai, generation prompt, ya scoring rules।
Summary aur exercises
- Chaar tiers alag guarantee: prompt agreement = koi guarantee nahi; JSON mode = valid JSON; schema constraint = supported schema conform; validation + retry = drain।
- Constrained decoding har step disallowed tokens ka logit -inf karke sample karti hai; engineering mein automaton + vocabulary index se har step ka cost table lookup।
- Yeh format guarantee karti hai, content sahi nahi, complete hona nahi, aur model distribution distort bhi kar sakti hai; reasoning tasks par strict format result ghatata hai - reasoning field ko answer se pehle rakhna sabse sasti mitigation hai।
- Function calling = structured output + message protocol: model sirf request karta hai; execution, validation, auth aapke code mein।
1. JSON mode aur Structured Outputs ka farq?
- JSON mode schema guarantee karta hai; Structured Outputs sirf valid JSON
- JSON mode sirf valid JSON guarantee karta hai; Structured Outputs diye gaye schema ka conform bhi guarantee karta hai
- Dono valid JSON guarantee nahi karte
- Farq sirf price ka hai
OpenAI docs: dono valid JSON guarantee karte hain; sirf Structured Outputs schema guarantee karta hai; jahan ho sake wahan Structured Outputs।
2. Constrained decoding har step par kya karti hai?
- Pehle free sample; invalid ho to drop karke dobara
- Disallowed tokens ka logit -inf, phir softmax aur sampling
- Training mein model ko format ratwana
- Prompt mein format baar-baar jodna
Mask illegal tokens ko sampling se hi nikaal deta hai; har step sirf allowed set se. “Sample phir check” rejection sampling hai - sakht format aur lambe outputs par bahut inefficient।
3. Pehle step par model A ya B, har ek 0.5. A ke baad sirf valid token ki model probability 0.1; B ke baad 0.9. Per-step mask mein output A se shuru hone ki probability?
- 5%
- 10%
- 50%
- 90%
Pehle step A aur B dono allowed - har ek 0.5; doosre step par ek hi valid token, renormalize 1. Model probabilities se normalize karte to ।
4. Schema constraint on hone ke baad kaun si problems abhi bhi khud handle karni hain? (multiple)
- Value errors: format valid, answer galat
- Output
max_tokensse truncate - sirf valid prefix - Safety refusal - output
refusalhai, schema wala nahi - JSON brackets mismatched
Bracket pairing format hai - constrained decoding use guarantee karti hai; values, completeness aur refusal constraint ke bahar।
5. Tam adi (2024) ne GPT-3.5 Turbo ka JSON mode Last Letter par bura dekha - direct cause?
- JSON parse failure rate high
- 100% answers ne
answerkoreasonse pehle rakha - direct answer ho gaya, CoT gayab - JSON mode output length limit karta hai
- Question input mein hi truncate ho gaya
Paper ne parse error rate near-zero naapa; problem field order mein thi: pehle answer, phir reason - CoT khatam।
6. Anthropic Messages API mein tool ka execution result model ko kaise wapas bheje?
-
role=toolwala message bhejo - Agle
usermessage meintool_resultblock, correspondingtool_use_idke saath -
function_call_outputappend karo - Result system prompt mein likh do
function_call_outputOpenAI Responses API ka shape hai. Anthropic tools kouser/assistantmessage content blocks mein rakhta hai - dedicatedtoolrole nahi hai।
Exercises
-
Upar wale widget mein temperature 0.5, 1, 2 set karein, constraint off, har par “1000x run”. Bina constraint ki complete-valid rate lagbhag kitni? Temperature ke saath kyun girti hai?
-
Neeche wala schema OpenAI strict mode ke liye hai - kam se kam do fixes batao, aur fixed schema likhein:
{ "type": "object", "properties": { "city": {"type": "string"}, "days": {"type": "integer", "minimum": 1}, "notes": {"type": "string"} }, "required": ["city", "days"] } -
Tool calling loop mein model ka
argumentsvalid JSON nahi (jaise adhoora likha). Code kya kare?
Reference answers
-
Lagbhag 53%, 17% aur near 0 (har run mein kuch points ka random jitter; 50k-run simulation par 53.1%, 16.9%, 0.1%). Temperature badhne se top-token se baaki tokens ko probability jaati hai - illegal tokens bhi: start par illegal probability T=0.5 par 21.6%, T=1 par 43.9%, T=2 par 64.2%. Complete output ke liye lagbhag das steps lagatar sahi likhne padte hain - per-step validity multiply hoti hai, isliye validity temperature ke saath tezi se girti hai. Constraint on: teeno temperatures par 100% valid - sirf 40-step truncation wale bahut kam exceptions।
-
Kam se kam do: (1) object mein
additionalProperties: falsenahi; (2)notesrequiredmein nahi - strict mode sab fields required maangta hai; optional dikhana ho to type null-union. Fixed:{ "type": "object", "properties": { "city": {"type": "string"}, "days": {"type": "integer", "minimum": 1}, "notes": {"type": ["string", "null"]} }, "required": ["city", "days", "notes"], "additionalProperties": false } -
Pehle check karein response
max_output_tokensse truncate to nahi hua (status=incomplete); agar haan, to output limit badhao ya output chhota karo, blind retry nahi. Waqai model ne galat likha ho to parse error ko isi call ka result bana kar (call_id sahit) model ko wapas do, use sudhaarne do. Har haal mein validated na hue call execute na karein; max turns limit; paar par error ya human।
Aage padhein
- Efficient Guided Generation for Large Language Models (Willard aur Louf, 2023): Outlines - regex ko finite state machine, vocabulary par index।
- XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (Dong adi, 2024): CFG ke under efficient mask computation; is page ke vocabulary-class aur 128k-vocab numbers isi se।
- Grammar-Aligned Decoding (Park adi, 2024): per-step mask model distribution distort karta hai, aur alignment wala ASAp algorithm।
- Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models (Tam adi, 2024): format limits ka reasoning vs classification par asar; is page ka table isi se।
- OpenAI docs: Structured Outputs aur Function calling (November 2026 mein dekhe gaye)।
- Anthropic docs: Define tools, Handle tool calls aur Strict tool use (November 2026 mein dekhe gaye)।
- Is site ke pages: prompt engineering guide, agents aur tool calling, decoding aur sampling।
- Robotics par constrained decoding ka example: RT-2 robot action tasks mein sirf 256 action tokens sample hone deta hai।
अक्सर पूछे जाने वाले सवाल
- JSON mode aur Structured Outputs mein kya farq?
- JSON mode sirf guarantee deta hai ki output valid JSON hai; aapke schema ke conform hone ki nahi; aur conversation mein JSON manga na ho to model khaali output de sakta hai jab tak token limit hit. Structured Outputs (strict mode) decoding ke waqt JSON Schema se constrain karta hai - supported schema subset ke conform ki guarantee. OpenAI docs kehte hain: jab Structured Outputs use ho sake, JSON mode na use karein।
- Constrained decoding output format kaise guarantee karti hai?
- Har token se pehle target format (regex, grammar ya JSON Schema) aur likhe gaye text se allowed token set nikaala jaata hai; baaki tokens ka logit -inf, phir softmax aur sampling - isliye har step valid prefix hai. Engineering mein format automaton mein compile hota hai aur vocabulary par index pehle se banta hai; har step sirf table lookup. Yeh format guarantee karta hai, content nahi; aur max_tokens ke andar complete hone ki bhi nahi।
- Structured output model ko "dumb" bana deta hai?
- Ho sakta hai - task aur approach par nirbhar. Tam adi (2024) ne dekha: reasoning tasks strict format limits par zyada bure, jitna strict utna zyada degradation; classification tasks par barabar ya behtar. Aam mitigations: schema mein reasoning field answer field se pehle, ya pehle natural language mein answer phir format convert, aur apne eval set par compare।
- Function calling mein model khud function execute karta hai?
- Nahi. Model sirf function name aur JSON arguments deta hai; execution aapke code mein hota hai, result naye message ke roop mein wapas model ko. Isliye parameter validation, permission checks, error handling aur rate limits aapki side par hain - strict mode on hai to bhi skip na karein।
- Strict mode on hai, to validation aur retry bhi chahiye?
- Haan. Strict mode sirf format dekhta hai: values galat ho sakti hain, output max_tokens se truncate ho sakta hai, safety par refuse ho sakta hai, aur business rules (amount ranges, resource ownership) schema mein nahi hote. Pehle response status aur refusal check karein, phir parse-validate; failure par specific error ke saath retry, retry count limit ke saath।