How to Build a Data Helper for LLM Prompts in Python

A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.

Medium Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 18 views 0 copies

Python code

47 lines
Python 3.9+
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper class for working with data in AI/LLM pipelines."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
        self.data = data or {}
    
    def flatten(self, prefix: str = "") -> Dict[str, Any]:
        """Flatten nested dictionaries for LLM-friendly key-value pairs."""
        result: Dict[str, Any] = {}
        for key, value in self.data.items():
            new_key = f"{prefix}.{key}" if prefix else key
            if isinstance(value, dict):
                result.update(DataHelper(value).flatten(new_key))
            else:
                result[new_key] = value
        return result
    
    def to_prompt(self, template: str) -> str:
        """Format data into a prompt template using {variable} placeholders."""
        flattened = self.flatten()
        return template.format(**flattened)
    
    def safe_load(cls, json_string: str) -> "DataHelper":
        """Parse JSON with error handling for LLM outputs."""
        try:
            return cls(json.loads(json_string))
        except json.JSONDecodeError:
            return cls({"error": "Invalid JSON", "raw": json_string})
    
    def summarize(self) -> List[str]:
        """Create a bullet-point summary suitable for chat context."""
        return [f"- {k}: {v}" for k, v in self.flatten().items()]


if __name__ == "__main__":
    sample = {
        "user": {"name": "Alice", "age": 30},
        "preferences": {"language": "Python", "level": "beginner"}
    }
    helper = DataHelper(sample)
    print(json.dumps(helper.flatten(), indent=2))
    print(helper.to_prompt("User: {user.name}, Level: {preferences.level}"))
    print("\n".join(helper.summarize()))

Output

stdout
{
  "user.name": "Alice",
  "user.age": 30,
  "preferences.language": "Python",
  "preferences.level": "beginner"
}
User: Alice, Level: beginner
- user.name: Alice
- user.age: 30
- preferences.language: Python
- preferences.level: beginner

How it works

The DataHelper class wraps data and provides methods that make nested structures easier to work with in LLM contexts. flatten() recursively converts nested dicts into dot-notation keys, which is ideal for prompt templates that reference fields like {user.name}. to_prompt() uses str.format with flattened keys to inject values directly into a template. safe_load() catches JSON errors from LLM outputs and returns an error object instead of crashing the pipeline. summarize() generates bullet-point lines that are ready to paste into chat context or model inputs.

Common mistakes

  • Forgetting that `str.format` requires curly braces to be escaped in literal template text
  • Not handling empty data — `flatten()` returns an empty dict, and `to_prompt` will raise KeyError for missing fields
  • Confusing `safe_load` with a classmethod — it must be called as `DataHelper.safe_load(...)`, not on an instance

Variations

  1. Use `json.dumps(flattened)` to produce a compact string for passing to APIs that accept raw JSON
  2. Add a `filter_keys` parameter to `flatten()` to exclude sensitive fields before sending data to a model

Real-world use cases

  • Preparing user profile data from a database into prompt-ready context for a chatbot response.
  • Flattening API response bodies before sending them as structured context to a language model for summarization.
  • Safely handling LLM-generated JSON that may be malformed, so your pipeline continues instead of failing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.