InvalidRequestError
anthropic.errors.InvalidRequestError
Stack trace
anthropic.errors.InvalidRequestError: Invalid role sequence in messages: system role must not appear in messages array; use system parameter instead
at anthropic.client.messages.create (client.py:123)
at main.py:45 Why it happens
Anthropic's chat API expects the system prompt to be passed separately via the 'system' parameter, not as a message with role 'system' in the messages list. Including a 'system' role message in the messages array violates the expected role sequence and triggers this error.
Detection
Validate that your messages array contains only 'user' and 'assistant' roles before sending the request, and ensure the system prompt is passed via the dedicated 'system' parameter.
Causes & fixes
Including a message with role='system' inside the messages list instead of using the system parameter.
Remove any 'system' role messages from the messages list and pass the system prompt text via the 'system' argument in client.messages.create().
Mixing Anthropic SDK usage patterns by passing system prompt both as a message and as the system parameter.
Use only the 'system' parameter for system prompts and keep messages list roles strictly as 'user' or 'assistant'.
Copying OpenAI chat message format directly, which includes 'system' role in messages, incompatible with Anthropic SDK v0.20+.
Adapt your code to Anthropic's SDK by removing 'system' role messages and using the separate system parameter.
Code: broken vs fixed
from anthropic import Anthropic
import os
client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])
messages = [
{"role": "system", "content": "You are a helpful assistant."}, # This causes the error
{"role": "user", "content": "Hello!"}
]
response = client.messages.create(
model="claude-2",
messages=messages # InvalidRequestError triggered here
)
print(response) from anthropic import Anthropic
import os
client = Anthropic(api_key=os.environ['ANTHROPIC_API_KEY'])
messages = [
{"role": "user", "content": "Hello!"}
]
response = client.messages.create(
model="claude-2",
system="You are a helpful assistant.", # Moved system prompt here
messages=messages # Only user and assistant roles here
)
print(response) # Fixed: no InvalidRequestError Workaround
Catch InvalidRequestError and strip out any 'system' role messages from the messages list before retrying the request with the system prompt passed separately.
Prevention
Always use the 'system' parameter for system prompts with Anthropic's chat API and keep messages list roles limited to 'user' and 'assistant' to avoid role sequence errors.