Skip to content

Anthropic

Anthropic is an AI safety and research company focused on building reliable, interpretable, and steerable AI systems. Included in their offerings is the Claude AI family of models, which are known for their conversational abilities, careful reasoning, and capacity to follow complex instructions. The Strands Agents SDK implements an Anthropic provider, allowing users to run agents against Claude models directly.

Anthropic is configured as an optional dependency in Strands Agents. To install, run:

Terminal window
pip install 'strands-agents[anthropic]' strands-agents-tools

After installing dependencies, you can import and initialize the Strands Agents’ Anthropic provider as follows:

from strands import Agent
from strands.models.anthropic import AnthropicModel
from strands_tools import calculator
model = AnthropicModel(
client_args={
"api_key": "<KEY>",
},
# **model_config
max_tokens=1028,
model_id="claude-sonnet-4-6",
params={
"temperature": 0.7,
}
)
agent = Agent(model=model, tools=[calculator])
response = agent("What is 2+2")
print(response)

The client_args configure the underlying Anthropic client. For a complete list of available arguments, please refer to the Anthropic Python SDK docs.

The model_config configures the underlying model selected for inference. The supported configurations are:

ParameterDescriptionExampleOptions
max_tokensMaximum number of tokens to generate before stopping1028reference
model_idID of a model to useclaude-sonnet-4-6reference
paramsAdditional pass-through parameters{"metadata": {"user_id": "u1"}}reference
cache_configEnables prompt caching on the system prompt and the conversationCacheConfig(ttl="1h")reference
cache_toolsCaches the tool definitions"default" or CacheToolsConfig(ttl="1h")reference

If you encounter the error ModuleNotFoundError: No module named 'anthropic', this means you haven’t installed the anthropic dependency in your environment. To fix, run pip install 'strands-agents[anthropic]'.

You can pass a pre-configured Anthropic client directly to AnthropicModel. You are responsible for managing the client’s lifecycle.

The Python SDK does not currently support passing a pre-configured client. Use client_args to configure the client at initialization.

Anthropic models support structured output through tool use. Pass a schema to the agent, and Strands generates a tool from it that the model calls to return validated, type-safe data.

Define a Pydantic model and pass it to agent.structured_output():

from pydantic import BaseModel, Field
from strands import Agent
from strands.models.anthropic import AnthropicModel
class MovieReview(BaseModel):
"""Analyze a movie review."""
title: str = Field(description="Movie title")
rating: int = Field(description="Rating from 1-10", ge=1, le=10)
genre: str = Field(description="Primary genre")
sentiment: str = Field(description="Overall sentiment: positive, negative, or neutral")
summary: str = Field(description="Brief summary of the review")
model = AnthropicModel(
client_args={"api_key": "<KEY>"},
max_tokens=1028,
model_id="claude-sonnet-4-6",
)
agent = Agent(model=model)
result = agent.structured_output(
MovieReview,
"""
Just watched "The Matrix" - what an incredible sci-fi masterpiece!
The groundbreaking visual effects and philosophical themes make this
a must-watch. Keanu Reeves delivers a solid performance. 9/10!
"""
)
print(f"Movie: {result.title}")
print(f"Rating: {result.rating}/10")
print(f"Genre: {result.genre}")
print(f"Sentiment: {result.sentiment}")

For schema patterns, error handling, and per-invocation overrides, see Structured Output.

Prompt caching lets Claude reuse an already-processed prefix of your prompt instead of reprocessing it on every call. The mechanism, the cost model, and the cache metrics match Amazon Bedrock; this section covers what differs here.

Caching is off by default. Set cache_configcacheConfig to cache the system prompt and add a cache point to the last user message, which caches everything before it:

from strands import Agent
from strands.models.anthropic import AnthropicModel
from strands.models import CacheConfig, CacheToolsConfig
model = AnthropicModel(
model_id="claude-sonnet-4-6",
max_tokens=1028,
cache_config=CacheConfig(ttl="1h"),
cache_tools=CacheToolsConfig(ttl="1h"),
)
agent = Agent(model=model)
result = agent("Summarize the attached report.")
print(result.metrics.accumulated_usage)
# Typical output:
# {'inputTokens': 12, ..., 'cacheReadInputTokens': 2505}

Cache activity is reported in the usage metrics, in the same fields Bedrock uses: see cache metrics.

cache_config caches the system prompt and the conversation; set system_prompt_ttl=False to leave the system prompt uncached, or a TTL string (system_prompt_ttl="1h") to give it its own duration. cache_tools caches the tool definitions and works on its own, so tool definitions can be cached without caching the conversation. Passing a plain string ("default") only switches it on: the value is not a TTL. Use CacheToolsConfig(ttl=...) to set one.

strategy is ignored by this provider.

Placement works as it does on Amazon Bedrock: a cache point you put in the last user message is kept where you put it, automatic placement is suspended for that message, and points in earlier messages are removed. Place your point ahead of content that is rebuilt on every call, otherwise it lands inside the cached prefix and every request writes an entry that none ever reads.

Two constraints are specific to this API:

  • Only some block types accept a cache point. Text, image, tool use, tool result, and document blocks do; a reasoning block does not. A point with only a reasoning block, or a media block sourced by location, ahead of it cannot be honored, so automatic placement applies instead.
  • Maximum of four cache points per request, shared across the tool definitions, the system prompt, and the messages. Automatic placement uses one per part it caches, so hand-placing several of your own alongside it can exceed the limit, and the API rejects the request.

A prompt below the model’s minimum cacheable length is not cached: if both cache metrics stay at zero, that is the likely cause. See cache limitations for per-model thresholds.

Token counting is used by context management strategies to estimate input tokens before each model call.

The Anthropic provider can use the native messages.count_tokens() API, which provides exact token counts including system prompts, messages, and tool specifications.

You can enable native token counting with:

model = AnthropicModel(
model_id="claude-sonnet-4-6",
use_native_token_count=True,
)

When disabled (or if the API call fails), falls back to estimation with a character-based heuristic (characters ÷ 4 for text, characters ÷ 2 for JSON).