How to Use ChatAnthropic with Langchain: Simple Guide
To use
ChatAnthropic in Langchain, import it from langchain.chat_models and create an instance with your API key. Then call its generate method with a list of messages to get a chat response.Syntax
The basic syntax to use ChatAnthropic involves importing the class, creating an instance with your API key, and calling the generate method with chat messages.
- Import: Bring in
ChatAnthropicfromlangchain.chat_models. - Instantiate: Provide your Anthropic API key to create the chat model.
- Generate: Pass a list of messages (with roles and content) to get the model's reply.
python
from langchain.chat_models import ChatAnthropic chat = ChatAnthropic(anthropic_api_key="your_api_key") response = chat.generate(messages=[ {"role": "user", "content": "Hello!"} ]) print(response.generations[0].message.content)
Example
This example shows how to send a simple greeting message to ChatAnthropic and print the response text.
python
from langchain.chat_models import ChatAnthropic # Replace with your actual Anthropic API key chat = ChatAnthropic(anthropic_api_key="sk-xxxx") messages = [ {"role": "user", "content": "Hi there! How are you?"} ] response = chat.generate(messages=messages) print(response.generations[0].message.content)
Output
Hello! I'm doing well, thank you for asking. How can I assist you today?
Common Pitfalls
- Not providing a valid
anthropic_api_keywill cause authentication errors. - Messages must be a list of dictionaries with
roleandcontentkeys; otherwise, the call fails. - Using roles other than
user,assistant, orsystemmay lead to unexpected behavior. - Forgetting to access
response.generations[0].message.contentto get the text output.
python
from langchain.chat_models import ChatAnthropic # Wrong: missing API key # chat = ChatAnthropic() # Wrong: messages not a list # response = chat.generate(messages={"role": "user", "content": "Hello"}) # Right way: chat = ChatAnthropic(anthropic_api_key="sk-xxxx") response = chat.generate(messages=[{"role": "user", "content": "Hello"}]) print(response.generations[0].message.content)
Output
Hello! How can I help you today?
Quick Reference
| Concept | Description |
|---|---|
| ChatAnthropic | Class to interact with Anthropic chat models in Langchain |
| anthropic_api_key | Your secret API key to authenticate requests |
| messages | List of dicts with roles ('user', 'assistant', 'system') and content strings |
| generate() | Method to send messages and get chat completions |
| response.generations[0].message.content | Access the text reply from the model |
Key Takeaways
Always provide your Anthropic API key when creating ChatAnthropic instance.
Pass messages as a list of dictionaries with 'role' and 'content' keys.
Use the generate() method to get chat responses from the model.
Access the reply text via response.generations[0].message.content.
Avoid invalid roles and incorrect message formats to prevent errors.