Engineering a Personal Prompt System: Library, Versioning, and Automated Tests
A code-first guide to treating prompts like code. You give each prompt a clear structure (role, context, constraints, output), store it in a versioned JSON library in Git, fill its variables safely, run it against saved test cases with a Python harness, and grade the results with rule checks, diffs or a second model acting as judge.

This guide is for developers who reuse the same prompts every week and want them to get better, not drift. You will store prompts in a versioned JSON library, run them against fixed test cases with a small Python harness, and grade the results. By the end, a prompt change is something you can test and review, like a code change.
Key takeaways
- Prompts are code: keep them in files, give each one an id, and review changes in Git.
- Test a prompt against the same saved inputs every time, so you can compare versions fairly.
- Start with cheap rule checks, read diffs for the rest, and add an LLM judge only for qualities that rules can't catch.
Why prompts need a system
If your prompts live in chat history and notes, you can't tell whether this week's version is better than last week's. You change a word, the output looks fine once, and you move on. A month later, the output has drifted and nobody knows why.
A personal prompt system is a small set of files and scripts that stores your prompts in one place, tracks their versions, and runs them against fixed test cases so you can compare results.
OpenAI's prompt engineering guide gives the same advice for production apps. It recommends storing prompts in your application code, pinning production apps to specific model snapshots, and building evaluation suites to measure prompt behavior as you iterate. This post applies those ideas at personal scale.
Step 1: Give every prompt the same structure
Before you test prompts, make them comparable. One simple checklist is R-C-C-O: Role, Context, Constraints, Output. It is a rule of thumb, not a standard. OpenAI's guide suggests a similar order for developer messages: identity, instructions, examples and context.
- Role: who the model should act as, for example "Senior Python backend engineer".
- Context: the background, for example "Refactoring a legacy Flask app to FastAPI".
- Constraints: what is required or forbidden, for example "No libraries other than Pydantic. At most 50 lines."
- Output: the exact format, for example "Return only the code. No explanations."
Compare a vague prompt with a structured one:
Write me a python script to scrape a website.
ROLE: Web scraping and data engineer.
CONTEXT: A scraper for a news site whose page structure changes often.
CONSTRAINTS: Use Selenium with headless Chrome. Follow the Next button for pagination.
Wait 1 to 3 seconds at random between pages. Handle timeouts.
OUTPUT: Only the Python class. No usage examples.
As a rule of thumb, the structured version gives output that needs less editing, because the model has fewer gaps to fill with guesses. Your test cases will tell you whether that holds for your prompts.
Step 2: Build the prompt library
Keep prompts in a file your code can read, not in a notes app. A JSON file is enough. Create prompts.json:
[
{
"id": "code-refactor-v1",
"description": "Refactor a Python function for readability",
"template": "You are a clean code reviewer. Refactor this function to follow PEP 8 and remove repetition.\n\nCODE:\n{{user_code}}\n\nCONSTRAINTS:\n1. Add a docstring.\n2. Add type hints.\n3. Return only code."
},
{
"id": "email-summarizer-v2",
"description": "Summarize a tech newsletter",
"template": "You are an executive assistant. Summarize this text in 3 bullet points. Keep only actionable points.\n\nTEXT:\n{{newsletter_text}}"
}
]
The {{variable}} placeholders keep the fixed instruction apart from the data you pass in. The version lives in the id: when you change a prompt in a way that changes its output, copy it to -v2 and keep -v1 until the new one passes its tests. Commit the file to Git, so every change has a diff and a message.
Step 3: Save test cases next to the prompts
A test case is a fixed input plus the checks its output must pass. Create cases.json:
[
{
"name": "adds-type-hints",
"prompt_id": "code-refactor-v1",
"variables": {"user_code": "def calc(a,b):\n print(a+b)\n return a+b"},
"must_contain": ["def ", "->", "\"\"\""],
"must_not_contain": ["Here is"],
"max_words": 120
}
]
Each check is something you can test in code: a string that must appear, a phrase that must not, a length limit. Add a case each time a prompt fails you in real use, so the same mistake can't come back unnoticed.
Step 4: Write the test harness
Install the OpenAI SDK and Pydantic in a virtual environment:
pip install openai==3.41.0 pydantic==2.14.1
Then create prompt_harness.py:
import json
import os
import re
import sys
from pathlib import Path
from openai import OpenAI
PLACEHOLDER = re.compile(r"\{\{\s*(\w+)\s*\}\}")
def load_prompts(path="prompts.json"):
with open(path, encoding="utf-8") as f:
return {prompt["id"]: prompt for prompt in json.load(f)}
def render(template, variables):
missing = set(PLACEHOLDER.findall(template)) - variables.keys()
if missing:
raise KeyError(f"missing variables: {sorted(missing)}")
return PLACEHOLDER.sub(lambda match: variables[match.group(1)], template)
def run_prompt(prompt_text):
client = OpenAI() # reads OPENAI_API_KEY
response = client.responses.create(
model=os.environ.get("PROMPT_MODEL", "gpt-6-luna"),
input=prompt_text,
)
return response.output_text
Checked against openai@3.41.0 and pydantic@2.14.1 (Python 3.13), 2026-10-29.
render fills every placeholder in the template and fails loudly if a variable is missing. The older version of this post used template.replace("{{user_code}}", data), which only worked for one prompt:
# Don't: only fills {{user_code}}; other prompts keep their raw placeholders
prompt_text = template.replace("{{user_code}}", data)
# Do: fills any {{name}} and raises if one is missing
prompt_text = render(template, {"newsletter_text": data})
On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model and gpt-6-astra as its most capable. Test with the model you will use for real, and set PROMPT_MODEL to switch. The client is created inside run_prompt, because OpenAI() raises an error when no API key is set, and that would stop tests that import this file.
Now add the checks and the runner to the same file:
def check(output, case):
failures = []
for text in case.get("must_contain", []):
if text not in output:
failures.append(f"missing {text!r}")
for text in case.get("must_not_contain", []):
if text in output:
failures.append(f"contains {text!r}")
if "max_words" in case and len(output.split()) > case["max_words"]:
failures.append(f"over {case['max_words']} words")
return failures
def run_cases(cases_path="cases.json", prompts_path="prompts.json", run=run_prompt):
prompts = load_prompts(prompts_path)
with open(cases_path, encoding="utf-8") as f:
cases = json.load(f)
failed = 0
for case in cases:
output = run(render(prompts[case["prompt_id"]]["template"], case["variables"]))
log = Path("logs") / case["prompt_id"] / f"{case['name']}.md"
log.parent.mkdir(parents=True, exist_ok=True)
log.write_text(output, encoding="utf-8")
failures = check(output, case)
failed += bool(failures)
print(f"{'FAIL' if failures else 'PASS'} {case['prompt_id']} / {case['name']} {failures or ''}")
return failed
if __name__ == "__main__":
sys.exit(1 if run_cases() else 0)
Run it with python prompt_harness.py. Each output is saved under logs/<prompt id>/<case>.md, and the script exits with an error if any case fails. The script creates the logs/ folders itself, so the first run doesn't crash after paying for the API call.
Step 5: Test the harness itself, without a key
The run parameter lets you swap the model for a fake function. That checks your files, placeholders and rules for free:
import json
from prompt_harness import check, render, run_cases
assert render("Hi {{ name }}", {"name": "Ana"}) == "Hi Ana"
try:
render("Hi {{name}}", {})
except KeyError:
pass
else:
raise AssertionError("missing variable not caught")
fake_output = 'def calc(a: int, b: int) -> int:\n """Add two numbers."""\n return a + b'
assert check(fake_output, json.load(open("cases.json"))[0]) == []
assert run_cases(run=lambda prompt_text: fake_output) == 0
print("harness works")
Save it as test_harness.py next to the JSON files and run it. If you rename a placeholder in prompts.json but not in cases.json, this fails before you spend anything.
Step 6: Compare versions
Rule checks catch broken formats, but not whether one wording reads better than another. For that, compare outputs side by side:
- Run the harness with
code-refactor-v1and commit thelogs/folder. - Copy the prompt to
code-refactor-v2, change one thing, and point a copy of the case at it. - Run the harness again and read the two log files side by side, or with
git diff --no-index. - Keep the version that passes the checks and reads better. Delete the loser, so the library stays small.
Change one thing at a time. If you change three, you won't know which one helped.
Step 7: Add an LLM judge for the fuzzy parts
Some qualities, such as tone or clarity, are hard to check with rules. A second prompt can grade them. Structured output makes the grade easy to read in code:
from pydantic import BaseModel
class Grade(BaseModel):
reason: str
score: int
def grade_output(task, output):
client = OpenAI()
response = client.responses.parse(
model=os.environ.get("JUDGE_MODEL", "gpt-6-astra"),
input=(
"You are a strict code reviewer. Score this output from 1 to 5 for how well it does the task. "
"1 means it ignores the task, 5 means it does all of it with no extra text. "
f"Explain your reason first.\n\nTASK:\n{task}\n\nOUTPUT:\n{output}"
),
text_format=Grade,
)
return response.output_parsed
Add grade_output to prompt_harness.py above the if __name__ block. Anthropic's guide on building evaluations notes that it is generally best to grade with a different model from the one that wrote the output, which is why the judge reads its own JUDGE_MODEL. The rubric names what 1 and 5 mean, and reason comes before score, so the judge explains before it decides.
Treat judge scores as a signal, not the truth. Check a sample of them by hand before you trust the trend.
Which grading method to use
| Method | What it checks | Trade-off | Use it when |
|---|---|---|---|
| Rule checks | Required text, banned phrases, length, valid JSON | Fast, free and repeatable, but blind to quality | Always, as the first gate |
| Side-by-side diff | Anything you can see by reading | Accurate, but your time doesn't scale | Choosing between two prompt versions |
| LLM judge | Tone, clarity, task coverage | Scales to many cases, but costs calls and needs spot checks | You have more cases than you can read |
Anthropic's evaluation guide puts the trade-off this way: more test cases with slightly noisier automated grading beat fewer cases graded by hand. For a personal system, start with rule checks and diffs, and add the judge when reading every output becomes the bottleneck.
Where this fits
Once a prompt has to return data rather than prose, add a schema and a retry loop, as in structured JSON output from LLMs. When prompts start to run inside chains, the fake-model test in building your first LLM chain applies the same idea with LangChain. And when an agent built from these prompts misbehaves, debugging AI agents covers how to trace it.
Start small: put your three most-used prompts in prompts.json, write one case for each, and run the harness before every change.
Frequently asked questions
How do I version prompts?
Store them in a file in Git and give each prompt an id with a version suffix, such as code-refactor-v2. OpenAI's prompt engineering guide also recommends keeping production prompts in your application code. Git then gives you a diff and a message for every change.
How many test cases does a prompt need?
Start with one per prompt, built from a real input. Add a new case every time the prompt fails in real use. A handful of cases that cover past failures is more useful than many cases that all test the easy path.
Is LLM-as-a-judge reliable?
It is useful but not exact. Give the judge a clear rubric, ask for a reason before the score, and use a different model from the one that wrote the output, as Anthropic's evaluation guide suggests. Spot-check its grades by hand.
Do I need a framework for prompt evals?
Not to start. A JSON file of prompts, a JSON file of cases and a short script cover a personal system. Move to a dedicated eval tool when you need dashboards, team review or many models at once.
Should I set temperature for prompt tests?
Only if your model's documentation lists the parameter, since support varies by model. Check the model's page before you add it. Saved test cases and repeated runs tell you more about consistency than one setting.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...