The extraction step sometimes returns invalid JSON
A pipeline asks an LLM to extract invoice fields as JSON. About 2% of responses fail to parse, or miss required fields, and the job crashes. How do you make this step reliable?
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
Constrain the output, then validate it like any untrusted input.
Show the solution
Use the provider's structured output or tool-calling feature with a JSON schema, so responses follow the schema. Validate every response against the schema in code (for example with Pydantic). On failure, retry once with the validation error in the prompt, and send records that still fail to a quarantine table for review instead of crashing the whole job.
Example (Python)
from pydantic import BaseModel, ValidationError
class Invoice(BaseModel):
invoice_id: str
total: float
currency: str
def parse(raw: str):
try:
return Invoice.model_validate_json(raw)
except ValidationError as e:
return e # retry once with str(e) in the prompt, then quarantine
Common mistakes
- Fixing the JSON with regular expressions.
- Assuming that parseable JSON is correct: values still need range and format checks.
How did you do? Your answer is saved in this browser and comes back for revision later.
Learn more
- Structured Extraction for PipelinesGenerative AI
- Structured Outputs: JSON and Function CallingGenAI & Agentic Systems