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.
Python code
47 linesimport 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
{
"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
- Use `json.dumps(flattened)` to produce a compact string for passing to APIs that accept raw JSON
- 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
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.