How to beginner · 3 min read

How to set system prompt with Claude API

Quick answer
Use the system parameter in the client.messages.create method to set the system prompt with the Claude API. Pass your instructions as a string to system and user messages in the messages list for context.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup

Install the anthropic Python package and set your API key as an environment variable.

  • Run pip install anthropic to install the SDK.
  • Set your API key in your environment: export ANTHROPIC_API_KEY='your_api_key' (Linux/macOS) or set ANTHROPIC_API_KEY=your_api_key (Windows).
bash
pip install anthropic

Step by step

This example shows how to set a system prompt with the Claude API using the system parameter to instruct the assistant.

python
import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=200,
    system="You are a helpful assistant that responds concisely.",
    messages=[{"role": "user", "content": "Explain the benefits of using system prompts."}]
)

print(response.content[0].text)
output
You can use system prompts to guide the assistant's behavior, tone, and style, ensuring consistent and relevant responses.

Common variations

You can customize the system prompt for different tasks or switch models by changing the model parameter. The system parameter is always a string that sets the assistant's context.

  • Use claude-3-5-haiku-20241022 for poetic responses.
  • Adjust max_tokens to control response length.
  • Use async calls with asyncio if needed.
python
import asyncio
import os
import anthropic

async def main():
    client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    response = await client.messages.acreate(
        model="claude-3-5-haiku-20241022",
        max_tokens=100,
        system="You are a poetic assistant.",
        messages=[{"role": "user", "content": "Write a haiku about spring."}]
    )
    print(response.content[0].text)

asyncio.run(main())
output
Spring breeze softly blows
Cherry blossoms paint the sky
Nature's breath renewed

Troubleshooting

If you receive errors like 401 Unauthorized, verify your ANTHROPIC_API_KEY environment variable is set correctly. If the response is empty or cut off, increase max_tokens. Ensure you use the correct model name as per the latest Anthropic documentation.

Key Takeaways

  • Use the system parameter to set the system prompt in Claude API calls.
  • Always pass user messages in the messages list with role user.
  • Set your Anthropic API key securely via environment variables.
  • Adjust max_tokens to control response length and avoid truncation.
  • Use async methods for non-blocking calls if your application requires concurrency.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-3-5-haiku-20241022
Verify ↗