anthropic-streaming-patterns
Use when integrating Claude API with streaming responses, implementing tool execution in streams, tracking API costs, or encountering streaming errors - provides Anthropic SDK 0.30.1+ patterns with mandatory cost monitoring
Best use case
anthropic-streaming-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when integrating Claude API with streaming responses, implementing tool execution in streams, tracking API costs, or encountering streaming errors - provides Anthropic SDK 0.30.1+ patterns with mandatory cost monitoring
Teams using anthropic-streaming-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/anthropic-streaming-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How anthropic-streaming-patterns Compares
| Feature / Agent | anthropic-streaming-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when integrating Claude API with streaming responses, implementing tool execution in streams, tracking API costs, or encountering streaming errors - provides Anthropic SDK 0.30.1+ patterns with mandatory cost monitoring
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Anthropic Claude API Streaming Patterns
## Overview
Claude API integration with streaming, tool execution, and cost tracking using Anthropic SDK.
**Core principle:** Stream (don't buffer). Track costs. Handle tools correctly.
**Announce at start:** "I'm using the anthropic-streaming-patterns skill for Claude API integration."
## When to Use
- Implementing Claude API service (Task 3.4)
- Implementing streaming responses
- Implementing tool execution within streams
- Tracking API costs
- Debugging streaming issues
## Quick Reference
| Pattern | SDK Method | Purpose |
|---------|-----------|---------|
| Initialize | messages.stream() | Start streaming |
| Text deltas | stream.on('text') | Receive text chunks |
| Tool start | stream.on('contentBlockStart') | Tool use begins |
| Tool input | stream.on('contentBlockDelta') | Accumulate params |
| Tool complete | stream.on('contentBlockStop') | Execute tool |
| Stream end | stream.on('message') | Calculate costs |
| Errors | stream.on('error') | Handle failures |
## Streaming Pattern (Complete)
```typescript
const stream = client.messages.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 8192,
messages: messageHistory,
tools: toolDefinitions,
});
let currentToolUse = null;
let accumulatedInput = '';
// Text deltas → forward to client
stream.on('text', (text) => {
sendToClient({type: 'content_delta', delta: text});
});
// Tool use started
stream.on('contentBlockStart', (block) => {
if (block.type === 'tool_use') {
currentToolUse = {name: block.name, id: block.id};
accumulatedInput = '';
sendToClient({type: 'tool_execution', tool: block.name});
}
});
// Tool input accumulation
stream.on('contentBlockDelta', (delta) => {
if (delta.type === 'input_json_delta' && currentToolUse) {
accumulatedInput = delta.partial_json;
}
});
// Tool execution
stream.on('contentBlockStop', async () => {
if (currentToolUse) {
const input = JSON.parse(accumulatedInput);
const result = await executeTool(currentToolUse.name, input);
sendToClient({type: 'tool_result', result});
currentToolUse = null;
}
});
// Stream complete with usage
stream.on('message', (message) => {
if (message.usage) {
const inputCost = (message.usage.input_tokens / 1000) * 0.003;
const outputCost = (message.usage.output_tokens / 1000) * 0.015;
saveSessionCost(sessionId, {
inputTokens: message.usage.input_tokens,
outputTokens: message.usage.output_tokens,
cost: inputCost + outputCost
});
}
});
stream.on('error', (error) => {
logger.error('Streaming error:', error);
sendToClient({type: 'error', error: error.message});
});
await stream.finalMessage(); // Wait for completion
```
## Cost Tracking (MANDATORY)
```typescript
const PRICING = {
input: 0.003, // $0.003 per 1k tokens
output: 0.015, // $0.015 per 1k output tokens
};
// Calculate per message
const cost = {
input: (inputTokens / 1000) * PRICING.input,
output: (outputTokens / 1000) * PRICING.output,
total: inputCost + outputCost
};
// Aggregate per session
sessionCosts.push(cost);
const sessionTotal = sessionCosts.reduce((sum, c) => sum + c.total, 0);
```
## Error Handling
```typescript
try {
const stream = await client.messages.stream({...});
} catch (error) {
if (error.status === 429) {
// Rate limit - wait and retry
await delay(60000);
return retry();
} else if (error.status === 401) {
// Auth error
throw new Error('Invalid API key');
} else {
logger.error(error);
throw error;
}
}
```
## Common Mistakes
| Mistake | Reality |
|---------|---------|
| "Buffering is simpler" | WRONG. Streaming provides real-time UX. Required. |
| "Cost tracking is optional" | WRONG. Users need visibility. Prevents surprise bills. |
| "I can figure out SDK" | WRONG. Event handling is subtle. Use proven patterns. |
| "Error handling later" | WRONG. Streams fail. Handle from start. |
### ❌ WRONG: Buffering
```typescript
const response = await client.messages.create({...}); // Buffering
const fullText = response.content[0].text;
sendToClient(fullText);
```
### ✅ CORRECT: Streaming
```typescript
const stream = await client.messages.stream({...});
stream.on('text', (delta) => sendToClient({type: 'content_delta', delta}));
```
## Red Flags
- "Buffering is easier" → WRONG. Stream for real-time.
- "Cost tracking is overhead" → WRONG. Mandatory feature.
- "Skip error handling" → WRONG. Streams fail often.
## Integration
- **Use FOR**: Task 3.4 (claude.service.ts)
- **Use WITH**: `@claude-mobile-cost-tracking`
- **Integrate**: Task 3.11 (cost.service.ts)Related Skills
apollo-server-patterns
Use when building GraphQL APIs with Apollo Server requiring resolvers, data sources, schema design, and federation.
api-patterns
API design principles and decision-making. REST vs GraphQL vs tRPC selection, response formats, versioning, pagination.
api-design-patterns
Design robust APIs with RESTful patterns, GraphQL schemas, versioning strategies, and error handling conventions. Supports OpenAPI/Swagger documentation and SDK generation patterns. Triggers on API design, schema definition, endpoint architecture, or developer experience requests.
Apex Enterprise Patterns
This skill should be used when the user asks to "create apex class", "write apex code", "implement service layer", "domain pattern", "selector pattern", "apex security", "bulkification", or mentions DRY, SOLID, or TDD principles for Apex. Provides framework-agnostic enterprise patterns for Apex development.
anthropic_administrator-automation
Automate Anthropic Admin tasks via Rube MCP (Composio): API keys, usage, workspaces, and organization management. Always search tools first for current schemas.
anthropic-usage
Check Anthropic API usage and costs for any time period. Use when the user asks about API costs, usage, spending, or billing for their Anthropic account. Supports natural language periods like "last week", "yesterday", "january 2025", specific dates, or date ranges.
anthropic-office-pdf
Comprehensive PDF manipulation toolkit for extracting text and tables, creating new PDFs, merging/splitting documents, and handling forms. When Claude needs to fill in a PDF form or programmatically process, generate, or analyze PDF documents at scale.
angular-ui-patterns
Modern Angular UI patterns for loading states, error handling, and data display. Use when building UI components, handling async data, or managing component states.
angreal-patterns
This skill should be used when the user asks to "test angreal tasks", "mock angreal", "document tasks", "angreal best practices", "error handling in tasks", "subprocess patterns", "dry run mode", "verbose mode", or needs guidance on testing patterns, development workflows, documentation strategies, or common implementation patterns for angreal tasks.
analyzing-text-patterns
Extract and analyze recurring patterns from log messages, span names, and event names using punctuation-based template discovery. Use when you need to understand log diversity, identify common message structures, detect unusual formats, or prepare for log parser development. Works by removing variable content and preserving structural markers.
analyzing-patterns
Automatically activated when user asks to "find patterns in...", "identify repeated code...", "analyze the architecture...", "what design patterns are used...", or needs to understand code organization, recurring structures, or architectural decisions
ai-sdk-patterns
Vercel AI SDK tool patterns for dx-toolkit - input schemas for smart queries, API key handling, raw response returns