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

claude-api

Skill1 starsChanged 3 months 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

59 other projects use a version of this, 10 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use web-artifacts-builder, algorithmic-art 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

    web-artifacts-builder

    Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.

    Also in 28 projects that use this

  • GoogleSkill

    algorithmic-art

    Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems. Create original algorithmic art rather than copying existing artists' work to avoid copyright violations.

    Also in 26 projects that use this

  • JetBrainsSkill

    doc-coauthoring

    Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.

    Also in 27 projects that use this

  • JetBrainsSkill

    slack-gif-creator

    Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack.

    Also in 26 projects that use this

  • GoogleSkill

    internal-comms

    A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

    Also in 27 projects that use this

  • tpavanipradeepSkill

    documentation-lookup

    Use up-to-date library and framework docs via Context7 MCP instead of training data. Activates for setup questions, API references, code examples, or when the user names a framework (e.g. React, Next.js, Prisma).

    Also in 3 projects that use this

  • +4 more from JetBrains

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 56 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 56 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.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

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.