A collection of simple examples showing how to use Claude's API in Python. Perfect for beginners who want to build AI applications with Claude!
Claude is Anthropic's AI assistant that can help with:
- Writing and analysis
- Answering questions
- Code assistance
- Language translation
- And much more!
- Python 3.7.1+
- Anthropic API key (Sign up here)
-
Install Claude's SDK and Python-dotenv
pip install anthropic python-dotenv
-
Set Up Your API Key
# Create a .env file and add your key ANTHROPIC_API_KEY=your_api_key_here
from anthropic import Anthropic
client = Anthropic(api_key=api_key)
# Simple example of calling Claude
response = client.messages.create(
model="claude-3-sonnet",
messages=[{"role": "user", "content": "Translate hello to French"}]
)# Basic chat that remembers conversation history
conversation_history = []
response = client.messages.create(
model="claude-3-sonnet",
messages=conversation_history
)# Custom AI assistant with specific personality
client.messages.create(
model="claude-3-sonnet",
system="You are ChefBot, an expert culinary assistant...",
messages=[...]
)# Generates engaging questions about any topic
client.messages.create(
model="claude-3-haiku",
system="You are an expert on the topic...",
messages=[{"role": "user", "content": "Generate questions..."}]
)# Real-time streaming chat with colored output
stream = client.messages.create(
model="claude-3-haiku",
messages=conversation_history,
stream=True
)
for chunk in stream:
if chunk.type == "content_block_delta":
print(chunk.delta.text, end="", flush=True)# Process and analyze images with Claude
client.messages.create(
model="claude-3-sonnet",
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "base64_encoded_image"
}
},
{
"type": "text",
"text": "Describe this image."
}
]
}]
)-
Run the Basic Translator
python hello.py
-
Chat with Claude
python chatbot.py
-
Get Cooking Help
python ChefBot.py
-
Try Real-time Chat
python stream.py
-
Generate Questions
python curiosity_engine.py
-
Analyze Images
python vision.py
- Messages: The basic unit of conversation with Claude
- System Prompts: Instructions that shape Claude's behavior
- Conversation History: Maintaining context across interactions
- Models: Different versions of Claude (we're using claude-3-sonnet)
- Streaming: Real-time response generation for interactive applications