Prepare LLM prompt data with a Python helper class
A beginner-friendly Python class that collects records, converts them to JSON, and produces a quick summary for building LLM prompt context.
Python code
35 linesimport json
from typing import Any, Dict, List
class DataHelper:
"""Simple helper to prepare data for LLM prompts."""
def __init__(self):
self.data = []
def add(self, item: Dict[str, Any]) -> "DataHelper":
self.data.append(item)
return self
def to_json(self) -> str:
return json.dumps(self.data, indent=2)
def summarize(self) -> Dict[str, int]:
"""Quick stats for the LLM context."""
if not self.data:
return {"count": 0, "keys": []}
return {
"count": len(self.data),
"keys": list(self.data[0].keys()),
"sample": self.data[0]
}
helper = DataHelper()
helper.add({"name": "Alice", "age": 30})
helper.add({"name": "Bob", "age": 25})
if __name__ == "__main__":
print("JSON payload for LLM:")
print(helper.to_json())
print("\nContext summary:")
print(json.dumps(helper.summarize(), indent=2))
Output
JSON payload for LLM:
[
{
"name": "Alice",
"age": 30
},
{
"name": "Bob",
"age": 25
}
]
Context summary:
{
"count": 2,
"keys": [
"name",
"age"
],
"sample": {
"name": "Alice",
"age": 30
}
}
How it works
The DataHelper class provides a simple, chainable API for building a dataset. The add method returns self, enabling method chaining for concise code. to_json uses json.dumps with indentation for readable output, perfect for pasting into LLM prompts. The summarize method returns basic statistics (count, keys, sample) to give the model context about the data structure. This pattern keeps prompt preparation isolated and testable, avoiding messy inline JSON building.
Common mistakes
- Forgetting to return `self` from `add` breaks chaining.
- Assuming keys are consistent across all records — `summarize` only inspects the first item.
- Using `json.dumps` on non-serializable objects (e.g., datetime) without custom handling.
Variations
- Use dataclasses to define record structures and convert them with `asdict()`.
Real-world use cases
- Collecting user feedback records before sending a batch to an LLM for sentiment analysis.
- Building a few-shot prompt by selecting historical examples and formatting them as JSON.
- Preparing structured input for a summarization model from a list of API responses.
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.