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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 16 views 0 copies

Python code

35 lines
Python 3.9+
import 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

stdout
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

  1. 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

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.