🤖

Claude Agent SDK

Verified

by Anthropic

Guides the agent when building applications on top of Anthropic's Claude Agent SDK — the library for long-running autonomous agents with tool use, memory, and streaming. Covers installation, model routing (Opus 4.7 / Sonnet 4.6 / Haiku 4.5), tool definitions, and prompt caching.

anthropicsdkagentpythontypescripttool-useprompt-caching
View on GitHub

Claude Agent SDK

Anthropic's official SDK for building autonomous agents with Claude. This skill covers the canonical patterns.

Install

Python:

pip install claude-agent-sdk

TypeScript:

npm install @anthropic-ai/claude-agent-sdk

Set ANTHROPIC_API_KEY in the environment.

Model selection (as of 2026-04)

  • claude-opus-4-7 — most capable. Complex reasoning, long-horizon agents.
  • claude-sonnet-4-6 — balanced. Default for most production agents.
  • claude-haiku-4-5-20251001 — fastest, cheapest. Classification, routing, simple tools.

Default to Sonnet unless the task genuinely needs Opus. Use Haiku for any step that's "look at this and decide yes/no".

Core pattern — tool use loop

  1. Define tools as JSON Schema.
  2. Send messages + tools to client.messages.create(...).
  3. If the response has stop_reason: "tool_use", execute the tool, append the result as a tool_result message, loop.
  4. Terminate on stop_reason: "end_turn".

Prompt caching

Mark stable prefix content (system prompt, reference docs, tool schemas) with cache_control: {"type": "ephemeral"}. Cache TTL is 5 minutes. Hit rates above 90% are normal and dramatically cut cost/latency. Always enable caching for agents with repeating context.

Streaming

Use client.messages.stream(...) for any user-facing agent. Buffer tool_use deltas until complete; don't attempt to execute a partial tool call.

Rate limits and retries

  • 429 responses include retry-after — honor it.
  • Use exponential backoff only on 5xx / network errors, never on 400/401/403.
  • Track token usage from response.usage and surface it to the user.

Safety rails for autonomous agents

  • Require human approval for destructive tool calls (delete, send email, execute shell).
  • Cap the tool-use loop (e.g., 20 iterations) to prevent runaway cost.
  • Log every tool call with args and result for audit.
  • Never include user secrets in system prompts — pass them via tool calls only.

References

  • Python SDK: https://github.com/anthropics/claude-agent-sdk-python
  • TypeScript SDK: https://github.com/anthropics/claude-agent-sdk-typescript
  • API docs: https://docs.claude.com
  • Model card (Opus 4.7): https://www.anthropic.com/claude/opus