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/streaming.md

View on GitHub
# Streaming — Python

## Quick Start

```python
with client.messages.stream(
    model="claude-opus-4-7",
    max_tokens=64000,
    messages=[{"role": "user", "content": "Write a story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

### Async

```python
async with async_client.messages.stream(
    model="claude-opus-4-7",
    max_tokens=64000,
    messages=[{"role": "user", "content": "Write a story"}]
) as stream:
    async for text in stream.text_stream:
        print(text, end="", flush=True)
```

---

## Handling Different Content Types

Claude may return text, thinking blocks, or tool use. Handle each appropriately:

> **Opus 4.7 / Opus 4.6:** Use `thinking: {type: "adaptive"}`. On older models, use `thinking: {type: "enabled", budget_tokens: N}` instead.

```python
with client.messages.stream(
    model="claude-opus-4-7",
    max_tokens=64000,
    thinking={"type": "adaptive"},
    messages=[{"role": "user", "content": "Analyze this problem"}]
) as stream:
    for event in stream:
        if event.type == "content_block_start":
            if event.content_block.type == "thinking":
                print("\n[Thinking...]")
            elif event.content_block.type == "text":
                print("\n[Response:]")

        elif event.type == "content_block_delta":
            if event.delta.type == "thinking_delta":
                print(event.delta.thinking, end="", flush=True)
            elif event.delta.type == "text_delta":
                print(event.delta.text, end="", flush=True)
```

---

## Streaming with Tool Use

The Python tool runner currently returns complete messages. Use streaming for individual API calls within a manual loop if you need per-token streaming with tools:

```python
with client.messages.stream(
    model="claude-opus-4-7",
    max_tokens=64000,
    tools=tools,
    messages=messages
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

    response = stream.get_final_message()
    # Continue with tool execution if response.stop_reason == "tool_use"
```

---

## Getting the Final Message

```python
with client.messages.stream(
    model="claude-opus-4-7",
    max_tokens=64000,
    messages=[{"role": "user", "content": "Hello"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

    # Get full message after streaming
    final_message = stream.get_final_message()
    print(f"\n\nTokens used: {final_message.usage.output_tokens}")
```

---

## Streaming with Progress Updates

```python
def stream_with_progress(client, **kwargs):
    """Stream a response with progress updates."""
    total_tokens = 0
    content_parts = []

    with client.messages.stream(**kwargs) as stream:
        for event in stream:
            if event.type == "content_block_delta":
                if event.delta.type == "text_delta":
                    text = event.delta.text
                    content_parts.append(text)
                    print(text, end="", flush=True)

            elif event.type == "message_delta":
                if event.usage and event.usage.output_tokens is not None:
                    total_tokens = event.usage.output_tokens

        final_message = stream.get_final_message()

    print(f"\n\n[Tokens used: {total_tokens}]")
    return "".join(content_parts)
```

---

## Error Handling in Streams

```python
try:
    with client.messages.stream(
        model="claude-opus-4-7",
        max_tokens=64000,
        messages=[{"role": "user", "content": "Write a story"}]
    ) as stream:
        for text in stream.text_stream:
            print(text, end="", flush=True)
except anthropic.APIConnectionError:
    print("\nConnection lost. Please retry.")
except anthropic.RateLimitError:
    print("\nRate limited. Please wait and retry.")
except anthropic.APIStatusError as e:
    print(f"\nAPI error: {e.status_code}")
```

---

## Stream Event Types

| Event Type            | Description                 | When it fires                     |
| --------------------- | --------------------------- | --------------------------------- |
| `message_start`       | Contains message metadata   | Once at the beginning             |
| `content_block_start` | New content block beginning | When a text/tool_use block starts |
| `content_block_delta` | Incremental content update  | For each token/chunk              |
| `content_block_stop`  | Content block complete      | When a block finishes             |
| `message_delta`       | Message-level updates       | Contains `stop_reason`, usage     |
| `message_stop`        | Message complete            | Once at the end                   |

## Best Practices

1. **Always flush output** — Use `flush=True` to show tokens immediately
2. **Handle partial responses** — If the stream is interrupted, you may have incomplete content
3. **Track token usage** — The `message_delta` event contains usage information
4. **Use timeouts** — Set appropriate timeouts for your application
5. **Default to streaming** — Use `.get_final_message()` to get the complete response even when streaming, giving you timeout protection without needing to handle individual events
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