LangChain Anthropic
LangChain Anthropic is an integration package that connects Anthropic's generative AI models (like Claude) with the LangChain framework. It allows developers to easily incorporate Anthropic's powerful chat models and (legacy) text completion models into their LangChain-based applications. As part of the broader LangChain ecosystem, it follows a frequent release cadence, often aligning with updates to `langchain-core` and the main `langchain` library. The current version is 1.4.0.
Common errors
-
anthropic.AuthenticationError: Invalid x-api-key.
cause The Anthropic API key is either missing, incorrectly formatted, or invalid, preventing successful authentication with the Anthropic API.fixSet the `ANTHROPIC_API_KEY` environment variable with your valid Anthropic API key (e.g., `os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."`) or pass it directly when initializing `ChatAnthropic` (e.g., `llm = ChatAnthropic(api_key="sk-ant-...")`). -
ModuleNotFoundError: No module named 'langchain.llms' or ImportError: cannot import name 'AnthropicLLM'
cause The import path for Anthropic models has changed with the modularization of LangChain, or the `langchain-anthropic` package is not installed.fixEnsure you have installed the `langchain-anthropic` package (`pip install -U langchain-anthropic`) and use the correct import path: `from langchain_anthropic import ChatAnthropic`. -
anthropic.RateLimitError: Number of concurrent connections has exceeded your rate limit.
cause Too many requests are being sent to the Anthropic API within a short period, exceeding the rate limits imposed by Anthropic for your account.fixImplement retry logic with exponential backoff using `tenacity`, or leverage LangChain's built-in rate limiting features. Consider requesting a rate limit increase from Anthropic if necessary. -
anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages: Unexpected role "ai". Allowed roles are "user" or "assistant"'}}cause The message list sent to the Anthropic API includes a message with an unsupported role (e.g., 'ai' when Anthropic expects 'assistant') or an incorrectly ordered system message.fixEnsure that `SystemMessage` is the first message in the list, and other roles are correctly mapped to 'user' (`HumanMessage`) or 'assistant' (`AIMessage`) as expected by the Anthropic API, or construct messages carefully following Anthropic's message API format. -
anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'This model does not support assistant message prefill. The conversation must end with a user message.'}}cause Certain newer Anthropic models (e.g., Claude Opus) do not support starting a new turn with an `AIMessage` (assistant message prefill). If the message history passed to `ChatAnthropic` ends with an AI message, it will cause this error.fixEnsure that the final message in the input list to `ChatAnthropic.invoke()` is always a `HumanMessage`, or explicitly manage the conversation history to avoid ending with an AI message for models that don't support prefill.
Warnings
- deprecated The `AnthropicLLM` class for text completion models is considered legacy. For modern Anthropic models like Claude 3, it's strongly recommended to use `ChatAnthropic` instead, which supports the chat-based API.
- breaking The default value for the `max_tokens` parameter in `langchain-anthropic` changed with LangChain v1. Previously, it defaulted to 1024. Now, it defaults to higher values based on the specific model's `max_output_tokens` profile. If your application relied on the old default, it might now consume more tokens or exhibit different truncation behavior.
- gotcha It is crucial to set the `ANTHROPIC_API_KEY` environment variable for authentication. Without it, your application will fail when trying to connect to Anthropic models.
- breaking LangChain v1 introduced significant architectural changes, including a simplified `langchain` package namespace, revised import paths, and new patterns for agents and tools. Code written for `langchain==0.x` might require substantial modifications.
- gotcha When using built-in Anthropic tools like the 'web fetch' tool, be aware of security implications. Enabling web fetching in environments where Claude processes untrusted input alongside sensitive data can pose data exfiltration risks.
Install
-
pip install langchain-anthropic
Imports
- ChatAnthropic
from langchain_anthropic import ChatAnthropic
- AnthropicLLM
from langchain.llms import Anthropic
from langchain_anthropic import AnthropicLLM
Quickstart
import os
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
# Set your Anthropic API key as an environment variable
# os.environ["ANTHROPIC_API_KEY"] = "YOUR_ANTHROPIC_API_KEY"
# Ensure the API key is set
if not os.environ.get("ANTHROPIC_API_KEY"):
raise ValueError("ANTHROPIC_API_KEY environment variable not set.")
model = ChatAnthropic(model="claude-3-sonnet-20240229", temperature=0)
messages = [
SystemMessage(content="You are a helpful AI assistant."),
HumanMessage(content="What is the capital of France?"),
]
response = model.invoke(messages)
print(response.content)