Do you want your Python scripts to think, reason, and respond? This tutorial guides Python developers on how to connect their code to Anthropic's Claude AI model, enabling their projects with advanced capabilities to read, reason, and generate responses.
Before You Start
Two important points to note upfront:
- The API usage incurs costs. While minimal (e.g., $5 for weeks of normal use), it's not free like the Claude.ai chat interface. You'll need to add credits at console.anthropic.com.
- You need Python 3.9 or later. Verify your version using:
If your Python version is older than 3.9, update it from python.org. During installation on Windows, ensure "Add Python to PATH" is checked, as missing this step can lead to setup issues.python --version
Setup
Follow these steps to create your project folder, set up a virtual environment, and install the necessary SDK:
mkdir claude-project
cd claude-project
python -m venv venv
Next, activate your virtual environment:
- For Mac/Linux:
source venv/bin/activate - For Windows:
venv\Scripts\activate
Your terminal prompt should start with (venv) once activated. This indicates that packages installed subsequently will be isolated within this environment:
pip install anthropic python-dotenv
Your API Key
Go to console.anthropic.com, create an account, and generate a new key under the "API Keys" section.
Store your API key securely in a .env file within your project folder:
ANTHROPIC_API_KEY=your-key-here
Crucially, add .env to your .gitignore file to prevent it from being committed to public repositories:
echo .env > .gitignore
This is vital for security; a publicly exposed API key can be discovered, used, and charged to your account within hours.
The First Call
Here’s how to initiate a conversation with Claude from Python:
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "What is a REST API?"
}
]
)
print(message.content[0].text)
Running this script will display Claude’s response directly in your terminal.
Three key aspects of this API call are important to understand:
model: Specifies the Claude model version you are using.claude-sonnet-4-6is generally the default for most use cases, balancing speed and capability effectively.max_tokens: Defines the maximum length of Claude’s response. Setting this too low can result in responses being abruptly cut off.1024is a recommended safe starting point.messages: This is a list representing the turns in the conversation. Each turn is an object containing a"role"(e.g.,"user"or"assistant") and"content"(the message itself).