Sub topic 10
OpenAI-style and Anthropic-style system prompts compared
This chapter assumes you can read basic Python, work with lists and dictionaries, and have seen a chat message as a dictionary with a role and content. It also assumes you know that chat APIs are stateless, so you send the whole history on every call. Here you will compare the two most common ways of passing a system prompt, see what breaks when you move code between them, and learn how to write a thin layer that hides the difference.
The two layouts
Both layouts carry the same information: instructions for the model, then a conversation. They differ in where the instructions live.
- OpenAI-style (Chat Completions): the system prompt is the first item in the
messageslist, with"role": "system". - Anthropic-style (Messages API): the system prompt is a separate top-level
systemparameter. Themessageslist holds onlyuserandassistantturns.
Here is the OpenAI-style call:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="MODEL_NAME", # replace with a chat model available to you
messages=[
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."},
{"role": "user", "content": "What is a list in Python?"},
],
)
print(response.choices[0].message.content)Here is the Anthropic-style call:
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="MODEL_NAME", # replace with a model available to you
max_tokens=300,
system="You are a helpful assistant. Keep answers under three sentences.",
messages=[
{"role": "user", "content": "What is a list in Python?"},
],
)
print(response.content[0].text)The diagram shows where the instructions sit in each request.
Differences that affect your code
The placement is the visible difference. Several smaller differences follow from it.
| Aspect | OpenAI-style Chat Completions | Anthropic-style Messages |
|---|---|---|
| System prompt location | First entry in `messages` | Top-level `system` parameter |
| Roles allowed in `messages` | `system`, `user`, `assistant` (plus `tool` and newer roles) | `user` and `assistant` |
| Response text | `response.choices[0].message.content` | `response.content[0].text` (a list of content blocks) |
| Output length limit | Optional | `max_tokens` is required |
| Alternating turns | Generally tolerant | Expects `user` and `assistant` turns to alternate, beginning with `user` |
Check the current documentation for your provider and model before relying on this table. Details such as role names, required parameters, and ordering rules change between API versions.
The system role is not allowed in Anthropic messages
If you copy an OpenAI-style history into the Anthropic API unchanged, the system entry in messages is rejected. The API returns a validation error, not a silently ignored prompt. The fix is to take the system text out of the list and pass it as system.
Newer OpenAI roles
OpenAI's newer APIs and models introduced a developer role that takes over the job of system for some models. It marks instructions from the application developer, and it ranks above user input. Many models still accept system. Others treat it as an alias for developer. Check which one your model expects. The chapter on tool and developer roles covers this in more detail.
Response shape
The OpenAI-style response holds a list of choices, and each choice has a message. The Anthropic-style response holds a list of content blocks. The first block is usually text, but a response can contain other block types, such as tool calls. Code that reads response.content[0].text without checking the block type will fail on those responses.
def anthropic_text(response):
"""Join all text blocks from an Anthropic-style response."""
return "".join(
block.text for block in response.content if block.type == "text"
)Alternation and ordering
The ordering rules from the earlier chapter on message ordering still apply. The two styles enforce them differently.
An Anthropic-style history should start with a user message and alternate user, assistant, user, and so on. Current versions of the API are more lenient than early ones. Consecutive messages with the same role are generally merged into one turn. Do not rely on that behavior without testing it, because a history that works today can be rejected by a different model or API version.
OpenAI-style APIs accept a wider range of sequences, but a sensible history still alternates. Two user messages in a row usually work, and the model reads them as one longer request.
A safe habit is to keep your own history valid under the stricter rules. Then it works with both.
Writing a provider-neutral history
You can store your history in one format and convert it when you call a provider. The OpenAI-style list, with the system message first, is a convenient storage format. This converter turns it into the arguments the Anthropic API expects.
def to_anthropic(messages):
"""Split an OpenAI-style message list into (system, messages) for Anthropic."""
system_parts = [m["content"] for m in messages if m["role"] == "system"]
turns = [m for m in messages if m["role"] != "system"]
system = "\n\n".join(system_parts)
return system, turns
history = [
{"role": "system", "content": "You are a helpful assistant. Keep answers under three sentences."},
{"role": "user", "content": "What is a list in Python?"},
{"role": "assistant", "content": "A list is an ordered, changeable collection of items."},
{"role": "user", "content": "How do I add an item to it?"},
]
system, turns = to_anthropic(history)
print(repr(system))
print(len(turns))Running this prints the joined system text and the number of remaining turns, which is 3. The function joins multiple system messages with a blank line. This is a design choice. An Anthropic request has one system value, so several system messages must be merged somehow.
You can then call the API like this:
import anthropic
client = anthropic.Anthropic()
system, turns = to_anthropic(history)
response = client.messages.create(
model="MODEL_NAME", # replace with a model available to you
max_tokens=300,
system=system,
messages=turns,
)
print(response.content[0].text)The few-shot pattern works the same way in both styles. The example pairs stay in the messages list as ordinary user and assistant turns. Only the instruction line moves.
A trap: system messages in the middle
OpenAI-style APIs let you put a system message anywhere in the list, for example to inject a new instruction partway through a conversation. The converter above would hoist it to the top and merge it into the single system prompt. The instruction then applies from the start of the conversation, not from the point where you inserted it. If a mid-conversation instruction matters, put it in a user message instead, or accept the change in timing.
What stays the same
Despite the layout differences, the working model is identical.
- Both APIs are stateless. You resend the system prompt and the full history on every call.
- Both treat the system prompt as higher-priority guidance than ordinary user text. Neither makes it a security boundary, so a determined user can still try to override it. See the chapter on instruction priority and untrusted input.
- The system prompt counts toward the context window and your token bill on every request. A long system prompt costs you each time.
- The assistant reply is something you append to your history yourself.
Because the system prompt is resent every time, keep it short and specific. Put behavior, tone, and constraints in it. Put facts that change per request in the user message.
Choosing an approach
Use the provider's own layout when you call one provider. Add a conversion layer only if you need to switch providers or support several.
- If you use a single provider, write messages in its native format. A conversion layer adds code you must maintain.
- If you support several providers, store history in one neutral format and convert at the call boundary, as
to_anthropicdoes. - If you want one code path for everything, an SDK or gateway that exposes an OpenAI-compatible interface can hide the difference. Check how it handles system prompts, because behavior at the edges, such as multiple system messages, varies.
Common errors
- System entry in the Anthropic
messageslist. The API rejects it. Move the text tosystem. - Missing
max_tokenson an Anthropic call. The request fails validation. Always set it. - Reading
content[0].textblindly. It breaks when the first block is not text. Filter by block type. - Starting an Anthropic history with an assistant turn. Trimming old messages can leave a history that starts with
assistant. After trimming, drop leading assistant turns. - Losing the system prompt when trimming. The
trim_historypattern from the history chapter keeps system messages separate. With Anthropic you holdsystemapart already, so only the turns need trimming. - Assuming
systemanddeveloperare interchangeable on every model. Test on the model you deploy.
The following function handles the fourth error. It trims the turns and then removes any leading assistant message.
def trim_turns(turns, max_messages=10):
"""Keep the most recent turns, and make sure the first one is from the user."""
trimmed = turns[-max_messages:]
while trimmed and trimmed[0]["role"] != "user":
trimmed = trimmed[1:]
return trimmed
turns = [
{"role": "user", "content": "Q1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "Q2"},
{"role": "assistant", "content": "A2"},
]
print(trim_turns(turns, max_messages=3))With max_messages=3, the slice starts at the assistant message A1. The loop removes it, and the output is the list holding Q2 and A2.
Exercise
You have this OpenAI-style history: a system message "Answer in French.", a user message "Hello", an assistant message "Bonjour", and a user message "How are you?". Show the arguments you would pass to the Anthropic Messages API, and explain one thing that would go wrong if you passed the list unchanged.
Show answer
Pass system="Answer in French." and messages=[{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Bonjour"}, {"role": "user", "content": "How are you?"}], plus a max_tokens value. If you passed the original list unchanged, the entry with role "system" would be in the messages list, and the Anthropic API would reject the request because that list accepts only user and assistant roles.
Exercise
A trimmed Anthropic-style history begins with an assistant message. Why is that a problem, and how can you fix it?
Show answer
The Messages API expects the conversation to begin with a user turn, so the request can be rejected or behave unexpectedly. Fix it by dropping leading assistant messages after trimming, as trim_turns does, or by trimming in whole user and assistant pairs.