How to write a system prompt for Claude
Quick answer
To write a system prompt for
Claude, use the system= parameter in the client.messages.create() method to define the assistant's behavior or role. This prompt sets the context before user messages and guides Claude's responses effectively.PREREQUISITES
Python 3.8+Anthropic API key (free tier works)pip install anthropic>=0.20
Setup
Install the anthropic Python package and set your API key as an environment variable.
- Run
pip install anthropic>=0.20to install the SDK. - Set your API key in your shell:
export ANTHROPIC_API_KEY='your_api_key_here'.
pip install anthropic>=0.20 Step by step
Use the system= parameter to provide the system prompt that defines Claude's role or instructions. Then send user messages in the messages list. The system prompt is the first context the model sees.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant that answers concisely and clearly."
user_message = "Explain the benefits of system prompts."
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
print(response.content[0].text) output
System prompts help guide the assistant's behavior, ensuring responses are aligned with user expectations and context.
Common variations
You can customize system prompts for different tasks, such as making Claude a tutor, translator, or code reviewer. Also, you can adjust max_tokens or use different Claude models like claude-3-5-haiku-20241022 for creative tasks.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# System prompt for a coding assistant
system_prompt = "You are a coding assistant that provides detailed Python code examples."
user_message = "Write a Python function to reverse a string."
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=150,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
print(response.content[0].text) output
def reverse_string(s):
return s[::-1] Troubleshooting
If Claude ignores your system prompt, ensure it is passed via the system= parameter and not inside the messages array. Also, check your model supports system prompts and that your API key is valid.
Key Takeaways
- Always use the
system=parameter to set Claude's system prompt for clear context. - Customize system prompts to tailor Claude's behavior for specific tasks or roles.
- Pass user inputs separately in the
messageslist with role "user". - Verify your API key and model support system prompts if responses seem off.
- Use concise, explicit instructions in system prompts for best results.