How to beginner · 3 min read

How to send a message with Anthropic python SDK

Quick answer
Use the anthropic Python SDK by creating an Anthropic client with your API key, then call client.messages.create() with the model, system prompt, and messages array. Extract the response text from message.content[0].text.

PREREQUISITES

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

Setup

Install the official Anthropic Python SDK and set your API key as an environment variable for secure authentication.

bash
pip install anthropic>=0.20

Step by step

This example shows how to send a message to the Anthropic API using the Python SDK. It creates a client, sends a user message, and prints the assistant's reply.

python
import os
import anthropic

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

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=512,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": "Hello, how do I send a message with Anthropic Python SDK?"}]
)

print(message.content[0].text)
output
Hello! To send a message with the Anthropic Python SDK, create an Anthropic client and use the messages.create() method with your prompt.

Common variations

  • Use different model names like claude-3-opus-20240229 for other Claude versions.
  • Adjust max_tokens to control response length.
  • Use asynchronous calls with asyncio and await if supported.

Troubleshooting

  • If you get authentication errors, verify your ANTHROPIC_API_KEY environment variable is set correctly.
  • For rate limit errors, check your usage and retry after some time.
  • Ensure your model name is valid and available in your Anthropic account.

Key Takeaways

  • Always use os.environ to load your Anthropic API key securely.
  • Call client.messages.create() with model, system, and messages parameters to send a message.
  • Extract the assistant's reply from message.content[0].text.
  • Adjust max_tokens and model to customize responses.
  • Check environment variables and model names if you encounter errors.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-3-opus-20240229
Verify ↗