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.
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_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)