Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Reliable LLM Structured Data Extraction

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to make structured data extracted by large language models (LLMs) more reliable. You'll learn practical techniques to reduce errors, validate outputs, and build a pipeline that catches mistakes before they reach your database or application. No special tools are required beyond an LLM API or interface and a way to run simple scripts.

What You'll Need

  • Access to an LLM (API or web interface)
  • A text editor or Python environment for scripting
  • Sample input documents to test with
  • Basic understanding of JSON and regular expressions

Step-by-Step

  1. Define your schema strictly. Write out exactly what fields you need, their types (string, number, date), and any allowed values. For example, if extracting product info, specify price as a number, currency as a 3-letter code, and in_stock as a boolean. The more precise your schema, the fewer surprises.
  2. Use a structured output format. Ask the LLM to return JSON only, with no extra text. In your prompt, include an example of the expected JSON structure. For APIs, use the response_format parameter if available (e.g., json_object in OpenAI). This forces the model to produce valid JSON.
  3. Provide few-shot examples. Give 2-3 complete examples of input text and the corresponding correct JSON output. This teaches the model the exact style and edge cases you expect. For instance, show how to handle missing values (use null vs. empty string).
  4. Add constraints and instructions. Tell the model what to do with ambiguous data. For example: "If the price is not mentioned, set price to null." Or "Convert all dates to ISO 8601 format." Explicit rules reduce hallucination.
  5. Validate the output programmatically. After receiving the JSON, run a validation script that checks: (a) it parses as valid JSON, (b) all required fields are present, (c) types match the schema, (d) values fall within expected ranges (e.g., price > 0). Use a library like pydantic in Python or ajv in JavaScript.
  6. Implement a retry mechanism. If validation fails, send the output back to the LLM with the error message and ask it to fix the issues. For example: "Your response failed validation because price is a string. Please return it as a number." Retry up to 2-3 times.
  7. Use confidence scores or self-consistency. For critical fields, ask the LLM to output a confidence score (0-1) for each field. Or run the extraction 3 times with different temperatures and take the majority answer for each field. This is called self-consistency and it reduces random errors.
  8. Post-process with rules. Apply simple regex or string manipulations to clean up common issues: trim whitespace, convert to lowercase where appropriate, remove extra punctuation. For example, strip leading/trailing spaces from names.
  9. Log and monitor failures. Keep a record of inputs that failed validation or had low confidence. Review them periodically to spot patterns (e.g., certain date formats or unit abbreviations that trip the model).
  10. Test with a golden set. Create a small test set of documents with known correct outputs. Run your pipeline on it after each change to measure precision and recall. Aim for at least 95% accuracy on required fields.

Common Mistakes

  • Vague schema: Saying "extract the date" without specifying format leads to inconsistent outputs like "March 5" vs. "2025-03-05".
  • Ignoring validation: Assuming the LLM always returns perfect JSON. It often adds markdown code fences or extra text.
  • Overloading the prompt: Asking for too many fields at once increases error rates. Break it into smaller tasks if possible.
  • Not handling missing data: The model might invent values when information is absent. Always instruct it to use null.
  • Using default temperature: High temperature (e.g., 1.0) increases randomness. For extraction, use a lower temperature (0.2 or less).

Tips

  • Use a system prompt that says: "You are a data extraction engine. You only output JSON."
  • If using an API, set temperature to 0 for deterministic outputs (though some variation still occurs).
  • Consider using a local JSON schema validator like jsonschema in Python to catch type errors.
  • For dates, use a library like dateutil to parse flexible formats and then normalize.
  • When retrying, show the model the exact validation error message—it helps it correct.

Troubleshooting

  • Output is not JSON: Add to your prompt: "Respond with only valid JSON, no markdown, no commentary." If using an API, check if the response has a content field with extra text—strip it.
  • Fields are consistently wrong: Review your few-shot examples. Are they representative? Add more examples that cover the problematic case.
  • Validation fails on types: The model might output "123" instead of 123. In your prompt, explicitly say: "Do not quote numbers." Also, in validation, coerce types if safe.
  • Missing fields: If the model omits a field, it may not have found the data. Check the input text—is the information actually there? If yes, rephrase your prompt to be more explicit about where to look.
  • High latency: If you're retrying often, consider reducing the number of retries or using a faster model for simple extractions.

Frequently Asked Questions

Can I use a free LLM for this?

Yes, but free models may have higher error rates and less reliable JSON output. The techniques here still apply, but you may need more retries.

How do I handle different languages in the input?

Specify the input language in the prompt. The LLM can extract structure regardless of language, but you may need to provide examples in that language.

What if the LLM extracts a value that is plausible but wrong?

This is a hallucination. Use self-consistency (run multiple times) and cross-check with a secondary source if available. For critical fields, consider a human review step.

Is it better to use a fine-tuned model?

Fine-tuning can improve accuracy for your specific domain, but it requires a large labeled dataset. Start with prompt engineering and validation first.

How do I measure reliability?

Build a test set with known answers. Calculate accuracy per field, and overall JSON validity rate. Track these metrics over time.

Can I use this for real-time extraction?

Yes, but keep prompts short and validation lightweight. Consider caching common patterns.