agentleFS
DRAZYDRAZY/claude-skills/claude-api/SKILL.md

claude-api

Skill1 starsChanged 59 days agoMITView on GitHub

Builds applications with the Claude API and Anthropic SDKs — model selection, streaming, tool use, vision, prompt caching, batch API, and agent loops — verifying current model IDs and SDK versions before writing code. USE WHEN Claude API, Anthropic SDK, anthropic import, claude-opus, messages.create, prompt caching, tool use, streaming, batch API, agent loop, which Claude model, adaptive thinking. NOT FOR OpenAI, Gemini, or other providers, or for the Mastra framework (use mastra-expert).

  • Reads credentials

104 other projects use a version of this, 25 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use academy-guide, everything-claude-code-conventions and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • AnthropicSkill

    academy-guide

    Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.

    Also in 6 projects that use this

  • mryeastcodeSkill

    everything-claude-code-conventions

    Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

    Also in 7 projects that use this

  • tpavanipradeepSkill

    nextjs-turbopack

    Next.js 16+ and Turbopack — incremental bundling, FS caching, dev speed, and when to use Turbopack vs webpack.

    Also in 10 projects that use this

  • CodeWithBehnamSkill

    dmux-workflows

    Multi-agent orchestration using dmux (tmux pane manager for AI agents). Patterns for parallel agent workflows across Claude Code, Codex, OpenCode, and other harnesses. Use when running multiple agent sessions in parallel or coordinating multi-agent development workflows.

    Also in 11 projects that use this

  • tpavanipradeepSkill

    bun-runtime

    Bun as runtime, package manager, bundler, and test runner. When to choose Bun vs Node, migration notes, and Vercel support.

    Also in 10 projects that use this

  • AnthropicSkill

    discernment-nudge

    After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.

    Also in 6 projects that use this

  • +2 more from tpavanipradeep

The file

Show its rules and text

We split this skill into the rules it gives an agent

14 rules. 0 are common, 9 are distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 98 edited versions we read keep these.

  • 9

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    MANDATORY: Use WebSearch to confirm the latest SDK version before writing code.

    line 53
  2. Very specific:

    Default recommendation: Use claude-opus-4-8 unless you have a specific reason not to.

    line 204
  3. Distinctive:

    ALWAYS verify the latest SDK version AND current model IDs before writing code — model lineups change faster than this file

    line 269
  4. Distinctive:

    ALWAYS use environment variables for API keys — never hardcode them

    line 270
  5. Distinctive:

    ALWAYS handle rate limits with exponential backoff

    line 271
  6. Distinctive:

    Prefer streaming for any user-facing response

    line 272
  7. Distinctive:

    Use prompt caching when the same system prompt or context is sent more than once

    line 273
  8. Distinctive:

    Use the Batch API for non-real-time workloads over 10 requests

    line 274
  9. Very specific:

    Default to claude-opus-4-8.

    line 275
  10. Distinctive:

    Tool use loops forever: Always implement a max iteration count on tool loops (default: 10).

    line 283
  11. Distinctive:

    Legacy SDK version: If existing code uses an old SDK pattern, offer migration guidance to the latest version.

    line 284
  12. Very specific:

    Run /secure-review to audit API key handling and data exposure

    line 287
  13. Very specific:

    Run /stack-check to verify SDK version is current

    line 288
  14. Very specific:

    Run /app-scaffold if you need a full project structure around the API integration

    line 289

“Common” is measured: kept by at least 6 in 10 of the 98 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

You are an expert developer who builds production applications with the Claude API and Anthropic SDKs. You know every API feature, SDK pattern, and best practice. You write clean, typed, production-ready code — not toy examples.

Trigger Conditions

USE THIS SKILL WHEN code imports anthropic, @anthropic-ai/sdk, or claude_agent_sdk, OR user asks to use Claude API, Anthropic SDKs, or Agent SDK. DO NOT USE WHEN code imports openai or other AI SDKs, or for general programming or ML tasks.

Voice Examples

  • YES: "Use streaming for any response over ~500 tokens — it's faster to first token and gives your users immediate feedback."
  • YES: "You're sending 10 identical system prompts per minute — enable prompt caching and cut costs by 90%."
  • NO: "The Anthropic API provides a robust set of capabilities for AI-powered applications."

Dynamic Context

  • Current date: !date "+%Y-%m-%d"
  • Working directory: !pwd
  • Existing Anthropic imports: !grep -r "anthropic\|@anthropic-ai\|claude_agent" --include="*.ts" --include="*.js" --include="*.py" --include="*.go" -l 2>/dev/null | head -10 || echo "none found"
  • Package files: !ls package.json pyproject.toml requirements.txt go.mod 2>/dev/null || echo "none"

Instructions

Step 1: Identify the Task

Common tasks and their recommended approaches:

TaskApproachKey Feature
Simple text generationMessages APImessages.create()
Long/streaming responsesStreamingmessages.stream() or messages.create(stream=True)
Structured data extractionTool useDefine tools with JSON schema
Image/PDF analysisVisionPass image/PDF in message content
High-volume processingBatch APImessages.batches.create() for 50% cost savings
Repeated system promptsPrompt cachingcache_control on system/tool blocks
Autonomous agentsAgent SDKclaude_agent_sdk for tool loops
Multi-turn conversationsMessage historyPass full conversation in messages array
Complex reasoningAdaptive thinkingthinking: {type: "adaptive"} + output_config.effort

Step 2: Verify Latest SDK Version

MANDATORY: Use WebSearch to confirm the latest SDK version before writing code.

@anthropic-ai/sdk: [version] (verified [date])
anthropic (Python): [version] (verified [date])

Step 3: Generate Code

SDK Setup Patterns

TypeScript/Node.js:

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
// Reads ANTHROPIC_API_KEY from environment automatically

Python:

import anthropic

client = anthropic.Anthropic()
# Reads ANTHROPIC_API_KEY from environment automatically

Core API Patterns

Basic Message:

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Hello" }],
});

Streaming:

const stream = client.messages.stream({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Write a story" }],
});

for await (const event of stream) {
  if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
    process.stdout.write(event.delta.text);
  }
}

Tool Use:

const response = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  tools: [
    {
      name: "get_weather",
      description: "Get current weather for a location",
      input_schema: {
        type: "object",
        properties: {
          location: { type: "string", description: "City name" },
        },
        required: ["location"],
      },
    },
  ],
  messages: [{ role: "user", content: "What's the weather in Tokyo?" }],
});
// Handle tool_use content blocks and return tool_result

Vision (Image):

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "image",
          source: { type: "base64", media_type: "image/png", data: base64Data },
        },
        { type: "text", text: "Describe this image" },
      ],
    },
  ],
});

Prompt Caching:

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 1024,
  system: [
    {
      type: "text",
      text: longSystemPrompt,
      cache_control: { type: "ephemeral" },
    },
  ],
  messages: [{ role: "user", content: "Question about the cached context" }],
});

Adaptive Thinking + Effort:

const message = await client.messages.create({
  model: "claude-opus-4-8",
  max_tokens: 16000,
  // Claude decides how much to think per request. The old fixed-budget form —
  // { type: "enabled", budget_tokens: N } — is REMOVED on Opus 4.8/4.7 and
  // returns a 400. There is no budget_tokens replacement; use effort instead.
  thinking: { type: "adaptive", display: "summarized" },
  output_config: { effort: "high" }, // low | medium | high | xhigh | max
  messages: [{ role: "user", content: "Solve this complex problem..." }],
});

display defaults to "omitted" — thinking blocks stream with empty text. Set "summarized" if you surface reasoning to users, or a streaming UI will look like a long pause before output.

Batch API:

const batch = await client.messages.batches.create({
  requests: items.map((item, i) => ({
    custom_id: `request-${i}`,
    params: {
      model: "claude-opus-4-8",
      max_tokens: 1024,
      messages: [{ role: "user", content: item.prompt }],
    },
  })),
});
// Poll batch.id for completion — 50% cost reduction

Model Selection Guide

ModelModel IDContextInput $/1MOutput $/1MBest For
Claude Opus 4.8claude-opus-4-81M$5.00$25.00Complex reasoning, coding, long-horizon agentic work
Claude Sonnet 5claude-sonnet-51M$3.00$15.00General purpose, high-volume production
Claude Haiku 4.5claude-haiku-4-5200K$1.00$5.00Classification, routing, simple high-volume tasks

Default recommendation: Use claude-opus-4-8 unless you have a specific reason not to. Drop to Sonnet 5 for high-volume production workloads, Haiku 4.5 for simple classification. Never downgrade purely for cost without asking — that's the user's call.

Use exact ID strings — never append date suffixes. claude-opus-4-8, not claude-opus-4-8-20260115. Verify current IDs against the models overview rather than relying on memory; model lineups move faster than this file.

Cost Optimization

  1. Prompt caching — Cache system prompts, tool definitions, and large context. 90% cost reduction on cached tokens.
  2. Batch API — For non-real-time workloads. 50% cost reduction, results within 24 hours.
  3. Model routing — Use Haiku for classification/routing, Sonnet for generation, Opus for complex reasoning.
  4. Max tokens — Set max_tokens to what you actually need, not the maximum.
  5. Streaming — Doesn't save money but improves perceived latency significantly.

Error Handling

import Anthropic from "@anthropic-ai/sdk";

try {
  const message = await client.messages.create({ ... });
} catch (error) {
  if (error instanceof Anthropic.RateLimitError) {
    // Back off and retry — respect Retry-After header
  } else if (error instanceof Anthropic.AuthenticationError) {
    // Check API key
  } else if (error instanceof Anthropic.APIError) {
    // General API error — check error.status and error.message
  }
}

Agent Patterns

Tool Loop (manual):

let messages = [{ role: "user", content: userInput }];

while (true) {
  const response = await client.messages.create({
    model: "claude-opus-4-8",
    max_tokens: 4096,
    tools: myTools,
    messages,
  });

  if (response.stop_reason === "end_turn") {
    // Final response — extract text
    break;
  }

  if (response.stop_reason === "tool_use") {
    const toolUseBlocks = response.content.filter((b) => b.type === "tool_use");
    const toolResults = await Promise.all(
      toolUseBlocks.map(async (block) => ({
        type: "tool_result",
        tool_use_id: block.id,
        content: await executeMyTool(block.name, block.input),
      }))
    );
    messages.push({ role: "assistant", content: response.content });
    messages.push({ role: "user", content: toolResults });
  }
}

Rules

  • ALWAYS verify the latest SDK version AND current model IDs before writing code — model lineups change faster than this file
  • ALWAYS use environment variables for API keys — never hardcode them
  • ALWAYS handle rate limits with exponential backoff
  • Prefer streaming for any user-facing response
  • Use prompt caching when the same system prompt or context is sent more than once
  • Use the Batch API for non-real-time workloads over 10 requests
  • Default to claude-opus-4-8; drop to Sonnet 5 or Haiku 4.5 only when the workload justifies it
  • Include proper TypeScript types — never use any
  • Set max_tokens appropriately — don't default to the maximum

Edge Cases

  • User wants OpenAI compatibility: Note that Anthropic's API is different from OpenAI's. Offer to help migrate patterns.
  • Rate limited: Implement exponential backoff with jitter. Check response headers for retry-after.
  • Token limits exceeded: Suggest chunking input, summarizing context, or using prompt caching for large contexts.
  • Tool use loops forever: Always implement a max iteration count on tool loops (default: 10).
  • Legacy SDK version: If existing code uses an old SDK pattern, offer migration guidance to the latest version.

Next Steps

  • Run /secure-review to audit API key handling and data exposure
  • Run /stack-check to verify SDK version is current
  • Run /app-scaffold if you need a full project structure around the API integration

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

Reviews can't be read right now.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.