Skip to main content

AI and machine learning · Beginner · 20 min

Write a system prompt that sets the role, the rules and the output format

By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15.2 · anthropic 2.14.0 · Claude Opus 5.5

You will turn a one-line prompt into a structured system prompt for a solar installer's support assistant, keep it in a template file that Python renders, and prove with deterministic tests that it is built correctly, stays cacheable and has a format your code can parse.

On this page

A system prompt is the standing brief a language model reads before every conversation in your app. Most first drafts are one line long, something like "You are a helpful assistant for a solar company". The model then has to guess who it is talking to, what it may promise, what to do when it does not know, and what shape the answer should take. It guesses differently each time, and your code cannot rely on any of it.

This tutorial builds a better one for a made-up company, Sunbase Solar, which installs solar panels, inverters and batteries in Lagos and Ogun State. Its support assistant answers customers on WhatsApp and the website. You will write the prompt as a template file with clearly tagged sections, render it with Python's standard library, keep the parts that change per message out of it, and write tests that catch a broken prompt before it ships.

Steps 1 to 7 need only Python. Step 8 sends the finished prompt to Claude and needs an API key.

Step 1 · Start from the one-line prompt and list what it leaves out

Create a throwaway project folder and save the first draft, so you can compare it with the finished prompt later:

Bash
mkdir -p ~/prompt-demo/prompts ~/prompt-demo/knowledge
cd ~/prompt-demo
python3 --version
cat > prompts/v0.txt <<'TXT'
You are a helpful assistant for a solar company. Answer customer questions.
TXT

Read it as the model would. It does not say:

  • Who is asking. A homeowner with a beeping inverter needs different words from an engineer.
  • What the facts are. Without the company's own policies, the model fills gaps from general knowledge, which may be wrong for this company.
  • What is off limits. Should it quote prices? Ask for payment details? Tell someone to open an inverter?
  • What to do when it does not know. If you never say, a model tends to produce a plausible answer instead.
  • What the reply looks like. Your code needs to know whether a person must follow up, and the reply has to fit a phone screen.

Each gap becomes a section of the new prompt.

Check it worked

python3 --version prints Python 3.15 followed by a patch number, and cat prompts/v0.txt shows the single line. Keep the five gaps in mind: by the end of step 3 each one has its own tagged section.

Step 2 · Put the reference facts in their own file

The facts the assistant may use belong in a separate file. Support staff can then update a warranty term without touching the instructions, and the prompt can wrap the file in one tagged block so the model can tell facts from rules.

Bash
cat > knowledge/faq.md <<'MD'
## Service area
Sunbase Solar installs and services systems in Lagos State and in Ogun State (Abeokuta, Sagamu and Ota). Outside these areas we can recommend a partner installer.

## Site surveys
A site survey is free in our service area. Surveys run Monday to Saturday, 9am to 4pm, and take about 90 minutes. The surveyor checks the roof, measures your daily power use and prepares a written quote.

## Products
We install monocrystalline solar panels, hybrid inverters (3.6 kVA and 6 kVA) and lithium iron phosphate (LiFePO4) batteries in 5 kWh and 10 kWh sizes.

## Warranty
Panels carry a 25-year performance warranty. Inverters carry a 5-year warranty. Batteries carry a 6-year or 6,000-cycle warranty, whichever comes first. A warranty claim needs the serial number from the label on the side of the unit.

## Quotes and payment
A quote is valid for 14 days. We take a 60% deposit to order equipment and the remaining 40% on the day of installation. Payment is by bank transfer to the account printed on the quote. Installers never collect cash.

## Cleaning and maintenance
Rinse panels with clean water every two to three months, and more often during harmattan, when dust cuts output. Never stand on the panels. A yearly service visit checks the wiring, the inverter settings and the battery health.

## Inverter alarms
A beeping inverter usually means the battery is low or the load is too high. Switch off heavy appliances such as pumping machines, irons and air conditioners and wait ten minutes. If the alarm continues or a red fault light stays on, contact support with a photo of the inverter screen.
MD

The file uses ## headings. The tests in step 7 use them to confirm that every topic reaches the rendered prompt.

Check it worked

Bash
grep -c '^## ' knowledge/faq.md

The output is 7, one per topic.

Step 3 · Write the system prompt as a template

Now write the prompt itself. Each part sits inside an XML-style tag. The tags are not special syntax to the model; they are clear labels, so it can tell the instructions, the reference facts and the format apart, and so your tests can find each part.

The template has three placeholders, written $company_name, $city and $knowledge. Python's string.Template fills them in. A literal dollar sign in the template would have to be written $$, so this prompt avoids one.

Bash
cat > prompts/support_system.txt <<'TXT'
<role>
You are the customer support assistant for $company_name, a solar installer based in $city.
You answer messages from homeowners and small business owners who use, or are thinking about buying, a solar system from $company_name. They are not engineers. Most write from a phone, and many mix English with Nigerian Pidgin or Yoruba.
</role>

<task>
Answer the customer's question using only the facts inside <knowledge>. Where it helps, point them to the next step: booking a free site survey, making a warranty claim or trying a safe first fix.
</task>

<rules>
Always:
- Reply in the language the customer wrote in, in short, plain sentences. Keep the reply under 120 words, because many customers read on prepaid mobile data.
- If a message mentions sparks, smoke, a burning smell or water near the inverter or batteries, tell the customer to switch the system off at the isolator, keep people away from it and call the emergency number on their warranty card. Then hand the conversation to a person.
- Use the customer's name once if it is given.

Never:
- Quote a price, a discount or a payment total. Prices change with the exchange rate, so offer a free site survey and a written quote instead.
- Ask for card numbers, bank PINs, passwords or one-time codes. Sunbase Solar is paid by bank transfer to the account printed on a quote, never through chat.
- Tell a customer to open an inverter or battery casing. They hold dangerous voltages even when switched off.
- Promise an installation date or a visit time. Only the scheduling team can confirm those.
</rules>

<when_unsure>
If the facts in <knowledge> do not answer the question, do not guess. Say: "I don't have that information, so I'm passing your message to our team." Then hand the conversation to a person. This applies to figures, dates, technical specifications and anything about another company's products.
</when_unsure>

<knowledge>
$knowledge
</knowledge>

<output_format>
Write exactly two parts, in this order, and nothing before or after them:
<reply>The message the customer will see, as plain text with no Markdown.</reply>
<handoff>yes or no</handoff>
Write yes when a person must follow up: a safety problem, a complaint, a question the knowledge does not answer, or a customer who asks for a human. Otherwise write no.
</output_format>
TXT

What each section does:

  • <role> says who the assistant is and, just as important, who the audience is. That one paragraph shapes vocabulary and tone more than a list of style rules would.
  • <task> limits the assistant to the facts provided and names the outcomes the business wants.
  • <rules> gives the do and do-not lists, each with its reason. A reason lets the model apply the rule to cases you did not list: "prices change with the exchange rate" also covers a customer asking "roughly how much?".
  • <when_unsure> gives the model a sentence to use when the facts run out. Without permission to say "I don't know", models are more likely to invent an answer.
  • <knowledge> holds the reference file from step 2.
  • <output_format> describes the exact shape of the answer, so code can split the customer message from the handoff flag.

Check it worked

Bash
grep -o '^<[a-z_]*>$' prompts/support_system.txt

The output lists six opening tags in order: <role>, <task>, <rules>, <when_unsure>, <knowledge> and <output_format>. Compare them with the five gaps from step 1: audience, facts, limits, uncertainty and format each have a home.

Step 4 · Render the template with Python

Write prompt.py. It loads the template, fills in the company details and the knowledge file, and prints the result. It uses only the standard library.

Bash
cat > prompt.py <<'PY'
import re
from pathlib import Path
from string import Template

HERE = Path(__file__).parent
MODEL = "claude-opus-5-5"
MAX_TOKENS = 4000

COMPANY = {"company_name": "Sunbase Solar", "city": "Lagos"}


def load(name):
    return Template((HERE / "prompts" / name).read_text(encoding="utf-8"))


def render_system():
    knowledge = (HERE / "knowledge" / "faq.md").read_text(encoding="utf-8").strip()
    return load("support_system.txt").substitute(COMPANY, knowledge=knowledge)


if __name__ == "__main__":
    print(render_system())
PY
python3 prompt.py > rendered.txt
head -n 3 rendered.txt

substitute raises a KeyError if any placeholder has no value. That is what you want: a prompt that silently goes out with $knowledge in it would leave the assistant with no facts at all. The other method, safe_substitute, leaves unknown placeholders in place without complaint, so do not use it for prompts.

Check it worked

The first three lines of rendered.txt read <role>, then You are the customer support assistant for Sunbase Solar, a solar installer based in Lagos., then the line about homeowners. Confirm that no placeholder survived and that the facts arrived:

Bash
python3 - <<'PY'
text = open("rendered.txt", encoding="utf-8").read()
assert "$" not in text, "a placeholder was not filled in"
assert "6,000-cycle warranty" in text, "the knowledge file is missing"
print(f"ok: {len(text)} characters, no placeholders left")
PY

The output starts with ok: and gives the length, just under 4,000 characters.

Step 5 · Keep names and dates out of the system prompt

The customer's name and today's date are useful to the model, so it is tempting to put them in the system prompt. Don't. Providers cache the start of a request that repeats exactly, which makes repeat calls cheaper and faster. Caching works on a prefix: change one character near the start and everything after it is sent at full price again. A system prompt that holds a name or a date is different for every customer and every day, so it never hits the cache.

Put the parts that change in the user turn instead, with their own small template:

Bash
cat > prompts/support_user.txt <<'TXT'
<context>
Customer name: $customer_name
Today's date: $today
</context>

<question>
$question
</question>
TXT

Then add the request builder to prompt.py. It returns the arguments for a call to the Messages API: the model, the token limit, the system prompt as a block marked for caching, and the user turn. Append it to the file:

Bash
cat >> prompt.py <<'PY'


def render_user(customer_name, today, question):
    return load("support_user.txt").substitute(
        customer_name=customer_name,
        today=today.isoformat(),
        question=question.strip(),
    )


def build_request(customer_name, today, question):
    return {
        "model": MODEL,
        "max_tokens": MAX_TOKENS,
        "output_config": {"effort": "low"},
        "system": [
            {
                "type": "text",
                "text": render_system(),
                "cache_control": {"type": "ephemeral"},
            }
        ],
        "messages": [
            {"role": "user", "content": render_user(customer_name, today, question)}
        ],
    }
PY

cache_control marks the end of the part you want cached. output_config sets the effort level: Claude Opus 5.5 always thinks before it answers, the thinking counts toward max_tokens, and a short support reply rarely needs deep reasoning. That is also why MAX_TOKENS is 4,000 rather than a few hundred, even though the reply itself is under 120 words.

Now build two requests for different customers on different days and compare them:

Bash
cat > compare.py <<'PY'
import datetime
import hashlib

from prompt import build_request

a = build_request("Funke", datetime.date(2026, 11, 18), "Do you install in Ibadan?")
b = build_request("Emeka", datetime.date(2026, 11, 19), "My inverter is beeping.")

for name, request in (("Funke", a), ("Emeka", b)):
    system = request["system"][0]["text"]
    digest = hashlib.sha256(system.encode()).hexdigest()[:12]
    print(name, "system prompt", digest)

print(b["messages"][0]["content"])
PY
python3 compare.py

Check it worked

Both lines print the same 12-character fingerprint, so the system prompt is byte for byte identical for both customers and both days. Below them, Emeka's user turn shows his name, 2026-11-19 and his question inside <question> tags. Only that part changes between calls.

Step 6 · Parse the output format in code

The <output_format> section is a contract between the prompt and your code. Write the code side now, a function that extracts the reply and the handoff flag and refuses anything that breaks the format. Append it to prompt.py:

Bash
cat >> prompt.py <<'PY'


REPLY_PATTERN = re.compile(
    r"\s*<reply>(?P<reply>.+?)</reply>\s*<handoff>(?P<handoff>yes|no)</handoff>\s*",
    re.DOTALL,
)


def parse_reply(text):
    match = REPLY_PATTERN.fullmatch(text)
    if not match:
        raise ValueError("the model's answer does not follow the output format")
    return match.group("reply").strip(), match.group("handoff") == "yes"
PY

fullmatch means nothing is allowed before <reply> or after </handoff>, apart from whitespace. A preamble such as "Sure, here is my answer" fails, which is the point: you find out at once rather than sending it to a customer.

Try it on three answers of the kind a model might give:

Bash
cat > samples.py <<'PY'
from prompt import parse_reply

samples = {
    "good": "<reply>Hello Funke, we don't cover Ibadan yet, but we can recommend a partner installer.</reply>\n<handoff>no</handoff>",
    "preamble": "Sure! Here is the reply.\n<reply>Hello.</reply>\n<handoff>no</handoff>",
    "unsure flag": "<reply>Let me check.</reply>\n<handoff>maybe</handoff>",
}

for name, text in samples.items():
    try:
        reply, handoff = parse_reply(text)
        print(f"{name}: accepted, handoff={handoff}")
    except ValueError as error:
        print(f"{name}: rejected ({error})")
PY
python3 samples.py

Check it worked

The output has three lines: good: accepted, handoff=False, then preamble: rejected (...) and unsure flag: rejected (...). In your app, a rejected answer should go to a person or be retried. It should never be shown to the customer as it is.

If your code needs several fields rather than one message and a flag, structured outputs, which force the answer to match a JSON schema, are a stronger guarantee than a format described in words. The tutorial on getting structured JSON output covers them.

Step 7 · Write deterministic tests for the prompt

The prompt is now code: a template, a data file and a builder. Like any code it can break quietly, through a renamed placeholder, a deleted section or someone adding today's date to the template. These tests use Python's built-in unittest and need no model and no network, so they give the same result every run:

Bash
cat > test_prompt.py <<'PY'
import datetime
import re
import unittest
from pathlib import Path

from prompt import build_request, load, parse_reply, render_system

SECTIONS = ["role", "task", "rules", "when_unsure", "knowledge", "output_format"]
DAY_ONE = datetime.date(2026, 11, 18)
DAY_TWO = datetime.date(2026, 11, 19)


class SystemPromptTests(unittest.TestCase):
    def setUp(self):
        self.system = render_system()

    def test_no_placeholder_is_left(self):
        self.assertNotIn("$", self.system)

    def test_every_section_appears_once_in_order(self):
        # A section tag sits alone on its line; the prose may mention <knowledge>.
        lines = self.system.splitlines()
        positions = []
        for tag in SECTIONS:
            self.assertEqual(lines.count(f"<{tag}>"), 1, tag)
            self.assertEqual(lines.count(f"</{tag}>"), 1, tag)
            positions.append(lines.index(f"<{tag}>"))
        self.assertEqual(positions, sorted(positions))

    def test_every_knowledge_topic_is_inside_the_knowledge_block(self):
        block = self.system.split("\n<knowledge>\n")[1].split("\n</knowledge>")[0]
        faq = Path("knowledge/faq.md").read_text(encoding="utf-8")
        for heading in re.findall(r"^## (.+)$", faq, re.MULTILINE):
            self.assertIn(heading, block)

    def test_prompt_stays_within_its_size_budget(self):
        # About 2,000 tokens at roughly four characters per token.
        self.assertLess(len(self.system), 8000)


class RequestTests(unittest.TestCase):
    def test_system_prompt_is_identical_across_customers_and_days(self):
        a = build_request("Funke", DAY_ONE, "Do you install in Ibadan?")
        b = build_request("Emeka", DAY_TWO, "My inverter is beeping.")
        self.assertEqual(a["system"], b["system"])
        self.assertEqual(a["system"][-1]["cache_control"], {"type": "ephemeral"})

    def test_names_and_dates_go_in_the_user_turn_only(self):
        request = build_request("Funke", DAY_ONE, "Do you install in Ibadan?")
        system = request["system"][0]["text"]
        user = request["messages"][0]["content"]
        for volatile in ("Funke", "2026-11-18"):
            self.assertNotIn(volatile, system)
            self.assertIn(volatile, user)
        self.assertIn("<question>\nDo you install in Ibadan?\n</question>", user)

    def test_a_missing_value_fails_loudly(self):
        with self.assertRaises(KeyError):
            load("support_user.txt").substitute(customer_name="Funke", today="2026-11-18")


class OutputFormatTests(unittest.TestCase):
    def test_a_well_formed_answer_is_parsed(self):
        reply, handoff = parse_reply("<reply>Please switch off at the isolator.</reply>\n<handoff>yes</handoff>")
        self.assertEqual(reply, "Please switch off at the isolator.")
        self.assertTrue(handoff)

    def test_text_outside_the_tags_is_rejected(self):
        with self.assertRaises(ValueError):
            parse_reply("Here you go:\n<reply>Hello.</reply>\n<handoff>no</handoff>")

    def test_a_missing_handoff_is_rejected(self):
        with self.assertRaises(ValueError):
            parse_reply("<reply>Hello.</reply>")


if __name__ == "__main__":
    unittest.main()
PY
python3 -m unittest -v test_prompt

What they protect:

  • The placeholder, section and knowledge tests catch a template or data file that changed shape.
  • The size test makes growth a decision. A system prompt is sent on every call, so each extra paragraph costs money on every message.
  • The two request tests guard the cache: if someone moves the date into the system prompt, they fail.
  • The format tests pin down the contract from step 6.

Run them in your CI pipeline whenever the prompt, the knowledge file or prompt.py changes.

Check it worked

The output lists ten tests, each ending in ok, then Ran 10 tests and OK. To see a test catch a real mistake, add the line Today's date: $today to the end of prompts/support_system.txt and run the tests again: render_system raises a KeyError because $today has no value there, and the six tests that render the system prompt end in ERROR. Remove the line, and the tests pass again.

Step 8 · Send the prompt to a model and read the answers yourself

The tests prove the prompt is assembled correctly. They do not prove a model follows it. That needs real calls and a person reading the results. This step needs the API key from the tutorial on calling an LLM API from Python, available in the ANTHROPIC_API_KEY environment variable. Never paste the key into a file in this folder.

Install the SDK into a virtual environment in the project:

Bash
cd ~/prompt-demo
python3 -m venv .venv
. .venv/bin/activate
pip install anthropic==2.14.0

Create ask.py. It builds the request with the code you have tested, sends it, checks why the model stopped, and parses the answer:

Python
import datetime
import sys

import anthropic

from prompt import build_request, parse_reply

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
request = build_request("Funke", datetime.date.today(), sys.argv[1])
response = client.messages.create(**request)

if response.stop_reason == "max_tokens":
    raise SystemExit("Stopped at max_tokens before the reply was complete; raise MAX_TOKENS.")
if response.stop_reason == "refusal":
    raise SystemExit("The model declined this request; send it to a person.")

text = "".join(block.text for block in response.content if block.type == "text")
reply, handoff = parse_reply(text)
print(reply)
print("handoff:", handoff)
print("cache written:", response.usage.cache_creation_input_tokens)
print("cache read:", response.usage.cache_read_input_tokens)

Ask it a few questions, including ones the knowledge does not answer:

Bash
python3 ask.py "Do you install in Abeokuta, and how much is a 5 kWh battery?"
python3 ask.py "Abeg, my inverter dey beep since morning. Wetin I go do?"
python3 ask.py "I see small smoke near my battery"

Read each answer against the rules, one by one: is the reply in the customer's language, under 120 words, free of prices, and is handoff true for the smoke message and for anything the knowledge does not cover? Read at least 20 answers across real kinds of customer questions before you put the assistant in front of customers. A model's answers vary, and a careful prompt makes mistakes less likely, not impossible. When a rule is broken, change the prompt, re-run the tests from step 7, and read the answers again.

Check it worked

Each command prints a short reply, a handoff: line and two cache lines. The price question gets no figure and an offer of a free survey. The Pidgin question gets a reply in Pidgin with the safe first fix from the knowledge file. The smoke message gets the isolator instruction and handoff: True. On the first call, cache written is above zero. Run the same command again within five minutes and cache read is above zero instead: the system prompt came from the cache. If both stay at zero, the prompt is shorter than the model's minimum cacheable length, which differs by model and is listed in Anthropic's prompt caching documentation. No error is raised in that case. When you are done, remove the folder with rm -rf ~/prompt-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.