xiaohongshu
xiaohongshu
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
Full skill instructions
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."
| 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 |
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
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);
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;
}
}
| 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. |
const response = await client.messages.create({...}); // Buffering
const fullText = response.content[0].text;
sendToClient(fullText);
const stream = await client.messages.stream({...});
stream.on('text', (delta) => sendToClient({type: 'content_delta', delta}));
@claude-mobile-cost-trackingxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience