---
name: "Anthropic Claude API"
description: "Skill for Anthropic Claude API — auto-generated from documentation"
version: "1.0.0"
author: "skynet"
category: "dev"
agents: ["claude-code", "codex", "gemini"]
tags: ["anthropic-api", "dev", "auto-generated"]
---

# Anthropic Claude API

---
name: Anthropic Claude API
description: Use when you need to integrate Claude AI into applications, build AI-powered features, or automate tasks using Claude's capabilities via API calls
metadata:
  author: skynet
  version: 1.0.0
category: dev
---

# Anthropic Claude API

## Prerequisites

```bash
# Install required packages
pip install anthropic
# or
npm install @anthropic-ai/sdk

# Set API key
export ANTHROPIC_API_KEY="your-api-key-here"
```

## Quick Start

### Python Basic Usage

```python
import anthropic

client = anthropic.Anthropic(
    api_key="your-api-key-here"
)

message = client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    temperature=0,
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)
print(message.content)
```

### cURL Basic Request

```bash
curl https://api.anthropic.com/v1/messages \
     --header "x-api-key: $ANTHROPIC_API_KEY" \
     --header "content-type: application/json" \
     --header "anthropic-version: 2023-06-01" \
     --data '{
       "model": "claude-3-sonnet-20240229",
       "max_tokens": 1000,
       "messages": [{"role": "user", "content": "Hello, world"}]
     }'
```

### Node.js Basic Usage

```javascript
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const msg = await anthropic.messages.create({
  model: "claude-3-sonnet-20240229",
  max_tokens: 1000,
  temperature: 0,
  system: "You are a helpful assistant.",
  messages: [
    {"role": "user", "content": "Hello, Claude!"}
  ]
});
console.log(msg.content);
```

## Model Selection Decision Tree

```
Need to choose a model?
├── High performance, complex reasoning needed?
│   └── claude-3-opus-20240229 (Most capable, slower)
├── Balanced performance and speed?
│   └── claude-3-sonnet-20240229 (Recommended for most use cases)
├── Fast responses, simple tasks?
│   └── claude-3-haiku-20240307 (Fastest, cost-effective)
└── Legacy support needed?
    └── claude-2.1 or claude-2.0
```

## Advanced Usage Patterns

### Streaming Responses

```python
import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Write a story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

### System Prompts and Multi-turn Conversations

```python
messages = [
    {"role": "user", "content": "What's the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."},
    {"role": "user", "content": "What's its population?"}
]

response = client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    system="You are a geography expert. Be precise and concise.",
    messages=messages
)
```

### Function Calling / Tool Use

```python
tools = [{
    "name": "get_weather",
    "description": "Get weather information for a location",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "City name"}
        },
        "required": ["location"]
    }
}]

message = client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
```

### Image Analysis

```python
import base64

with open("image.jpg", "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode()

message = client.messages.create(
    model="claude-3-sonnet-20240229",
    max_tokens=1000,
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": "image/jpeg",
                    "data": image_data
                }
            }
        ]
    }]
)
```

## Common Workflows

### Batch Processing

```python
import asyncio
import anthropic

async def process_batch(texts):
    client = anthropic.AsyncAnthropic()
    
    async def process_single(text):
        return await client.messages.create(
            model="claude-3-haiku-20240307",
            max_tokens=500,
            messages=[{"role": "user", "content": f"Summarize: {text}"}]
        )
    
    tasks = [process_single(text) for text in texts]
    return await asyncio.gather(*tasks)
```

### Rate Limiting Handler

```python
import time
from anthropic import RateLimitError

def safe_api_call(client, **kwargs):
    max_retries = 3
    base_delay = 1
    
    for attempt in range(max_retries):
        try:
            return client.messages.create(**kwargs)
        except RateLimitError as e:
            if attempt == max_retries - 1:
                raise e
            delay = base_delay * (2 ** attempt)
            print(f"Rate limited. Waiting {delay}s...")
            time.sleep(delay)
```

### Response Validation

```python
def validate_and_extract(response):
    if not response.content:
        raise ValueError("Empty response")
    
    text_content = ""
    for block in response.content:
        if block.type == "text":
            text_content += block.text
    
    if len(text_content.strip()) == 0:
        raise ValueError("No text content in response")
    
    return text_content
```

## CLI Examples

### Using httpie

```bash
# Install httpie
pip install httpie

# Make API call
http POST https://api.anthropic.com/v1/messages \
  x-api-key:$ANTHROPIC_API_KEY \
  content-type:application/json \
  anthropic-version:2023-06-01 \
  model="claude-3-sonnet-20240229" \
  max_tokens:=1000 \
  messages:='[{"role": "user", "content": "Hello"}]'
```

### Bash Script for Bulk Processing

```bash
#!/bin/bash
# bulk_claude.sh

API_KEY="your-api-key"
MODEL="claude-3-haiku-20240307"

while IFS= read -r line; do
  curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $API_KEY" \
    -H "content-type: application/json" \
    -H "anthropic-version: 2023-06-01" \
    -d "{
      \"model\": \"$MODEL\",
      \"max_tokens\": 500,
      \"messages\": [{\"role\": \"user\", \"content\": \"$line\"}]
    }" | jq -r '.content[0].text'
  sleep 1  # Rate limiting
done < input.txt
```

## Troubleshooting

### Common Error Messages and Fixes

**Error: `anthropic.AuthenticationError: Invalid API Key`**
```bash
# Fix: Check API key
echo $ANTHROPIC_API_KEY
# Regenerate key at console.anthropic.com
export ANTHROPIC_API_KEY="sk-ant-api03-new-key-here"
```

**Error: `anthropic.RateLimitError: Rate limit exceeded`**
```python
# Fix: Add exponential backoff
import time
from anthropic import RateLimitError

try:
    response = client.messages.create(...)
except RateLimitError:
    time.sleep(60)  # Wait 1 minute
    response = client.messages.create(...)  # Retry
```

**Error: `anthropic.BadRequestError: messages: too long`**
```python
# Fix: Check token count and truncate
def count_tokens_rough(text):
    return len(text.split()) * 1.3  # Rough estimate

def truncate_messages(messages, max_tokens=100000):
    total = sum(count_tokens_rough(msg["content"]) for msg in messages)
    if total > max_tokens:
        # Keep system message and recent messages
        return messages[-10:]  # Keep last 10 messages
    return messages
```

**Error: `Connection timeout`**
```python
# Fix: Increase timeout
client = anthropic.Anthropic(
    timeout=httpx.Timeout(60.0, read=20.0, write=10.0, connect=2.0)
)
```

**Error: `Invalid model specified`**
```python
# Fix: Use correct model names
valid_models = [
    "claude-3-opus-20240229",
    "claude-3-sonnet-20240229", 
    "claude-3-haiku-20240307",
    "claude-2.1",
    "claude-2.0"
]
```

### Debugging Tips

```python
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)

# Check response metadata
response = client.messages.create(...)
print(f"Model: {response.model}")
print(f"Usage: {response.usage}")
print(f"Stop reason: {response.stop_reason}")
```

### Performance Optimization

```python
# Use appropriate model for task complexity
task_complexity = {
    "simple": "claude-3-haiku-20240307",
    "medium": "claude-3-sonnet-20240229", 
    "complex": "claude-3-opus-20240229"
}

# Optimize max_tokens for your use case
response_lengths = {
    "short_answer": 100,
    "summary": 500,
    "article": 2000,
    "analysis": 4000
}

# Use streaming for long responses
if expected_length > 1000:
    # Use streaming
    with client.messages.stream(...) as stream:
        for text in stream.text_stream:
            process_incrementally(text)
```
