The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
docs(anthropic): clean up docstrings (#34317)
Mason Daugherty57ff48e62e57
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.pyindex 58ca2da92e..5b075b3f92 100644--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py@@ -663,1152 +663,35 @@ def _handle_anthropic_bad_request(e: anthropic.BadRequestError) -> None:class ChatAnthropic(BaseChatModel):"""Anthropic (Claude) chat models.- See the [Claude Platform docs](https://platform.claude.com/docs/en/about-claude/models/overview)- for a list of the latest models, their capabilities, and pricing.-- Setup:- Install `langchain-anthropic` and set environment variable `ANTHROPIC_API_KEY`.-- ```bash- pip install -U langchain-anthropic- export ANTHROPIC_API_KEY="your-api-key"- ```-- Key init args:- **Completion params:**-- * [`model`][langchain_anthropic.chat_models.ChatAnthropic.model]: Name of- Anthropic model to use. e.g. `'claude-sonnet-4-5-20250929'`.- * [`temperature`][langchain_anthropic.chat_models.ChatAnthropic.temperature]:- Sampling temperature. Ranges from `0.0` to `1.0`.- * [`max_tokens`][langchain_anthropic.chat_models.ChatAnthropic.max_tokens]: Max- number of tokens to generate.-- **Client params:**-- * [`timeout`][langchain_anthropic.chat_models.ChatAnthropic.default_request_timeout]:- Timeout for requests.- * [`anthropic_proxy`][langchain_anthropic.chat_models.ChatAnthropic.anthropic_proxy]:- Proxy to use for the Anthropic clients, will be used for every API call.- If not passed in will be read from env var `ANTHROPIC_PROXY`.- * [`max_retries`][langchain_anthropic.chat_models.ChatAnthropic.max_retries]:- Max number of retries if a request fails.- * [`api_key`][langchain_anthropic.chat_models.ChatAnthropic.anthropic_api_key]:- Anthropic API key. If not passed in will be read from env var- `ANTHROPIC_API_KEY`.- * [`base_url`][langchain_anthropic.chat_models.ChatAnthropic.anthropic_api_url]:- Base URL for API requests. Only specify if using a proxy or service emulator.-- ???+ example "Instantiate"-- ```python- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- temperature=0,- max_tokens=1024,- timeout=None,- max_retries=2,- # api_key="...",- # base_url="...",- # other params...- )- ```-- ???+ note "Unsupported params"-- Any param which is not explicitly supported will be passed directly to- [`Anthropic.messages.create(...)`](https://platform.claude.com/docs/en/api/python/messages/create)- each time to the model is invoked.-- !!! example-- ```python- from langchain_anthropic import ChatAnthropic- import anthropic-- ChatAnthropic(..., extra_headers={}).invoke(...)-- # Results in underlying API call of:-- anthropic.Anthropic(..).messages.create(..., extra_headers={})-- # ... which is also equivalent to:-- ChatAnthropic(...).invoke(..., extra_headers={})- ```-- ???+ example "Invoke"-- ```python- messages = [- (- "system",- "You are a helpful translator. Translate the user sentence to French.",- ),- (- "human",- "I love programming.",- ),- ]- model.invoke(messages)- ```-- ```python- AIMessage(- content="J'aime la programmation.",- response_metadata={- "id": "msg_01Trik66aiQ9Z1higrD5XFx3",- "model": "claude-sonnet-4-5-20250929",- "stop_reason": "end_turn",- "stop_sequence": None,- "usage": {"input_tokens": 25, "output_tokens": 11},- },- id="run-5886ac5f-3c2e-49f5-8a44-b1e92808c929-0",- usage_metadata={- "input_tokens": 25,- "output_tokens": 11,- "total_tokens": 36,- },- )- ```-- ???+ example "Stream"-- ```python- for chunk in model.stream(messages):- print(chunk.text, end="")- ```-- ```python- AIMessageChunk(content="J", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content="'", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content="a", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content="ime", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content=" la", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content=" programm", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content="ation", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- AIMessageChunk(content=".", id="run-272ff5f9-8485-402c-b90d-eac8babc5b25")- ```-- To aggregate the full message from the stream:-- ```python- stream = model.stream(messages)- full = next(stream)- for chunk in stream:- full += chunk- full- ```-- ```python- AIMessageChunk(content="J'aime la programmation.", id="run-b34faef0-882f-4869-a19c-ed2b856e6361")- ```-- ???+ example "Async invocation"-- ```python- await model.ainvoke(messages)-- # stream:- # async for chunk in (await model.astream(messages))-- # batch:- # await model.abatch([messages])- ```-- ```python- AIMessage(- content="J'aime la programmation.",- response_metadata={- "id": "msg_01Trik66aiQ9Z1higrD5XFx3",- "model": "claude-sonnet-4-5-20250929",- "stop_reason": "end_turn",- "stop_sequence": None,- "usage": {"input_tokens": 25, "output_tokens": 11},- },- id="run-5886ac5f-3c2e-49f5-8a44-b1e92808c929-0",- usage_metadata={- "input_tokens": 25,- "output_tokens": 11,- "total_tokens": 36,- },- )- ```-- ???+ example "Token counting"-- You can count tokens in messages before sending them to the model using the- [`get_num_tokens_from_messages()`][langchain_anthropic.chat_models.ChatAnthropic.get_num_tokens_from_messages]- method, which uses Anthropic's official token counting API.-- ???+ example "Tools"-- ```python hl_lines="16"- from pydantic import BaseModel, Field--- class GetWeather(BaseModel):- '''Get the current weather in a given location'''-- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")--- class GetPopulation(BaseModel):- '''Get the current population in a given location'''-- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")--- model_with_tools = model.bind_tools([GetWeather, GetPopulation])- ai_msg = model_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")- ai_msg.tool_calls- ```-- ```python- [- {- "name": "GetWeather",- "args": {"location": "Los Angeles, CA"},- "id": "toolu_01KzpPEAgzura7hpBqwHbWdo",- },- {- "name": "GetWeather",- "args": {"location": "New York, NY"},- "id": "toolu_01JtgbVGVJbiSwtZk3Uycezx",- },- {- "name": "GetPopulation",- "args": {"location": "Los Angeles, CA"},- "id": "toolu_01429aygngesudV9nTbCKGuw",- },- {- "name": "GetPopulation",- "args": {"location": "New York, NY"},- "id": "toolu_01JPktyd44tVMeBcPPnFSEJG",- },- ]- ```-- See [`ChatAnthropic.bind_tools()`][langchain_anthropic.chat_models.ChatAnthropic.bind_tools]- for more info.-- !!! note "Strict tool use"-- Anthropic supports a strict tool use feature that guarantees tool names- and arguments are validated and correctly typed.-- See [`ChatAnthropic.bind_tools()`][langchain_anthropic.chat_models.ChatAnthropic.bind_tools]- for more info.-- ???+ example "Token-efficient tool use"-- See LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#token-efficient-tool-use)- for more detail.-- ```python hl_lines="6"- from langchain_anthropic import ChatAnthropic- from langchain_core.tools import tool-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- betas=["token-efficient-tools-2025-02-19"]- )-- @tool- def get_weather(location: str) -> str:- \"\"\"Get the weather at a location.\"\"\"- return "It's sunny."-- model_with_tools = model.bind_tools([get_weather])- response = model_with_tools.invoke(- "What's the weather in San Francisco?"- )- print(response.tool_calls)- print(f'Total tokens: {response.usage_metadata["total_tokens"]}')- ```-- ```txt- [{'name': 'get_weather', 'args': {'location': 'San Francisco'}, 'id': 'toolu_01HLjQMSb1nWmgevQUtEyz17', 'type': 'tool_call'}]- Total tokens: 408- ```-- ???+ example "Fine-grained tool streaming"-- Fine-grained tool streaming enables faster streaming of tool parameters- without buffering or JSON validation, reducing latency when receiving large tool- parameters. For more details, see the- [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#fine-grained-tool-streaming).-- ```python hl_lines="5"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-3-5-sonnet-20241022",- betas=["fine-grained-tool-streaming-2025-05-14"]- )-- def write_document(title: str, content: str) -> str:- \"\"\"Write a document with the given title and content.\"\"\"- return f"Document '{title}' written"-- model_with_tools = model.bind_tools([write_document])-- # Stream tool calls with reduced latency- for chunk in model_with_tools.stream(- "Write a document about the benefits of streaming APIs"- ):- print(chunk)- ```-- !!! note-- This is a beta feature that may return invalid or partial JSON inputs.-- Implement appropriate error handling for incomplete JSON, especially- when `max_tokens` is reached.-- ???+ example "Image input"-- See the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#multimodal)- for more detail.-- ??? example "URL"-- ```python- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- message = HumanMessage(- content=[- {"type": "text", "text": "Describe the image at the URL."},- {- "type": "image",- "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",- },- ]- )- response = model.invoke([message])- ```-- ??? example "Base64 encoded"-- ```python- import base64- import httpx- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- image_url = "https://picsum.photos/id/237/200/300"- image_data = base64.b64encode(httpx.get(image_url, follow_redirects=True).content).decode("utf-8")-- message = HumanMessage(- content=[- {"type": "text", "text": "Describe the image."},- {- "type": "image",- "base64": image_data,- "mime_type": "image/jpeg",- },- ]- )- response = model.invoke([message])- ```-- ??? example "Files API"-- You can also pass in files that are managed through Anthropic's- [Files API](https://platform.claude.com/docs/en/build-with-claude/files):-- ```python- import anthropic- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- client = anthropic.Anthropic()- file = client.beta.files.upload(- file=("image.png", open("/path/to/image.png", "rb"), "image/png"),- )-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- betas=["files-api-2025-04-14"],- )-- message = HumanMessage(- content=[- {"type": "text", "text": "Describe this image."},- {- "type": "image",- "file_id": file.id,- },- ]- )- response = model.invoke([message])- ```-- ???+ example "PDF input"-- See the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#multimodal)- for more detail.-- ??? example "URL"-- ```python- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- message = HumanMessage(- content=[- {"type": "text", "text": "Summarize this document."},- {- "type": "file",- "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",- "mime_type": "application/pdf",- },- ]- )- response = model.invoke([message])- ```-- ??? example "Base64 encoded"-- ```python- import base64- import httpx- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- pdf_url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"- pdf_data = base64.b64encode(httpx.get(pdf_url).content).decode("utf-8")-- message = HumanMessage(- content=[- {"type": "text", "text": "Summarize this document."},- {- "type": "file",- "base64": pdf_data,- "mime_type": "application/pdf",- },- ]- )- response = model.invoke([message])- ```-- ??? example "Files API"-- You can also pass in files that are managed through Anthropic's- [Files API](https://platform.claude.com/docs/en/build-with-claude/files):-- ```python- import anthropic- from langchain_anthropic import ChatAnthropic- from langchain_core.messages import HumanMessage-- client = anthropic.Anthropic()- file = client.beta.files.upload(- file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),- )-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- betas=["files-api-2025-04-14"],- )-- message = HumanMessage(- content=[- {"type": "text", "text": "Summarize this document."},- {- "type": "file",- "file_id": file.id,- },- ]- )- response = model.invoke([message])- ```-- ???+ example "Extended thinking"-- Certain [Claude models](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#supported-models)- support an [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking)- feature, which will output the step-by-step reasoning process that led to its- final answer. See the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#extended-thinking)- for more detail.-- !!! warning "Differences in thinking across model versions"-- The Claude Messages API handles thinking differently across Claude Sonnet- 3.7 and Claude 4 models.-- Refer to the [Claude docs](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#differences-in-thinking-across-model-versions)- for more info.-- !!! example-- ```python hl_lines="6"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- max_tokens=5000,- thinking={"type": "enabled", "budget_tokens": 2000},- )-- response = model.invoke("What is the cube root of 50.653?")- response.content- ```-- ```python- [- {- "signature": "...",- "thinking": "To find the cube root of 50.653...",- "type": "thinking",- },- {"text": "The cube root of 50.653 is ...", "type": "text"},- ]- ```-- ???+ example "Effort"-- Certain Claude models support an [effort](https://platform.claude.com/docs/en/build-with-claude/effort)- feature, which will control how many tokens Claude uses when responding. See the- [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#effort)- for more detail.-- !!! example-- ```python hl_lines="6"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-opus-4-5-20251101",- max_tokens=4096,- effort="medium", # Options: "high", "medium", "low"- )-- response = model.invoke("Analyze the trade-offs between microservices and monolithic architectures")- print(response.content)- ```-- ???+ example "Prompt caching"-- Prompt caching reduces processing time and costs for repetitive tasks or prompts- with consistent elements. See the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#prompt-caching)- for more detail.-- ```python hl_lines="16"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- messages = [- {- "role": "system",- "content": [- {- "type": "text",- "text": "Below is some long context:",- },- {- "type": "text",- "text": f"{long_text}",- "cache_control": {"type": "ephemeral"},- },- ],- },- {- "role": "user",- "content": "What's that about?",- },- ]-- response = model.invoke(messages)- response.usage_metadata["input_token_details"]- ```-- ```python- {"cache_read": 0, "cache_creation": 1458}- ```-- Alternatively, you may enable prompt caching at invocation time. You may want to- conditionally cache based on runtime conditions, such as the length of the- context. This is useful for app-level decisions about what to- cache.-- ```python hl_lines="3"- response = model.invoke(- messages,- cache_control={"type": "ephemeral"},- )- ```-- ??? example "Extended caching"-- The cache lifetime is 5 minutes by default. If this is too short, you can- apply one hour caching by setting `ttl` to `'1h'`.-- ```python hl_lines="12"- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- )-- messages = [- {- "role": "user",- "content": [- {- "type": "text",- "text": f"{long_text}",- "cache_control": {"type": "ephemeral", "ttl": "1h"},- },- ],- }- ]-- response = model.invoke(messages)- ```-- Details of cached token counts will be included on the `InputTokenDetails`- of response's `usage_metadata`:-- ```python- response = model.invoke(messages)- response.usage_metadata- ```-- ```python- {- "input_tokens": 1500,- "output_tokens": 200,- "total_tokens": 1700,- "input_token_details": {- "cache_read": 0,- "cache_creation": 1000,- "ephemeral_1h_input_tokens": 750,- "ephemeral_5m_input_tokens": 250,- },- }- ```-- See [Claude documentation](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration-beta)- for detail.-- ???+ example "Response metadata"-- ```python- ai_msg = model.invoke(messages)- ai_msg.response_metadata- ```-- ```python- {- "id": "msg_013xU6FHEGEq76aP4RgFerVT",- "model": "claude-sonnet-4-5-20250929",- "stop_reason": "end_turn",- "stop_sequence": None,- "usage": {"input_tokens": 25, "output_tokens": 11},- }- ```-- ???+ example "Token usage metadata"-- ```python- ai_msg = model.invoke(messages)- ai_msg.usage_metadata- ```-- ```python- {"input_tokens": 25, "output_tokens": 11, "total_tokens": 36}- ```-- Message chunks containing token usage will be included during streaming by- default:-- ```python- stream = model.stream(messages)- full = next(stream)- for chunk in stream:- full += chunk- full.usage_metadata- ```-- ```python- {"input_tokens": 25, "output_tokens": 11, "total_tokens": 36}- ```-- These can be disabled by setting [`stream_usage=False`][langchain_anthropic.chat_models.ChatAnthropic.stream_usage]- in the stream method or when initializing `ChatAnthropic`.-- ???+ example "Citations"-- Anthropic supports a [citations](https://platform.claude.com/docs/en/build-with-claude/citations)- feature that lets Claude attach context to its answers based on source- documents supplied by the user.-- When passing a [Claude document content block](https://platform.claude.com/docs/en/build-with-claude/citations#document-types)- with `#!json "citations": {"enabled": True}` included in the query, Claude may- generate citations in its response.-- See the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#citations)- for more detail.-- ```python hl_lines="9-19"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-3-5-haiku-20241022")-- messages = [- {- "role": "user",- "content": [- {- "type": "document",- "source": {- "type": "text",- "media_type": "text/plain",- "data": "The grass is green. The sky is blue.",- },- "title": "My Document",- "context": "This is a trustworthy document.",- "citations": {"enabled": True},- },- {"type": "text", "text": "What color is the grass and sky?"},- ],- }- ]-- response = model.invoke(messages)- response.content- ```-- ```python hl_lines="6-15 21-30"- [- {"text": "Based on the document, ", "type": "text"},- {- "text": "the grass is green",- "type": "text",- "citations": [- {- "type": "char_location",- "cited_text": "The grass is green. ",- "document_index": 0,- "document_title": "My Document",- "start_char_index": 0,- "end_char_index": 20,- }- ],- },- {"text": ", and ", "type": "text"},- {- "text": "the sky is blue",- "type": "text",- "citations": [- {- "type": "char_location",- "cited_text": "The sky is blue.",- "document_index": 0,- "document_title": "My Document",- "start_char_index": 20,- "end_char_index": 36,- }- ],- },- {"text": ".", "type": "text"},- ]- ```-- ???+ example "Context management"-- Anthropic supports a context editing feature that will automatically manage the- model's context window (e.g., by clearing tool results). See the- [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#context-management)- for more detail.-- ```python hl_lines="5-6"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- betas=["context-management-2025-06-27"],- context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},- )- model_with_tools = model.bind_tools([{"type": "web_search_20250305", "name": "web_search"}])- response = model_with_tools.invoke("Search for recent developments in AI")- ```-- ???+ example "Extended context window"-- Claude Sonnet 4 supports a 1-million token context window, available in beta for- organizations in usage tier 4 and organizations with custom rate limits. See- the [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#extended-context-window)- for more detail.-- ```python hl_lines="5"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- betas=["context-1m-2025-08-07"], # Enable 1M context beta- )-- long_document = \"\"\"- This is a very long document that would benefit from the extended 1M- context window...- [imagine this continues for hundreds of thousands of tokens]- \"\"\"-- messages = [- HumanMessage(f\"\"\"- Please analyze this document and provide a summary:-- {long_document}-- What are the key themes and main conclusions?- \"\"\")- ]-- response = model.invoke(messages)- ```-- ???+ example "Structured output"-- See [`ChatAnthropic.with_structured_output()`][langchain_anthropic.chat_models.ChatAnthropic.with_structured_output]- for more info, including strict output validation.-- ```python hl_lines="12"- from pydantic import BaseModel, Field--- class Joke(BaseModel):- '''Joke to tell user.'''-- setup: str = Field(description="The setup of the joke")- punchline: str = Field(description="The punchline to the joke")- rating: int | None = Field(description="How funny the joke is, from 1 to 10")--- structured_model = model.with_structured_output(Joke)- structured_model.invoke("Tell me a joke about cats")- ```-- ```python- Joke(- setup="Why was the cat sitting on the computer?",- punchline="To keep an eye on the mouse!",- rating=None,- )- ```-- ???+ example "Built-in tools"-- See LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#built-in-tools)- for more detail.-- ??? example "Bash tool"-- Claude supports a [bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool)- that allows it to execute shell commands in a persistent bash session. See- the LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#bash-tool)- for more detail.-- ```python- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- bash_tool = {- "type": "bash_20250124",- "name": "bash",- }-- model_with_bash = model.bind_tools([bash_tool])- response = model_with_bash.invoke("List all Python files in the current directory")- ```-- ??? example "Code execution"-- Claude supports a [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool)- that allows it to execute code snippets in a secure, sandboxed environment. See the- LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#code-execution)- for more detail.-- ```python hl_lines="3-6"- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- tool = {- "type": "code_execution_20250522",- "name": "code_execution",- }- model_with_tools = model.bind_tools([tool])-- response = model_with_tools.invoke(- "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"- )- ```-- !!! note "Automatic beta header"-- The required `code-execution-2025-05-22` or `code-execution-2025-08-25`- beta header is automatically appended to the request when using the- `code_execution_20250522` or `code_execution_20250825` tool type,- respectively. You don't need to manually specify it in the `betas`- parameter.-- ??? example "Computer use"-- Claude supports [computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool)- capabilities, allowing it to interact with desktop environments through- screenshots, mouse control, and keyboard input. See the LangChain- [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#computer-use)- for more detail.-- ```python- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- computer_tool = {- "type": "computer_20250124",- "name": "computer",- "display_width_px": 1024,- "display_height_px": 768,- "display_number": 1,- }-- model_with_computer = model.bind_tools([computer_tool])- response = model_with_computer.invoke("Take a screenshot to see what's on the screen")-- # response.tool_calls contains the action Claude wants to perform- # You must execute this action in your environment and pass the result back- ```-- !!! note "Automatic beta header"-- The required beta header is automatically appended based on the tool- version. For `computer_20250124` and `computer_20251124`, the respective- `computer-use-2025-01-24` and `computer-use-2025-11-24` beta header is- added automatically.-- ??? example "Remote MCP"-- Claude can use a [MCP connector tool](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector)- for model-generated calls to remote MCP servers. See the LangChain- [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#remote-mcp)- for more detail.-- ```python hl_lines="3-20 24 29"- from langchain_anthropic import ChatAnthropic-- mcp_servers = [- {- "type": "url",- "url": "https://docs.langchain.com/mcp",- "name": "LangChain Docs",- # "authorization_token": "PLACEHOLDER", # optional authorization- }- ]-- # Optional: configure which tools are enabled via mcp_toolset- tools = [- {- "type": "mcp_toolset",- "mcp_server_name": "LangChain Docs",- # "default_config": {"enabled": False}, # disable all by default- # "configs": {"ask_question": {"enabled": True}}, # allowlist- }- ]-- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- mcp_servers=mcp_servers,- )-- response = model.invoke(- "What are LangChain content blocks?",- tools=tools,- )- ```-- !!! note "Automatic beta header"-- The required `mcp-client-2025-11-20` beta header is automatically- appended to the request when using `mcp_servers`. You don't need to- manually specify it in the `betas` parameter.-- ??? example "Text editor"-- Claude supports a [text editor tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool)- that allows it to read and modify files in a code repository. See the- LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#text-editor)- for more detail.-- ```python hl_lines="5-8"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- tool = {- "type": "text_editor_20250124",- "name": "str_replace_editor",- }- model_with_tools = model.bind_tools([tool])-- response = model_with_tools.invoke(- "There's a syntax error in my primes.py file. Can you help me fix it?"- )- print(response.text)- response.tool_calls- ```-- ```txt- I'd be happy to help you fix the syntax error in your primes.py file. First, let's look at the current content of the file to identify the error.- ```-- ```txt- [{'name': 'str_replace_editor',- 'args': {'command': 'view', 'path': '/repo/primes.py'},- 'id': 'toolu_01VdNgt1YV7kGfj9LFLm6HyQ',- 'type': 'tool_call'}]- ```-- ??? example "Web fetch"-- Claude can use a [web fetching tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool)- to retrieve full content from specified web pages and PDF documents and- ground its responses with citations. See the LangChain- [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#web-fetch)- for more detail.-- ```python hl_lines="5-9"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-haiku-4-5-20251001")-- tool = {- "type": "web_fetch_20250910",- "name": "web_fetch",- "max_uses": 3,- }- model_with_tools = model.bind_tools([tool])-- response = model_with_tools.invoke("Please analyze the content at https://docs.langchain.com/")- ```-- !!! note "Automatic beta header"-- The required `web-fetch-2025-09-10` beta header is automatically- appended to the request when using the `web_fetch_20250910` tool type.- You don't need to manually specify it in the `betas` parameter.-- ??? example "Web search"-- Claude can use a [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool)- to run searches and ground its responses with citations. See the LangChain- [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#web-search)- for more detail.-- ```python hl_lines="5-9"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- tool = {- "type": "web_search_20250305",- "name": "web_search",- "max_uses": 3,- }- model_with_tools = model.bind_tools([tool])-- response = model_with_tools.invoke("How do I update a web app to TypeScript 5.5?")- ```-- ??? example "Memory tool"-- ```python hl_lines="5-8"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")+ See the [LangChain docs for `ChatAnthropic`](https://docs.langchain.com/oss/python/integrations/chat/anthropic)+ for tutorials, feature walkthroughs, and examples.- tool = {- "type": "memory_20250818",- "name": "memory",- }- model_with_tools = model.bind_tools([tool])-- response = model_with_tools.invoke("What are my interests?")- ```-- !!! note "Automatic beta header"-- The required `context-management-2025-06-27` beta header is automatically- appended to the request when using the `memory_20250818` tool type.- You don't need to manually specify it in the `betas` parameter.-- See the [Claude docs](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool)- for more info.-- ??? example "Tool search"-- Tool search enables Claude to dynamically discover and load tools on-demand- instead of loading all tool definitions upfront. Use the `extras` parameter to- specify `defer_loading` on LangChain tools.-- See the- [LangChain docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#tool-search)- for more detail.-- ```python hl_lines="4 10"- from langchain_anthropic import ChatAnthropic- from langchain_core.tools import tool-- @tool(extras={"defer_loading": True})- def get_weather(location: str, unit: str = "fahrenheit") -> str:- \"\"\"Get the current weather for a location.\"\"\"- return f"Weather in {location}: Sunny, 72°{unit[0].upper()}"-- @tool(extras={"defer_loading": True})- def search_files(query: str) -> str:- \"\"\"Search through files in the workspace.\"\"\"- return f"Found 3 files matching '{query}'"-- model = ChatAnthropic(model="claude-sonnet-4-5-20250929")-- model_with_tools = model.bind_tools([- {- "type": "tool_search_tool_regex_20251119",- "name": "tool_search_tool_regex",- },- get_weather,- search_files,- ])-- response = model_with_tools.invoke("What's the weather in San Francisco?")- ```-- !!! note "Automatic beta header"+ See the [Claude Platform docs](https://platform.claude.com/docs/en/about-claude/models/overview)+ for a list of the latest models, their capabilities, and pricing.- The required `advanced-tool-use-2025-11-20` beta header is automatically- appended to the request when using tool search tools.+ Example:+ ```python+ # pip install -U langchain-anthropic+ # export ANTHROPIC_API_KEY="your-api-key"- !!! tip "Best practices"+ from langchain_anthropic import ChatAnthropic- - Tools with `defer_loading: True` are only loaded when Claude discovers them via search- - Keep your 3-5 most frequently used tools as non-deferred for optimal performance- - Both variants search tool names, descriptions, argument names, and argument descriptions+ model = ChatAnthropic(+ model="claude-sonnet-4-5-20250929",+ # temperature=,+ # max_tokens=,+ # timeout=,+ # max_retries=,+ # base_url="...",+ # Refer to API reference for full list of parameters+ )+ ```- See the [Claude docs](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool)- for more info.- """ # noqa: E501+ Note:+ Any param which is not explicitly supported will be passed directly to+ [`Anthropic.messages.create(...)`](https://platform.claude.com/docs/en/api/python/messages/create)+ each time to the model is invoked.+ """model_config = ConfigDict(populate_by_name=True,@@ -2512,7 +1395,7 @@ class ChatAnthropic(BaseChatModel):See the [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#strict-tool-use) for more info.kwargs: Any additional parameters are passed directly to `bind`.- ???+ example+ Example:```pythonfrom langchain_anthropic import ChatAnthropicfrom pydantic import BaseModel, Field@@ -2544,220 +1427,6 @@ class ChatAnthropic(BaseChatModel):# id='run-87b1331e-9251-4a68-acef-f0a018b639cc-0'# )```-- ??? example "Force tool call with tool_choice `'any'`"-- ```python- from langchain_anthropic import ChatAnthropic- from pydantic import BaseModel, Field--- class GetWeather(BaseModel):- '''Get the current weather in a given location'''-- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")--- class GetPrice(BaseModel):- '''Get the price of a specific product.'''-- product: str = Field(..., description="The product to look up.")--- model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)- model_with_tools = model.bind_tools([GetWeather, GetPrice], tool_choice="any")- model_with_tools.invoke(- "what is the weather like in San Francisco",- )- ```-- ??? example "Force specific tool call with `tool_choice` `'<name_of_tool>'`"-- ```python- from langchain_anthropic import ChatAnthropic- from pydantic import BaseModel, Field--- class GetWeather(BaseModel):- '''Get the current weather in a given location'''-- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")--- class GetPrice(BaseModel):- '''Get the price of a specific product.'''-- product: str = Field(..., description="The product to look up.")--- model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)- model_with_tools = model.bind_tools([GetWeather, GetPrice], tool_choice="GetWeather")- model_with_tools.invoke("What is the weather like in San Francisco")- ```-- ??? example "Cache specific tools"-- ```python- from langchain_anthropic import ChatAnthropic, convert_to_anthropic_tool- from pydantic import BaseModel, Field--- class GetWeather(BaseModel):- '''Get the current weather in a given location'''-- location: str = Field(..., description="The city and state, e.g. San Francisco, CA")--- class GetPrice(BaseModel):- '''Get the price of a specific product.'''-- product: str = Field(..., description="The product to look up.")--- # We'll convert our pydantic class to the anthropic tool format- # before passing to bind_tools so that we can set the 'cache_control'- # field on our tool.- cached_price_tool = convert_to_anthropic_tool(GetPrice)-- # Currently the only supported "cache_control" value is {"type": "ephemeral"}- cached_price_tool["cache_control"] = {"type": "ephemeral"}-- # Need to pass in extra headers to enable use of the beta cache control API.- model = ChatAnthropic(- model="claude-sonnet-4-5-20250929",- temperature=0,- )- model_with_tools = model.bind_tools([GetWeather, cached_price_tool])- model_with_tools.invoke("What is the weather like in San Francisco")- ```-- This outputs:-- ```python- AIMessage(- content=[- {- "text": "Certainly! I can help you find out the current weather in San Francisco. To get this information, I'll use the GetWeather function. Let me fetch that data for you right away.",- "type": "text",- },- {- "id": "toolu_01TS5h8LNo7p5imcG7yRiaUM",- "input": {"location": "San Francisco, CA"},- "name": "GetWeather",- "type": "tool_use",- },- ],- response_metadata={- "id": "msg_01Xg7Wr5inFWgBxE5jH9rpRo",- "model": "claude-sonnet-4-5-20250929",- "stop_reason": "tool_use",- "stop_sequence": None,- "usage": {- "input_tokens": 171,- "output_tokens": 96,- "cache_creation_input_tokens": 1470,- "cache_read_input_tokens": 0,- },- },- id="run-b36a5b54-5d69-470e-a1b0-b932d00b089e-0",- tool_calls=[- {- "name": "GetWeather",- "args": {"location": "San Francisco, CA"},- "id": "toolu_01TS5h8LNo7p5imcG7yRiaUM",- "type": "tool_call",- }- ],- usage_metadata={- "input_tokens": 171,- "output_tokens": 96,- "total_tokens": 267,- },- )- ```-- If we invoke the tool again, we can see that the "usage" information in the `AIMessage.response_metadata` shows that we had a cache hit:-- ```python hl_lines="23"- AIMessage(- content=[- {- "text": "To get the current weather in San Francisco, I can use the GetWeather function. Let me check that for you.",- "type": "text",- },- {- "id": "toolu_01HtVtY1qhMFdPprx42qU2eA",- "input": {"location": "San Francisco, CA"},- "name": "GetWeather",- "type": "tool_use",- },- ],- response_metadata={- "id": "msg_016RfWHrRvW6DAGCdwB6Ac64",- "model": "claude-sonnet-4-5-20250929",- "stop_reason": "tool_use",- "stop_sequence": None,- "usage": {- "input_tokens": 171,- "output_tokens": 82,- "cache_creation_input_tokens": 0,- "cache_read_input_tokens": 1470,- },- },- id="run-88b1f825-dcb7-4277-ac27-53df55d22001-0",- tool_calls=[- {- "name": "GetWeather",- "args": {"location": "San Francisco, CA"},- "id": "toolu_01HtVtY1qhMFdPprx42qU2eA",- "type": "tool_call",- }- ],- usage_metadata={- "input_tokens": 171,- "output_tokens": 82,- "total_tokens": 253,- },- )- ```-- ??? example "Strict tool use"-- Strict tool use guarantees that tool names and arguments are validated- and correctly typed.-- !!! note-- Strict tool use requires:-- - Claude Sonnet 4.5 or Opus 4.1- - `langchain-anthropic>=1.1.0`-- To enable strict tool use, specify `strict=True` when calling- [`bind_tools`][langchain_anthropic.chat_models.ChatAnthropic.bind_tools].-- ```python hl_lines="11"- from langchain_anthropic import ChatAnthropic-- model = ChatAnthropic(- model="claude-sonnet-4-5",- )-- def get_weather(location: str) -> str:- \"\"\"Get the weather at a location.\"\"\"- return "It's sunny."-- model_with_tools = model.bind_tools([get_weather], strict=True)- ```-- !!! note "Automatic beta header"-- The required `structured-outputs-2025-11-13` beta header is- automatically appended to the request when using `strict=True`, so you- don't need to manually specify it in the `betas` parameter.-- See LangChain [docs](https://docs.langchain.com/oss/python/integrations/chat/anthropic#strict-tool-use)- for more detail.""" # noqa: E501# Allows built-in tools either by their:# - Raw `dict` format@@ -2867,22 +1536,7 @@ class ChatAnthropic(BaseChatModel):depends on the `schema` as described above.- `'parsing_error'`: `BaseException | None`- ???+ example "Native structured output with `method='json_schema'`"-- Anthropic supports a native structured output feature that guarantees- responses adhere to a given schema.-- !!! note-- Native structured output requires:-- - Claude Sonnet 4.5 or Opus 4.1- - `langchain-anthropic>=1.1.0`-- To enable native structured output, specify `method="json_schema"` when- calling `with_structured_output`. (Under the hood, LangChain will- append the required `structured-outputs-2025-11-13` beta header)-+ Example:```python hl_lines="13"from langchain_anthropic import ChatAnthropicfrom pydantic import BaseModel, Field@@ -2901,82 +1555,6 @@ class ChatAnthropic(BaseChatModel):print(response)# -> Movie(title="Inception", year=2010, director="Christopher Nolan", rating=8.8)```-- ??? example "Pydantic schema (`include_raw=False`)"-- ```python- from langchain_anthropic import ChatAnthropic- from pydantic import BaseModel--- class AnswerWithJustification(BaseModel):- '''An answer to the user question along with justification for the answer.'''-- answer: str- justification: str--- model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)- structured_model = model.with_structured_output(AnswerWithJustification)-- structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")- # -> AnswerWithJustification(- # answer='They weigh the same',- # justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'- # )- ```-- ??? example "Pydantic schema (`include_raw=True`)"-- ```python- from langchain_anthropic import ChatAnthropic- from pydantic import BaseModel--- class AnswerWithJustification(BaseModel):- '''An answer to the user question along with justification for the answer.'''-- answer: str- justification: str--- model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)- structured_model = model.with_structured_output(AnswerWithJustification, include_raw=True)-- structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")- # -> {- # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),- # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),- # 'parsing_error': None- # }- ```-- ??? example "Dictionary schema (`include_raw=False`)"-- ```python- from langchain_anthropic import ChatAnthropic-- schema = {- "name": "AnswerWithJustification",- "description": "An answer to the user question along with justification for the answer.",- "input_schema": {- "type": "object",- "properties": {- "answer": {"type": "string"},- "justification": {"type": "string"},- },- "required": ["answer", "justification"],- },- }- model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)- structured_model = model.with_structured_output(schema)-- structured_model.invoke("What weighs more a pound of bricks or a pound of feathers")- # -> {- # 'answer': 'They weigh the same',- # 'justification': 'Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume and density of the two substances differ.'- # }- ```""" # noqa: E501if method == "json_mode":warning_message = (