Sub topic 12
Using the Voice Guide as a System Prompt in Code
This chapter shows how to send your voice guide to an AI model from your own code. It assumes you have a working voice guide from the earlier chapters, basic Python skills, and an API key for the model provider. The examples use the Anthropic Python SDK, but the same idea applies to other providers.
What a system prompt is
A system prompt is a block of text that you send with every API request. It sets the assistant's role, tone, and rules before the user's message arrives. In a chat app, the custom instructions you saved in settings or a project do this job for you. In code, nothing is saved on your behalf. Each request must carry the instructions, or the model won't see them.
This has three consequences:
- The API doesn't remember earlier requests. Every call needs the voice guide again.
- You control exactly which version of the guide each request uses.
- Any code path that forgets to send the guide produces unbranded output.
The system prompt is separate from the conversation. In the Anthropic API it is the system parameter, and the messages list holds only user and assistant turns. Keep the voice guide in system. Put the task itself, such as "Draft a welcome email", in the user message.
Where the code fits in the layers
An earlier chapter described layers: account-level, project-level, and conversation-level instructions. API calls skip the first two. Your code is the only layer, so the system prompt has to hold everything those layers would have held.
Store the guide in a file
Keep the voice guide in its own file, such as voice_guide.md, and not inside your Python source. This gives you three benefits:
- Writers can edit the guide without touching code.
- Version control shows exactly what changed between revisions.
- The same file can be pasted into a chat app's custom instructions, so the chat and API versions stay identical.
Here is the guide used throughout this chapter. Save it as voice_guide.md.
You write on behalf of Brightleaf, a bookkeeping app for freelancers.
Voice: friendly, plain-spoken, and practical. Write like a knowledgeable colleague, not a salesperson.
Do:
- Use second person ("you") and contractions.
- Keep sentences under 25 words.
- Lead with the answer, then give the reason.
Don't:
- Use jargon such as "synergy" or "leverage".
- Use more than one exclamation mark per piece.
- State prices, legal, or tax claims unless they appear in the text I provide.
Example:
Instead of: "Our solution empowers you to streamline invoicing!"
Write: "Send an invoice in two clicks and see when it's paid."
If you lack information, ask a question instead of guessing.A minimal request
This script reads the file and passes its contents as the system prompt.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
with open("voice_guide.md", encoding="utf-8") as f:
voice_guide = f.read()
response = client.messages.create(
model="YOUR_MODEL_ID", # replace with a model ID available to your account
max_tokens=500,
system=voice_guide,
messages=[
{"role": "user", "content": "Draft a two-sentence welcome email for new users."}
],
)
print(response.content[0].text)Points to check before you run it:
- Install the SDK with
pip install anthropic. - Set
ANTHROPIC_API_KEYin your environment. Never write the key into the source file or the voice guide. - Replace
YOUR_MODEL_IDwith a real model ID from your account. The placeholder will fail with an error. - Run the script from the folder that contains
voice_guide.md, or use an absolute path.
max_tokens caps the length of the reply. If the cap is too low, the text is cut off mid-sentence. This can look like a voice problem when it's a limit problem. Check response.stop_reason. A value of max_tokens means the reply was truncated.
Reuse the guide across many tasks
Real applications make many calls. Load the file once and wrap the call in a function, so no caller can skip the guide.
import anthropic
client = anthropic.Anthropic()
def load_guide(path: str = "voice_guide.md") -> str:
with open(path, encoding="utf-8") as f:
return f.read()
VOICE_GUIDE = load_guide()
def write_on_brand(task: str, source_text: str = "", max_tokens: int = 500) -> str:
"""Return a draft that follows the voice guide."""
content = task
if source_text:
content += "\n\nUse only the facts in this text:\n" + source_text
response = client.messages.create(
model="YOUR_MODEL_ID", # replace with a model ID available to your account
max_tokens=max_tokens,
system=VOICE_GUIDE,
messages=[{"role": "user", "content": content}],
)
if response.stop_reason == "max_tokens":
raise RuntimeError("Reply was cut off. Raise max_tokens.")
return response.content[0].text
if __name__ == "__main__":
print(write_on_brand("Explain what an invoice reminder is, in one short paragraph."))The source_text argument supports the guardrail in the guide. The guide says not to state prices or tax claims "unless they appear in the text I provide." Your code is where that text is provided. If a task needs a price, pass the pricing page text in source_text. If you don't, the model should ask a question, as the guide instructs.
Keep the guide and the task apart
Mixing the two causes common errors.
| Mistake | What goes wrong | Fix |
|---|---|---|
| Pasting the guide into every user message | The guide gets repeated, and users can see or edit it in a chat interface | Send it once in `system` |
| Putting task details in the guide | The guide grows and drifts toward one use case | Pass task details in the user message |
| Building the system prompt from user input | A user can insert text that overrides your rules | Treat user text as data in the user message only |
| Hard-coding the guide in a string | Edits need a code deploy and are hard to review | Load it from a file |
The third row matters for security. If your app takes text from customers, don't concatenate it into the system prompt. Keep it in the user message, and keep your rules in the system prompt. This doesn't make the model immune to instructions hidden in customer text, so the guardrails in your guide still need testing.
Test through the API
The test list from the testing chapter works the same way in code. Run each test prompt through your function, so you test the real path including the system prompt, not a chat window that may have different settings.
TEST_PROMPTS = [
"Write a two-sentence welcome email for a new user.",
"Explain what an invoice reminder is, in one short paragraph.",
"Reply to a customer who is upset about a late payment notice.",
"How much does the Pro plan cost?",
]
for number, prompt in enumerate(TEST_PROMPTS, start=1):
reply = write_on_brand(prompt)
print(f"--- Prompt {number}: {prompt}")
print(reply)
print()Add this loop to a file that imports write_on_brand. Then read each reply against the checklist: second person and contractions, sentences under 25 words, no banned jargon, at most one exclamation mark, and no invented prices.
Some checks can be automated because they are countable. This function tests the exclamation mark rule and a banned word list.
import re
BANNED_WORDS = ["synergy", "leverage"]
def check_basic_rules(text: str) -> list[str]:
problems = []
if text.count("!") > 1:
problems.append("More than one exclamation mark")
for word in BANNED_WORDS:
if re.search(rf"\b{word}\w*\b", text, flags=re.IGNORECASE):
problems.append(f"Banned word: {word}")
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
for s in sentences:
if len(s.split()) >= 25:
problems.append(f"Long sentence: {s[:40]}...")
return problemsAutomated checks catch rule breaks. They can't judge whether the reply sounds like a knowledgeable colleague. A person still needs to read a sample of the output.
Randomness and repeat runs
Model output varies from run to run. One good reply doesn't prove the guide works. Run each test prompt several times, for example three to five, and look for rules that break only some of the time. An intermittent failure usually means an instruction is ambiguous or buried. Move the rule higher in the guide, state it more plainly, or add an example.
Common errors
- Authentication error. The environment variable
ANTHROPIC_API_KEYis missing or wrong in the shell that runs the script. - Model not found. The model ID is a placeholder or isn't available to your account.
- File not found. The script runs from a different working directory than the guide's location.
- Unbranded output. A code path calls the API directly and skips
write_on_brand. Search your codebase for directmessages.createcalls. - Drift after edits. Someone changed
voice_guide.mdwithout rerunning the test list. Rerun it after every change. - Truncated replies.
max_tokensis too low for the task.
Record which version you used
When a draft looks wrong, you will want to know which guide produced it. Store a version label in the file's name or in version control, and log it with each request. Even a simple log line with the date and the guide's commit hash lets you reproduce a result. The maintenance chapter covers sharing and versioning the guide across a team in more detail.
Exercise
Your app calls the API with a customer's pasted message. A teammate suggests adding the customer's text to the end of the system prompt so the model "has more context". Why is this a bad idea, and where should the text go instead?
Show answer
The system prompt holds your trusted rules. If customer text is appended to it, the customer can write instructions that look like part of your rules and override them. The customer's text should go in the user message, labeled as the material to work from, while the voice guide stays alone in the system parameter.
Exercise
You run the welcome-email prompt five times. Four replies follow the "under 25 words" rule, and one doesn't. What should you do, and what does the result tell you?
Show answer
The rule is only partly working, so the instruction is probably ambiguous, buried, or lacking an example. Rewrite it more plainly, move it higher in the guide, or add a before-and-after example. Then rerun the full test list several times, because a single passing run would not show whether the fix worked.
Exercise
Write a short Python snippet that reads voice_guide.md and sends it as the system prompt, and name the two values you must replace before it runs.
Show answer
Load the file with open("voiceguide.md", encoding="utf-8"), read it into a string, and pass that string as system= in client.messages.create(...), with the task in the messages list. You must replace the model ID placeholder with a real model ID and make sure ANTHROPICAPI_KEY is set in the environment.