📋 Eliminating Parsing Failures: Moving Beyond Prompt Engineering to Deterministic Decoding
Relying on prompt phrasing like "Please respond in valid JSON" is inherently unreliable in production software architectures; models frequently introduce trailing commas, unescaped markdown blocks, or schema drift. Structured Outputs and Grammar-Constrained Decoding (e.g., Guidance, Outlines, llama.cpp GBNF grammars, and OpenAI JSON Mode) intervene directly at the inference logits level. By dynamically masking the vocabulary probability distribution at every generation step based on a Context-Free Grammar (CFG) or JSON Schema, invalid tokens are assigned a probability of zero ($-\infty$ logit), guaranteeing 100% syntactic and semantic compliance before the response string is even emitted.
from typing import List
from pydantic import BaseModel, Field
from openai import OpenAI
# Define strict target schema
class LineItem(BaseModel):
description: str = Field(description="Description of purchased item")
quantity: int = Field(description="Quantity purchased")
unit_price: float = Field(description="Price per unit in USD")
total_price: float = Field(description="Line total amount")
class InvoiceExtraction(BaseModel):
vendor_name: str = Field(description="Name of the invoice issuer")
invoice_number: str = Field(description="Invoice identification number")
issue_date: str = Field(description="Date in YYYY-MM-DD format")
line_items: List[LineItem]
grand_total: float = Field(description="Total invoice sum including tax")
client = OpenAI()
# Inference call with guaranteed schema adherence
completion = client.beta.chat.completions.parse(
model="gpt-4o-2026-03",
messages=[
{"role": "system", "content": "Extract structured billing details from the invoice."},
{"role": "user", "content": "[RAW OCR INVOICE TEXT PAYLOAD]"}
],
response_format=InvoiceExtraction,
)
invoice_data = completion.choices.message.parsed
print(f"Vendor: {invoice_data.vendor_name} | Total: ${invoice_data.grand_total}")
# GBNF Grammar file: ip_subnet.gbnf
# root ::= ipv4 "/" subnet
# ipv4 ::= digit1_3 "." digit1_3 "." digit1_3 "." digit1_3
# digit1_3 ::= [0-9] | [0-9][0-9] | [1-2][0-9][0-9]
# subnet ::= [1-3]?[0-9]
from llama_cpp import Llama
llm = Llama(model_path="./models/llama-3-8b.gguf", logits_all=True)
grammar_path = "./grammars/ip_subnet.gbnf"
# Inference constrained strictly to the GBNF grammar
response = llm(
"Provide the primary gateway IP and subnet mask for server rack A-12:",
max_tokens=32,
grammar_path=grammar_path,
temperature=0.0
)
print(response["choices"]["text"])
# Output guaranteed to match: e.g., "192.168.1.1/24" without conversational filler.
from enum import Enum
from pydantic import BaseModel, Field
class ICD10Category(str, Enum):
DIABETES_T2 = "E11.9"
ESSENTIAL_HYPERTENSION = "I10"
ACUTE_BRONCHITIS = "J20.9"
MAJOR_DEPRESSIVE_DISORDER = "F32.9"
class ClinicalCodingResult(BaseModel):
primary_diagnosis_code: ICD10Category = Field(description="Normalized ICD-10 billing code")
confidence_score: float = Field(ge=0.0, le=1.0, description="Classification confidence")
clinical_rationale: str = Field(description="Brief justification based on clinical notes")
# When passed to structured outputs, the LLM logits are dynamically masked
# so that ONLY tokens corresponding to "E11.9", "I10", "J20.9", or "F32.9"
# can be generated at the enum field position.
class STIXIndicator(BaseModel):
type: str = Field(default="indicator")
spec_version: str = Field(default="2.1")
id: str = Field(description="UUIDv4 in STIX format e.g. indicator--uuid")
name: str = Field(description="Indicator name")
pattern: str = Field(description="Cyber observable expression e.g. [ipv4-addr:value = '192.0.2.1']")
valid_from: str = Field(description="Timestamp in ISO 8601 format")
# Enforces that all generated threat feeds adhere strictly to automated SOAR ingestion parsers.
class Department(str, Enum):
ELECTRONICS = "Electronics"
APPAREL = "Apparel"
HOME_GARDEN = "Home & Garden"
class ProductTaxonomy(BaseModel):
department: Department
category: str = Field(description="Sub-category within department")
tags: List[str] = Field(description="Max 5 attribute tags", max_items=5)
is_hazmat: bool = Field(description="Whether product contains lithium batteries or chemicals")
class S3BucketResource(BaseModel):
bucket_name: str = Field(pattern=r"^[a-z0-9.-]{3,63}$", description="Valid globally unique S3 bucket name")
region: str = Field(default="us-east-1")
versioning_enabled: bool = True
tags: dict[str, str] = Field(description="Key-value infrastructure tags")
# Guarantees generated IaC configurations pass `terraform validate` on first execution.
class RefundToolArguments(BaseModel):
transaction_id: str = Field(description="UUID of transaction to refund")
refund_amount_cents: int = Field(gt=0, description="Amount in integer cents")
reason_code: str = Field(enum=["FRAUD", "CUSTOMER_REQUEST", "DUPLICATE"])
# Prevents agents from passing floating-point currency values or unmapped string reasons.
class RiskLevel(str, Enum):
LOW = "Low"
MEDIUM = "Medium"
HIGH = "High"
CRITICAL = "Critical"
class ContractClauseExtraction(BaseModel):
clause_title: str
risk_assessment: RiskLevel
financial_exposure_usd: float | None = Field(description="Max liability cap in USD if specified")
summary: str
class DepartmentQueue(str, Enum):
BILLING = "Billing"
TECHNICAL_SUPPORT = "Technical Support"
ENTERPRISE_SALES = "Enterprise Sales"
class TicketMetadata(BaseModel):
queue: DepartmentQueue
priority_level: int = Field(ge=1, le=5, description="1=Low, 5=Emergency")
customer_sentiment_score: float = Field(ge=-1.0, le=1.0, description="-1.0 is extremely angry, 1.0 is delighted")
suggested_auto_reply: str
class ColumnMapping(BaseModel):
legacy_column_name: str
modern_column_name: str
transformation_expression: str = Field(description="SQL or Pandas snippet to convert data type")
data_loss_risk: bool = Field(description="True if truncation or type coercion occurs")