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".
What this skill does
# 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 in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.