Sub topic 1
What a System Prompt Is and How Roles Work
A system prompt is the block of instructions your application sends to a language model before any user input. It defines the model's job, limits, and output format for a whole conversation. This chapter explains how the system prompt fits into the message list the model receives, what each role means, and which mistakes come from misreading that structure.
Prerequisites
This chapter assumes you have:
- Called an LLM chat API at least once and seen a request with a list of messages.
- Basic familiarity with JSON, since messages are JSON objects.
- Enough Python to read short functions and dictionaries.
You do not need to know any specific provider's SDK. The examples use a provider-neutral message format.
The model sees one sequence of text
A chat API looks like a conversation with separate parties. Internally, the provider converts your messages into a single sequence of tokens, adding special markers that show where each message starts and which role wrote it. The model then predicts the next message in that sequence.
Three consequences follow from this:
- The model has no memory between calls. If you want it to remember an earlier turn, you must send that turn again.
- The system prompt is not stored on the provider's side. You send it with every request.
- Roles are a convention the model was trained to respect. They work well, but they are not an access-control system.
The roles
Most chat APIs define the same small set of roles.
| Role | Written by | Purpose |
|---|---|---|
| system | You, the developer | Standing instructions: task, rules, format, tone |
| user | The end user, or your code on their behalf | The request for this turn, plus any data you attach |
| assistant | The model (or your code, to replay history) | Earlier model replies, and tool call requests |
| tool | Your code | The result of a tool the model asked to run |
Some providers add variations. OpenAI's newer models use a developer role for the same purpose that system served before. Anthropic's Messages API takes the system prompt as a separate top-level system parameter instead of a message in the list. Gemini calls it system_instruction. The names differ, but the idea is the same: a privileged slot for the developer's instructions. Check your provider's documentation for the exact field.
A minimal provider-neutral message list looks like this:
messages = [
{"role": "system", "content": "You are a concise assistant for Acme Billing. Answer in two sentences or fewer."},
{"role": "user", "content": "What is a pro-rated charge?"},
{"role": "assistant", "content": "A pro-rated charge covers only part of a billing period. It is calculated from the number of days you used the service."},
{"role": "user", "content": "And when does it apply?"},
]The final user message is the one the model answers. The earlier assistant message is not a memory. It is text you chose to include, and you could edit it before sending.
How a request flows
The diagram shows what happens on every turn of a chat application.
Your application owns the history. If you drop old turns to save tokens, the model forgets them. If you forget to resend the system prompt, the model loses all your rules on that turn.
What belongs in the system prompt
Put instructions there that stay true for the whole session or for every user:
- The task and role of the assistant.
- Rules and limits that always apply.
- The output format.
- How to treat data that arrives in later messages.
Put things that change per request in the user message: the question, retrieved documents, the current date, user preferences. A common pattern is a fixed system prompt plus a user message built from a template each turn.
Here is a small, complete example. It uses a placeholder function in place of a real API call, so you can run it to see what your application would send.
import json
SYSTEM_PROMPT = (
"You are a support assistant for Acme Billing. "
"Answer questions about invoices and payments. "
"If you do not know, say so."
)
def build_request(history: list[dict], user_text: str) -> list[dict]:
"""Return the full message list for this turn."""
return (
[{"role": "system", "content": SYSTEM_PROMPT}]
+ history
+ [{"role": "user", "content": user_text}]
)
history: list[dict] = []
request = build_request(history, "Why was I charged twice?")
print(json.dumps(request, indent=2))
# After the model replies, you must store both sides yourself.
history.append({"role": "user", "content": "Why was I charged twice?"})
history.append({"role": "assistant", "content": "I can't see your account, but duplicate charges often come from a retried payment."})Running it prints a list whose first element is the system message. Nothing in the API stores the conversation for you, so the two append calls at the end are required for the next turn to have context.
Why placement matters
Models are trained to give system instructions more weight than user text. That weight helps in three practical ways.
- Persistence. Instructions in the system slot are resent on every turn, so they are still present at turn 50.
- Priority. When a user message conflicts with the system prompt, a well-trained model usually follows the system prompt. "Usually" is the key word, and a later chapter covers what to do when it fails.
- Separation. Keeping instructions apart from user data makes it easier to treat the data as data.
Placement is not a guarantee. A long conversation can push the system prompt far from the end of the context, and models tend to attend more closely to recent text. If a rule keeps slipping in long sessions, restating it briefly in a late message is a legitimate fix, as long as the system prompt remains the primary source.
A second practical effect is cost. Many providers cache a repeated prefix of the request, so a stable system prompt at the start can be cheaper and faster than one that changes every call. Putting a timestamp or a username at the top of the system prompt breaks that caching. Put changing values after the stable text, or in the user message.
System prompt versus other ways to shape behavior
| Approach | Good for | Limit |
|---|---|---|
| System prompt | Rules, role, format that apply to every request | Costs tokens on every call, and the model may not follow it perfectly |
| User message content | Per-request data and questions | Mixed with untrusted input |
| Few-shot examples in messages | Showing a format or style | Uses context, and examples can be copied too literally |
| Fine-tuning | Consistent style or narrow tasks at scale | Slower to change, needs training data |
| Application code | Hard guarantees such as permissions and validation | Cannot handle language-level judgment |
Use the system prompt for behavior you want to describe in words. Use code for anything that must always hold, such as "never reveal another customer's data". The model should not be the only thing standing between a user and information they should not see.
Common errors
Treating the system prompt as secret. Users can often coax a model into repeating its instructions. Do not put API keys, internal URLs, or anything else sensitive in it. Assume anyone who uses your app could read the system prompt.
Treating the system prompt as a security boundary. A rule like "never reveal the discount codes" in the prompt reduces the chance of a leak. It does not prevent one. Enforce access in code, and keep sensitive data out of the context entirely.
Forgetting to resend it. With stateless APIs, a refactor that rebuilds the message list without the system message produces a model that suddenly ignores your rules. Test that the first message of every request is the system prompt.
Putting user data in the system prompt. Inserting a user's name, message, or uploaded document directly into the system string gives untrusted text the same authority as your instructions. Keep it in the user message, clearly marked as data.
Putting everything in the system prompt. A system prompt of 3,000 words is hard to maintain, and the important rules get lost among the unimportant ones. Keep it as short as the task allows.
Expecting a different role to mean a different mind. If you place instructions in an assistant message, the model may treat them as something it said earlier, not as a rule. Use each role for its purpose.
Mixing up provider formats. Sending {"role": "system"} inside the messages list to an API that expects a top-level system field can cause an error or be silently ignored, depending on the provider. If a system prompt appears to have no effect, check the request body first, before rewriting the prompt.
Tool messages
When you give the model tools (functions it can ask your code to run), two more message types appear. The assistant message may contain a tool call request instead of text. Your code runs the tool and sends the result back in a tool message. The model then continues. These messages are data from your systems, and later chapters cover how to write instructions for them. For now, note that they fit the same pattern: you send the whole sequence again each turn.
Summary of the working model
- The model receives one sequence built from your message list, with role markers.
- You own the history and resend it, including the system prompt, on every request.
- The system role carries standing instructions, and the user role carries per-request input.
- Roles influence priority, but they do not enforce security.
- Stable content first and changing content later helps both clarity and caching.
Exercise
A teammate's chatbot works well for the first reply but ignores all formatting rules from the second reply onward. The code builds the list as history + [user_message] after the first turn, and adds the system message only when history is empty. What is the bug, and how do you fix it?
Show answer
The system message is sent only on the first turn. The API is stateless, so every request must include the system prompt. Fix it by building the list as [system_message] + history + [user_message] on every call, and add a test that asserts the first message of each request has the role "system" (or that the top-level system field is set, for providers that use one).
Exercise
You want the assistant to greet users by name and to never give tax advice. Which of these goes in the system prompt, which goes in the user message, and why? Which should also be enforced in application code if a violation would cause real harm?
Show answer
"Never give tax advice" is a standing rule, so it belongs in the system prompt. The user's name changes per request, so it belongs in the user message (or after the stable part of the prompt, to protect prefix caching). The tax rule is a policy that the model might occasionally break, so if a violation has serious consequences, add a code-level check such as an output filter or a human review step. Do not rely on the prompt alone.