All skills
anthropics avatar

/claude-api

@8a1541c official
by Anthropicanthropics/skills179k stars
21,196

Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).

Use this Skill: https://skilld.dev/gh/anthropics/skills/claude-api

This session only. Nothing lands on disk.

sharedmanaged-agents-memory.md

≈2.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Managed Agents - Memory Stores

Public beta. Memory stores ship under the agent-memory-2026-07-22 beta header; the SDK sets it automatically on all client.beta.memory_stores.* calls. Don't add managed-agents-2026-04-01 to these calls - sending both headers on a memory store request returns a 400. Attaching a store to a session is a session call and still uses managed-agents-2026-04-01. If client.beta.memory_stores is missing, upgrade to the latest SDK release.

Sessions are ephemeral by default - when one ends, anything the agent learned is gone. A memory store is a workspace-scoped collection of small text documents that persists across sessions. When a store is attached to a session (via resources[]), it is mounted into the container as a filesystem directory; the agent reads and writes it with the ordinary file tools, and a system-prompt note tells it the mount is there.

Every mutation to a memory produces an immutable memory version (memver_...), giving you an audit trail and point-in-time rollback/redact.

Warning: Never store credentials, API keys, or tokens in memory stores. Memories persist across sessions and are returned verbatim into future contexts - a key written once is replayed into every later session that mounts the store. Use vault environment_variable credentials instead (shared/managed-agents-tools.md -> Vaults). If a secret has already been written, delete the memory and redact the affected versions (see "Redact a version" below).

Object model

Object ID prefix Scope Notes
Memory store memstore_... Workspace Attach to sessions via resources[]
Memory mem_... Store One text file, addressed by path (<= 100KB each - prefer many small files)
Memory version memver_... Memory Immutable snapshot per mutation; operation in created / modified / deleted

Create a store

description is passed to the agent so it knows what the store contains - write it for the model, not for humans.

store = client.beta.memory_stores.create(
    name="User Preferences",
    description="Per-user preferences and project context.",
)
print(store.id)  # memstore_01Hx...

Other SDKs: TypeScript client.beta.memoryStores.create({...}); Go client.Beta.MemoryStores.New(ctx, ...). See shared/managed-agents-api-reference.md -> SDK Method Reference for the full per-language table.

Stores support retrieve / update / list (with include_archived, created_at_{gte,lte} filters) / delete / archive. Archive makes the store read-only - existing session attachments continue, new sessions cannot reference it; no unarchive.

Seed with content (optional)

Pre-load reference material before any session runs. memories.create creates a memory at the given path; if a memory already exists there the call returns 409 (memory_path_conflict_error, with the conflicting_memory_id). The store ID is the first positional argument.

client.beta.memory_stores.memories.create(
    store.id,
    path="/formatting_standards.md",
    content="All reports use GAAP formatting. Dates are ISO-8601...",
)

Attach to a session

Memory stores go in the session's resources[] array alongside file and github_repository resources (see shared/managed-agents-environments.md -> Resources). Memory stores attach at session create time only - sessions.resources.add() does not accept memory_store. Sessions on self-hosted environments attach them the same way (and memory_store is the only resource type those environments accept) - see the self-hosted note below.

session = client.beta.sessions.create(
    agent=agent.id,
    environment_id=environment.id,
    resources=[
        {
            "type": "memory_store",
            "memory_store_id": store.id,
            "access": "read_write",  # or "read_only"; default is "read_write"
            "instructions": "User preferences and project context. Check before starting any task.",
        }
    ],
)
Field Required Notes
type Yes "memory_store"
memory_store_id Yes memstore_...
access - "read_write" (default) or "read_only" - enforced at the filesystem level on the cloud mount; on self-hosted sandboxes enforced by the worker's write/edit tools and by the upload path (see below)
instructions - Session-specific guidance for this store, in addition to the store's name/description. <= 4,096 chars.

Max 8 memory stores per session. Attach multiple when different slices of memory have different owners or lifecycles - e.g. one read-only shared-reference store plus one read-write per-user store, or one store per end-user/team/project sharing a single agent config.

How the agent sees it (FUSE mount)

Each attached store is mounted in the session container at /mnt/memory/<store-name>/. The agent interacts with it using the standard file tools (bash, read, write, edit, glob, grep) - there are no dedicated memory tools. On cloud sandboxes access: "read_only" makes the mount read-only at the filesystem level (on self-hosted sandboxes it is enforced by the worker's write/edit tools and the upload path - see below); "read_write" allows the agent to create, edit, and delete files under it. A short description of each mount (name, path, instructions, access) is automatically injected into the system prompt so the agent knows the store exists without you having to mention it.

Writes the agent makes under the mount are persisted back to the store and produce memory versions just like host-side memories.update calls.

Self-hosted sandboxes: a synced local copy, not a live mount. On a self_hosted environment the SDK worker (EnvironmentWorker - Python, TypeScript, Go; the ant CLI worker does not mount stores) downloads each attached store to the same /mnt/memory/<store-name>/ path and reconciles it with the store on an interval, so writes are visible to other sessions only after sync, conflicts resolve in favor of the store, and read_only is enforced by the worker's tools rather than the filesystem (bash can still alter the local copy). Everything else - sync interval, per-session secret, host prep, troubleshooting - lives in shared/managed-agents-self-hosted-sandboxes.md § Memory stores. Not available on self-hosted environments on Claude Platform on AWS.

Manage memories directly (host-side)

Use these for review workflows, correcting bad memories, or seeding stores out-of-band.

List

Returns Memory | MemoryPrefix entries - a MemoryPrefix (type: "memory_prefix", just a path) is a directory-like node when listing hierarchically. Use path_prefix to scope (include a trailing slash: "/notes/" matches /notes/a.md but not /notes_backup/old.md) and depth to bound the tree walk. Pass view="full" to include content in each item; the default "basic" returns metadata only.

for m in client.beta.memory_stores.memories.list(store.id, path_prefix="/"):
    if m.type == "memory":
        print(f"{m.path}  ({m.content_size_bytes} bytes, sha={m.content_sha256[:8]})")
    else:  # "memory_prefix"
        print(f"{m.path}/")

Read

mem = client.beta.memory_stores.memories.retrieve(memory_id, memory_store_id=store.id)
print(mem.content)

retrieve defaults to view="full" (content included); view matters mainly on list endpoints.

Create vs. update

Operation Addressed by Semantics
memories.create(store_id, path=..., content=...) Path Create at path. 409 (memory_path_conflict_error, includes conflicting_memory_id) if the path is already occupied.
memories.update(mem_id, memory_store_id=..., path=..., content=...) mem_... ID Mutate existing memory. Change content, path (rename), or both. Renaming onto an occupied path returns the same 409 memory_path_conflict_error.
mem = client.beta.memory_stores.memories.create(
    store.id,
    path="/preferences/formatting.md",
    content="Always use tabs, not spaces.",
)

client.beta.memory_stores.memories.update(
    mem.id,
    memory_store_id=store.id,
    path="/archive/2026_q1_formatting.md",  # rename
)

Optimistic concurrency (precondition on update)

memories.update accepts a precondition so you can read -> modify -> write back without clobbering a concurrent writer. The only supported type is content_sha256. On mismatch the API returns 409 (memory_precondition_failed_error) - re-read and retry against fresh state.

client.beta.memory_stores.memories.update(
    mem.id,
    memory_store_id=store.id,
    content="CORRECTED: Always use 2-space indentation.",
    precondition={"type": "content_sha256", "content_sha256": mem.content_sha256},
)

Delete

client.beta.memory_stores.memories.delete(mem.id, memory_store_id=store.id)

Pass expected_content_sha256 for a conditional delete.

Audit and rollback - memory versions

Every mutation creates an immutable memver_... snapshot. Versions accumulate for the lifetime of the parent memory; memories.retrieve always returns the current head, the version endpoints give you history.

Operation that triggers it operation field on the version
memories.create at a new path "created"
memories.update changing content, path, or both (or an agent-side write to the mount) "modified"
memories.delete "deleted"

Each version also records created_by - an actor object with type in session_actor / api_actor / user_actor - and, after redaction, redacted_at + redacted_by.

List versions

Newest-first, paginated. Filter by memory_id, operation, session_id, api_key_id, or created_at_gte / created_at_lte. Pass view="full" to include content; default is metadata-only.

for v in client.beta.memory_stores.memory_versions.list(store.id, memory_id=mem.id):
    print(f"{v.id}: {v.operation}")

Retrieve a version

version = client.beta.memory_stores.memory_versions.retrieve(
    version_id, memory_store_id=store.id
)
print(version.content)

Redact a version

Scrubs content from a historical version while preserving the audit trail (actor + timestamps). Clears content, content_sha256, content_size_bytes, and path; everything else stays. Use for leaked secrets, PII, or user-deletion requests.

client.beta.memory_stores.memory_versions.redact(version_id, memory_store_id=store.id)

Endpoint reference

See shared/managed-agents-api-reference.md -> Memory Stores / Memories / Memory Versions for the full HTTP method/path tables. Raw HTTP base path:

POST   /v1/memory_stores
POST   /v1/memory_stores/{memory_store_id}/archive
GET    /v1/memory_stores/{memory_store_id}/memories
PATCH  /v1/memory_stores/{memory_store_id}/memories/{memory_id}
GET    /v1/memory_stores/{memory_store_id}/memory_versions
POST   /v1/memory_stores/{memory_store_id}/memory_versions/{version_id}/redact

For cURL examples and the CLI (ant beta:memory-stores ...), WebFetch the Memory URL in shared/live-sources.md -> Managed Agents.

Source: SKILL.md on GitHub

1 warning2d5 checks · Risk SAFE
  • Gen Agent Trust Hub2d

    This skill is a developer reference for the Claude API and Anthropic SDKs. It includes some security considerations related to building agents with powerful capabilities like shell command execution and web fetching. While these present a potential surface for indirect prompt injection, the skill provides extensive security guidance, emphasizing sandboxing and input validation as mitigation strategies. All external resources and packages originate from trusted official sources.

  • Socket2d

    No alerts

  • Snyk2d

    Risk: LOW · No issues

  • Runlayer7mo

    12/26 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 8a1541c. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 3 days ago.

Activeupdated 3 days ago

README badge

README badge for anthropics/skills/claude-api

Reference for the Claude API and official Anthropic SDKs — model IDs, pricing, parameters, streaming, tool use, MCP, managed agents, caching, token counting, and model migration. Read this skill before opening a file that involves Claude, an Anthropic model, agent workflows, or LLM-shaped tasks with no specified provider.

Generated from the current SKILL.md.

Which Claude model should I use by default?
Use Claude Opus 4.8 (model ID: `claude-opus-4-8`) as the default. Also default to adaptive thinking (`thinking: {type: "adaptive"}`) for anything complex, and streaming for requests with long input, output, or high max_tokens.
What should I do if the project uses OpenAI or another non-Anthropic provider?
Stop and ask the user whether they want to switch the file to Claude or want a non-Claude implementation. Do not edit a non-Anthropic file with Anthropic SDK calls.
Should I use the official SDK or raw HTTP?
Use the official Anthropic SDK for your language whenever one exists (Python, TypeScript, Java, Go, Ruby, C#, PHP). Only use raw HTTP (curl, requests, fetch) if the user explicitly asks for it, the project is shell/cURL, or the language has no official SDK.
When should I use Managed Agents versus Claude API with tool use?
Use Managed Agents when you want Anthropic to run the agent loop and host a per-session container for tool execution (file ops, bash, code). Use Claude API with tool use for multi-step workflows where you control the orchestration and host the compute yourself.
Does this skill work with Amazon Bedrock, Google Vertex AI, or Microsoft Foundry?
Managed Agents is not available on those platforms. Use Claude API with tool use instead. Claude Platform on AWS (Anthropic-operated) has full feature parity with the first-party API.

Generated from the current SKILL.md. These answers refresh after source changes.