पाठ 8 / 31

Output Parsers और Structured Output

मॉडल के पाठ को validated Python objects में बदलें।

Parse करें, validate करें, ज़ोर से विफल हों

मॉडल पाठ लौटाते हैं; प्रोग्रामों को objects चाहिए। Output parsers उत्तर बदलते हैं: सादे पाठ के लिए StrOutputParser, JSON के लिए JsonOutputParser, और types व बाधाओं (जैसे urgency 1 से 5 के बीच) वाले Pydantic schema के विरुद्ध validate करने को PydanticOutputParser। Parser prompt में रखने के लिए format instructions भी बना सकता है। उत्तर schema तोड़े तो parser OutputParserException उठाता है जिसे आप पकड़कर retry कर सकते हैं। कई chat models model.with_structured_output(Schema) से native structured output भी समर्थित करते हैं, जो provider की tool-calling या JSON-schema सुविधा उपयोग करता है और आम तौर पर मुक्त पाठ parse करने से अधिक भरोसेमंद है।

Pydantic से validate करना, चलाकर

मैंने यह Python virtual environment में langchain-core 1.6.6, langchain-text-splitters 1.1.2 और llama-index-core 0.14.25 के साथ ऑफ़लाइन चलाया। किसी API key या network call की ज़रूरत नहीं क्योंकि असली मॉडल की जगह fake मॉडल या खिलौना embedding है। वैध उत्तर Ticket ऑब्जेक्ट बनता है। urgency 9 वाला उत्तर le=5 बाधा तोड़ता है, इसलिए parser OutputParserException उठाता है।

from pydantic import BaseModel, Field
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.exceptions import OutputParserException

class Ticket(BaseModel):
    category: str = Field(description="billing, technical or other")
    urgency: int = Field(ge=1, le=5)

parser = PydanticOutputParser(pydantic_object=Ticket)
print(parser.parse('{"category": "billing", "urgency": 4}'))
try:
    parser.parse('{"category": "billing", "urgency": 9}')
except OutputParserException as e:
    print("rejected:", type(e).__name__)
print("format hint mentions:", "urgency" in parser.get_format_instructions())

Output:

category='billing' urgency=4
rejected: OutputParserException
format hint mentions: True

त्वरित जाँच: उत्तर Pydantic schema तोड़े तो क्या होता है?

  • मॉडल दोबारा प्रशिक्षित होता है
  • ग़लत मान चुपचाप स्वीकार हो जाता है
  • Parser exception उठाता है जिसे आप पकड़कर retry कर सकते हैं
  • प्रोग्राम बिना error समाप्त होता है
Answer

Parser exception उठाता है जिसे आप पकड़कर retry कर सकते हैं — ज़ोर से विफल होना आपको बुरे आउटपुट को स्पष्ट रूप से सँभालने देता है।