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 keypip install anthropic>=0.20
Setup
Install the official Anthropic Python SDK and set your API key as an environment variable for secure authentication.
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.
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
modelnames likeclaude-3-opus-20240229for other Claude versions. - Adjust
max_tokensto control response length. - Use asynchronous calls with
asyncioandawaitif supported.
Troubleshooting
- If you get authentication errors, verify your
ANTHROPIC_API_KEYenvironment variable is set correctly. - For rate limit errors, check your usage and retry after some time.
- Ensure your
modelname is valid and available in your Anthropic account.
Key Takeaways
- Always use
os.environto load your Anthropic API key securely. - Call
client.messages.create()withmodel,system, andmessagesparameters to send a message. - Extract the assistant's reply from
message.content[0].text. - Adjust
max_tokensandmodelto customize responses. - Check environment variables and model names if you encounter errors.