anth-sdk-patterns
Apply production-ready Anthropic SDK patterns for TypeScript and Python. Use when implementing Claude integrations, building reusable wrappers, or establishing team coding standards for the Messages API. Trigger with phrases like "anthropic SDK patterns", "claude best practices", "anthropic code patterns", "production claude code".
Best use case
anth-sdk-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Apply production-ready Anthropic SDK patterns for TypeScript and Python. Use when implementing Claude integrations, building reusable wrappers, or establishing team coding standards for the Messages API. Trigger with phrases like "anthropic SDK patterns", "claude best practices", "anthropic code patterns", "production claude code".
Teams using anth-sdk-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/anth-sdk-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How anth-sdk-patterns Compares
| Feature / Agent | anth-sdk-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?
Apply production-ready Anthropic SDK patterns for TypeScript and Python. Use when implementing Claude integrations, building reusable wrappers, or establishing team coding standards for the Messages API. Trigger with phrases like "anthropic SDK patterns", "claude best practices", "anthropic code patterns", "production claude code".
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.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Anthropic SDK Patterns
## Overview
Production-ready patterns for the Anthropic SDK covering client management, error handling, type safety, and multi-tenant configurations.
## Prerequisites
- Completed `anth-install-auth` setup
- Familiarity with async/await patterns
- TypeScript 5+ or Python 3.10+
## Pattern 1: Typed Wrapper with Retry
```typescript
import Anthropic from '@anthropic-ai/sdk';
import type { Message, MessageCreateParams } from '@anthropic-ai/sdk/resources/messages';
class ClaudeService {
private client: Anthropic;
constructor(apiKey?: string) {
this.client = new Anthropic({
apiKey: apiKey || process.env.ANTHROPIC_API_KEY,
maxRetries: 3, // SDK handles 429 + 5xx automatically
timeout: 60_000,
});
}
async complete(
prompt: string,
options: Partial<MessageCreateParams> = {}
): Promise<string> {
const message = await this.client.messages.create({
model: options.model || 'claude-sonnet-4-20250514',
max_tokens: options.max_tokens || 1024,
messages: [{ role: 'user', content: prompt }],
...options,
});
const textBlock = message.content.find((b) => b.type === 'text');
if (!textBlock || textBlock.type !== 'text') {
throw new Error(`No text in response: ${message.stop_reason}`);
}
return textBlock.text;
}
async *stream(prompt: string, model = 'claude-sonnet-4-20250514'): AsyncGenerator<string> {
const stream = this.client.messages.stream({
model,
max_tokens: 4096,
messages: [{ role: 'user', content: prompt }],
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
yield event.delta.text;
}
}
}
}
```
## Pattern 2: Multi-Turn Conversation Manager
```python
import anthropic
from dataclasses import dataclass, field
@dataclass
class Conversation:
client: anthropic.Anthropic = field(default_factory=anthropic.Anthropic)
model: str = "claude-sonnet-4-20250514"
system: str = ""
messages: list = field(default_factory=list)
max_tokens: int = 4096
def say(self, user_message: str) -> str:
self.messages.append({"role": "user", "content": user_message})
response = self.client.messages.create(
model=self.model,
max_tokens=self.max_tokens,
system=self.system,
messages=self.messages,
)
assistant_text = response.content[0].text
self.messages.append({"role": "assistant", "content": assistant_text})
return assistant_text
@property
def token_count(self) -> int:
"""Estimate total tokens in conversation."""
return sum(len(str(m["content"])) // 4 for m in self.messages)
# Usage
conv = Conversation(system="You are a helpful coding assistant.")
print(conv.say("What is a closure in JavaScript?"))
print(conv.say("Can you show me an example?")) # Has full context
```
## Pattern 3: Structured Output with Prefill
```python
import json
import anthropic
client = anthropic.Anthropic()
def extract_structured(text: str, schema_description: str) -> dict:
"""Force JSON output using assistant prefill technique."""
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": f"Extract data from this text as JSON.\n\nSchema: {schema_description}\n\nText: {text}"},
{"role": "assistant", "content": "{"} # Prefill forces JSON output
]
)
json_str = "{" + message.content[0].text
return json.loads(json_str)
# Usage
data = extract_structured(
"John Smith, 35, lives in NYC and works at Google as a PM.",
'{"name": str, "age": int, "city": str, "company": str, "role": str}'
)
# {"name": "John Smith", "age": 35, "city": "NYC", "company": "Google", "role": "PM"}
```
## Pattern 4: Multi-Tenant Client Factory
```typescript
const clients = new Map<string, Anthropic>();
export function getClientForTenant(tenantId: string): Anthropic {
if (!clients.has(tenantId)) {
const apiKey = getApiKeyForTenant(tenantId); // From your secret store
clients.set(tenantId, new Anthropic({ apiKey }));
}
return clients.get(tenantId)!;
}
```
## Pattern 5: Token-Aware Request Sizing
```python
# Use the Token Counting API to pre-check request size
count = client.messages.count_tokens(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": long_document}],
system="You are a summarizer."
)
print(f"Input will use {count.input_tokens} tokens")
# Adjust max_tokens to stay within budget
remaining_budget = 200_000 - count.input_tokens
max_tokens = min(4096, remaining_budget)
```
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| SDK `maxRetries` | 429 / 5xx errors | Built-in exponential backoff |
| Prefill technique | Force JSON output | No regex parsing needed |
| Token counting | Long documents | Prevent context overflow |
| Client factory | Multi-tenant SaaS | Key isolation per customer |
## Resources
- [Client SDKs](https://docs.anthropic.com/en/api/client-sdks)
- [Token Counting API](https://docs.anthropic.com/en/docs/build-with-claude/token-counting)
- [Prompt Caching](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching)
## Next Steps
Apply patterns in `anth-core-workflow-a` for tool use workflows.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".