Skip to content

davila7/claude-code-templates / cli-tool/components/skills/development/claude-api

claude-api

Unverified

Build, debug, and optimize Claude API / Anthropic SDK apps. Apps built with this skill should include prompt caching. Also handles migrating existing Claude API code between Claude model versions (4.5 → 4.6, 4.6 → 4.7, retired-model replacements). TRIGGER when: code imports `anthropic`/`@anthropic-ai/sdk`; user asks for the Claude API, Anthropic SDK, or Managed Agents; user adds/modifies/tunes a Claude feature (caching, thinking, compaction, tool use, batch, files, citations, memory) or model (Opus/Sonnet/Haiku) in a file; questions about prompt caching / cache hit rate in an Anthropic SDK project. SKIP: file imports `openai`/other-provider SDK, filename like `*-openai.py`/`*-generic.py`, provider-neutral code, general programming/ML.

FileKindSize
LICENSE.txtmarkdown11.1 KB
SKILL.mdskill md32.3 KB
csharp/claude-api.mdmarkdown14.1 KB
curl/examples.mdmarkdown6.3 KB
curl/managed-agents.mdmarkdown7.2 KB
go/claude-api.mdmarkdown13.5 KB
go/managed-agents/README.mdmarkdown18.0 KB
java/claude-api.mdmarkdown14.7 KB
java/managed-agents/README.mdmarkdown16.2 KB
php/claude-api.mdmarkdown10.9 KB
php/managed-agents/README.mdmarkdown12.9 KB
python/agent-sdk/README.mdmarkdown12.4 KB
python/agent-sdk/patterns.mdmarkdown9.0 KB
python/claude-api/README.mdmarkdown11.9 KB
python/claude-api/batches.mdmarkdown5.0 KB
python/claude-api/files-api.mdmarkdown3.9 KB
python/claude-api/streaming.mdmarkdown5.1 KB
python/claude-api/tool-use.mdmarkdown16.5 KB
python/managed-agents/README.mdmarkdown9.6 KB
ruby/claude-api.mdmarkdown2.9 KB
ruby/managed-agents/README.mdmarkdown9.9 KB
shared/agent-design.mdmarkdown8.1 KB
shared/error-codes.mdmarkdown7.5 KB
shared/live-sources.mdmarkdown16.2 KB
shared/managed-agents-api-reference.mdmarkdown23.2 KB
shared/managed-agents-client-patterns.mdmarkdown9.2 KB
shared/managed-agents-core.mdmarkdown12.8 KB
shared/managed-agents-environments.mdmarkdown10.4 KB
shared/managed-agents-events.mdmarkdown9.4 KB
shared/managed-agents-memory.mdmarkdown9.4 KB
shared/managed-agents-multiagent.mdmarkdown6.4 KB
shared/managed-agents-onboarding.mdmarkdown7.9 KB
shared/managed-agents-outcomes.mdmarkdown6.0 KB
shared/managed-agents-overview.mdmarkdown9.0 KB
shared/managed-agents-tools.mdmarkdown13.2 KB
shared/managed-agents-webhooks.mdmarkdown4.9 KB
shared/model-migration.mdmarkdown64.0 KB
shared/models.mdmarkdown7.4 KB
shared/prompt-caching.mdmarkdown9.6 KB
shared/tool-use-concepts.mdmarkdown16.4 KB
typescript/agent-sdk/README.mdmarkdown10.6 KB
typescript/agent-sdk/patterns.mdmarkdown4.6 KB
typescript/claude-api/README.mdmarkdown9.7 KB
typescript/claude-api/batches.mdmarkdown2.5 KB
typescript/claude-api/files-api.mdmarkdown2.2 KB
typescript/claude-api/streaming.mdmarkdown5.5 KB
typescript/claude-api/tool-use.mdmarkdown15.0 KB
typescript/managed-agents/README.mdmarkdown9.2 KB

python/claude-api/batches.md

View on GitHub
# Message Batches API — Python

The Batches API (`POST /v1/messages/batches`) processes Messages API requests asynchronously at 50% of standard prices.

## Key Facts

- Up to 100,000 requests or 256 MB per batch
- Most batches complete within 1 hour; maximum 24 hours
- Results available for 29 days after creation
- 50% cost reduction on all token usage
- All Messages API features supported (vision, tools, caching, etc.)

---

## Create a Batch

```python
import anthropic
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request

client = anthropic.Anthropic()

message_batch = client.messages.batches.create(
    requests=[
        Request(
            custom_id="request-1",
            params=MessageCreateParamsNonStreaming(
                model="claude-opus-4-7",
                max_tokens=16000,
                messages=[{"role": "user", "content": "Summarize climate change impacts"}]
            )
        ),
        Request(
            custom_id="request-2",
            params=MessageCreateParamsNonStreaming(
                model="claude-opus-4-7",
                max_tokens=16000,
                messages=[{"role": "user", "content": "Explain quantum computing basics"}]
            )
        ),
    ]
)

print(f"Batch ID: {message_batch.id}")
print(f"Status: {message_batch.processing_status}")
```

---

## Poll for Completion

```python
import time

while True:
    batch = client.messages.batches.retrieve(message_batch.id)
    if batch.processing_status == "ended":
        break
    print(f"Status: {batch.processing_status}, processing: {batch.request_counts.processing}")
    time.sleep(60)

print("Batch complete!")
print(f"Succeeded: {batch.request_counts.succeeded}")
print(f"Errored: {batch.request_counts.errored}")
```

---

## Retrieve Results

> **Note:** Examples below use `match/case` syntax, requiring Python 3.10+. For earlier versions, use `if/elif` chains instead.

```python
for result in client.messages.batches.results(message_batch.id):
    match result.result.type:
        case "succeeded":
            msg = result.result.message
            text = next((b.text for b in msg.content if b.type == "text"), "")
            print(f"[{result.custom_id}] {text[:100]}")
        case "errored":
            if result.result.error.type == "invalid_request":
                print(f"[{result.custom_id}] Validation error - fix request and retry")
            else:
                print(f"[{result.custom_id}] Server error - safe to retry")
        case "canceled":
            print(f"[{result.custom_id}] Canceled")
        case "expired":
            print(f"[{result.custom_id}] Expired - resubmit")
```

---

## Cancel a Batch

```python
cancelled = client.messages.batches.cancel(message_batch.id)
print(f"Status: {cancelled.processing_status}")  # "canceling"
```

---

## Batch with Prompt Caching

```python
shared_system = [
    {"type": "text", "text": "You are a literary analyst."},
    {
        "type": "text",
        "text": large_document_text,  # Shared across all requests
        "cache_control": {"type": "ephemeral"}
    }
]

message_batch = client.messages.batches.create(
    requests=[
        Request(
            custom_id=f"analysis-{i}",
            params=MessageCreateParamsNonStreaming(
                model="claude-opus-4-7",
                max_tokens=16000,
                system=shared_system,
                messages=[{"role": "user", "content": question}]
            )
        )
        for i, question in enumerate(questions)
    ]
)
```

---

## Full End-to-End Example

```python
import anthropic
import time
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
from anthropic.types.messages.batch_create_params import Request

client = anthropic.Anthropic()

# 1. Prepare requests
items_to_classify = [
    "The product quality is excellent!",
    "Terrible customer service, never again.",
    "It's okay, nothing special.",
]

requests = [
    Request(
        custom_id=f"classify-{i}",
        params=MessageCreateParamsNonStreaming(
            model="claude-haiku-4-5",
            max_tokens=50,
            messages=[{
                "role": "user",
                "content": f"Classify as positive/negative/neutral (one word): {text}"
            }]
        )
    )
    for i, text in enumerate(items_to_classify)
]

# 2. Create batch
batch = client.messages.batches.create(requests=requests)
print(f"Created batch: {batch.id}")

# 3. Wait for completion
while True:
    batch = client.messages.batches.retrieve(batch.id)
    if batch.processing_status == "ended":
        break
    time.sleep(10)

# 4. Collect results
results = {}
for result in client.messages.batches.results(batch.id):
    if result.result.type == "succeeded":
        msg = result.result.message
        results[result.custom_id] = next((b.text for b in msg.content if b.type == "text"), "")

for custom_id, classification in sorted(results.items()):
    print(f"{custom_id}: {classification}")
```
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 319kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 319kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 319kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall