SOP-001: Claude API Setup
Document Control
- SOP ID: 001
- Version: 1.0
- Status: Active
- Last Updated: December 2024
- Review Cycle: Quarterly
Overview
This SOP provides comprehensive instructions for setting up and configuring the Claude API for development and production environments.
Purpose
Establish a standardized process for Claude API initialization, authentication, and basic configuration.
Scope
Applies to all Claude API implementations across Python, JavaScript, and other supported SDKs.
Prerequisites
- [ ] Valid Anthropic account
- [ ] Development environment (Python 3.8+ or Node.js 16+)
- [ ] Terminal/command line access
- [ ] Internet connectivity
Procedure
┌─────────────────────────────────────────────────────────────────────┐
│ API SETUP WORKFLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ [Account Creation] │
│ ▼ │
│ [API Key Generation] ──► [Secure Storage] │
│ ▼ ▼ │
│ [SDK Installation] ──────► [Environment Config] │
│ ▼ ▼ │
│ [Connection Test] ◄────── [Authentication Setup] │
│ ▼ │
│ [Model Selection] ──► [Rate Limit Config] ──► [Production Ready] │
│ │
└─────────────────────────────────────────────────────────────────────┘Step 1: Create Anthropic Account
- Navigate to console.anthropic.com
- Click "Sign Up"
- Enter required information:
- Email address
- Password (min 12 characters)
- Organization name (if applicable)
- Verify email via confirmation link
- Complete profile setup
Verification Point: Login successful at console.anthropic.com
Step 2: Generate API Key
Access API Keys section:
Console → Settings → API KeysCreate new API key:
Click [+ Create API Key] Name: "development-key-YYYYMMDD" Permissions: Full Access (for dev)Copy and store securely:
bash# DO NOT store in code # Use password manager or secure vault
Security Requirements:
- Never commit to version control
- Rotate keys every 90 days
- Use separate keys for dev/staging/prod
Step 3: Install SDK
Python Installation
bash
# Create virtual environment
python -m venv claude-env
source claude-env/bin/activate # Linux/Mac
# or
claude-env\Scripts\activate # Windows
# Install SDK
pip install anthropic
# Verify installation
pip show anthropicNode.js Installation
bash
# Initialize project
npm init -y
# Install SDK
npm install @anthropic-ai/sdk
# Install dotenv for environment variables
npm install dotenv
# Verify installation
npm list @anthropic-ai/sdkStep 4: Configure Environment
Method 1: Environment Variables
bash
# Linux/Mac (.bashrc or .zshrc)
export ANTHROPIC_API_KEY='sk-ant-api03-...'
# Windows (PowerShell)
[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-api03-...", "User")Method 2: .env File (Recommended)
env
# .env file in project root
ANTHROPIC_API_KEY=sk-ant-api03-...
ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
ANTHROPIC_MAX_TOKENS=4096
ANTHROPIC_TEMPERATURE=0.7Method 3: Configuration File
json
// config.json
{
"api": {
"key": "${ANTHROPIC_API_KEY}",
"baseUrl": "https://api.anthropic.com",
"version": "2024-10-22",
"timeout": 30000,
"retries": 3
}
}Step 5: Initialize Client
Python Client
python
# claude_client.py
import os
from anthropic import Anthropic
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class ClaudeClient:
def __init__(self):
self.client = Anthropic(
api_key=os.getenv('ANTHROPIC_API_KEY'),
max_retries=3,
timeout=30.0
)
self.default_model = os.getenv('ANTHROPIC_MODEL', 'claude-3-5-sonnet-20241022')
def send_message(self, prompt, model=None):
"""Send a message to Claude"""
try:
response = self.client.messages.create(
model=model or self.default_model,
max_tokens=1024,
messages=[
{"role": "user", "content": prompt}
]
)
return response.content[0].text
except Exception as e:
print(f"Error: {e}")
return None
# Usage
if __name__ == "__main__":
claude = ClaudeClient()
response = claude.send_message("Hello, Claude!")
print(response)JavaScript Client
javascript
// claude_client.js
require('dotenv').config();
const Anthropic = require('@anthropic-ai/sdk');
class ClaudeClient {
constructor() {
this.client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
this.defaultModel = process.env.ANTHROPIC_MODEL || 'claude-3-5-sonnet-20241022';
}
async sendMessage(prompt, model = null) {
try {
const response = await this.client.messages.create({
model: model || this.defaultModel,
max_tokens: 1024,
messages: [
{ role: 'user', content: prompt }
]
});
return response.content[0].text;
} catch (error) {
console.error('Error:', error);
return null;
}
}
}
// Usage
async function main() {
const claude = new ClaudeClient();
const response = await claude.sendMessage("Hello, Claude!");
console.log(response);
}
if (require.main === module) {
main();
}
module.exports = ClaudeClient;Step 6: Connection Verification
Run this comprehensive test:
python
# test_connection.py
import os
import json
from datetime import datetime
from anthropic import Anthropic
def test_claude_api():
"""Comprehensive API test suite"""
results = {
"timestamp": datetime.now().isoformat(),
"tests": {}
}
# Test 1: API Key Validation
try:
api_key = os.getenv('ANTHROPIC_API_KEY')
assert api_key and api_key.startswith('sk-ant-'), "Invalid API key format"
results["tests"]["api_key"] = "✅ Valid"
except AssertionError as e:
results["tests"]["api_key"] = f"❌ {str(e)}"
return results
# Test 2: Client Initialization
try:
client = Anthropic()
results["tests"]["client_init"] = "✅ Success"
except Exception as e:
results["tests"]["client_init"] = f"❌ {str(e)}"
return results
# Test 3: Basic Message
try:
response = client.messages.create(
model="claude-3-5-haiku-20241022",
max_tokens=50,
messages=[
{"role": "user", "content": "Respond with 'API Connected'"}
]
)
assert "API Connected" in response.content[0].text
results["tests"]["basic_message"] = "✅ Connected"
except Exception as e:
results["tests"]["basic_message"] = f"❌ {str(e)}"
# Test 4: Model Availability
models = [
"claude-3-5-sonnet-20241022",
"claude-3-5-haiku-20241022",
"claude-3-opus-20240229"
]
for model in models:
try:
response = client.messages.create(
model=model,
max_tokens=10,
messages=[
{"role": "user", "content": "Hi"}
]
)
results["tests"][f"model_{model}"] = "✅ Available"
except Exception as e:
results["tests"][f"model_{model}"] = f"❌ Unavailable"
# Print results
print("\n" + "="*50)
print("CLAUDE API CONNECTION TEST RESULTS")
print("="*50)
for test, result in results["tests"].items():
print(f"{test}: {result}")
print("="*50)
# Save results
with open('api_test_results.json', 'w') as f:
json.dump(results, f, indent=2)
return results
if __name__ == "__main__":
test_claude_api()Verification
Success Criteria
- [ ] API key is valid and active
- [ ] SDK is properly installed
- [ ] Environment variables are configured
- [ ] Client can connect to Claude API
- [ ] At least one model is accessible
- [ ] Test message receives response
Performance Benchmarks
| Metric | Target | Acceptable |
|---|---|---|
| Connection Time | < 1s | < 3s |
| First Response | < 2s | < 5s |
| Token/Second | > 50 | > 30 |
Troubleshooting
Common Issues
Issue: "API key not found"
bash
# Solution 1: Check environment variable
echo $ANTHROPIC_API_KEY
# Solution 2: Source profile
source ~/.bashrc # or ~/.zshrc
# Solution 3: Use .env file
python -c "from dotenv import load_dotenv; load_dotenv(); import os; print(os.getenv('ANTHROPIC_API_KEY'))"Issue: "Rate limit exceeded"
python
# Solution: Implement exponential backoff
import time
from anthropic import RateLimitError
def retry_with_backoff(func, max_retries=5):
for i in range(max_retries):
try:
return func()
except RateLimitError:
wait_time = (2 ** i) + random.random()
time.sleep(wait_time)
raise Exception("Max retries exceeded")Issue: "Connection timeout"
python
# Solution: Increase timeout
client = Anthropic(
timeout=60.0, # Increase from default 30s
max_retries=5
)Issue: "Model not available"
python
# Solution: Use fallback model
MODELS = [
"claude-3-5-sonnet-20241022", # Primary
"claude-3-5-haiku-20241022", # Fallback 1
"claude-3-opus-20240229" # Fallback 2
]
for model in MODELS:
try:
response = client.messages.create(model=model, ...)
break
except Exception:
continueSecurity Considerations
API Key Management
- Never hardcode keys in source code
- Use separate keys for each environment
- Rotate regularly (every 90 days)
- Monitor usage for anomalies
- Implement key encryption at rest
Network Security
python
# Use HTTPS proxy if required
import httpx
client = Anthropic(
http_client=httpx.Client(
proxies="http://proxy.company.com:8080",
verify="/path/to/ca-bundle.crt"
)
)Best Practices
- Error Handling: Always wrap API calls in try-except blocks
- Logging: Implement comprehensive logging (but never log API keys)
- Monitoring: Track API usage and costs
- Caching: Cache responses when appropriate
- Rate Limiting: Implement client-side rate limiting
See Also
- SOP-002: Claude Code Installation
- SOP-005: Authentication & Security
- SOP-011: Rate Limiting Configuration
- Workflow-005: Prompt Engineering
External Resources
Verification Checklist:
- [ ] Account created and verified
- [ ] API key generated and secured
- [ ] SDK installed successfully
- [ ] Environment configured properly
- [ ] Connection test passed
- [ ] Model accessibility confirmed
Next Step: Proceed to SOP-002: Claude Code Installation