How to Use AI Message in LangChain: Simple Guide
In LangChain, use
AIMessage to create messages from the AI in a chat interface. Instantiate AIMessage with the AI's text response, then pass it to your chat or processing logic to handle AI-generated content.Syntax
The AIMessage class represents a message generated by the AI in LangChain's chat framework. You create it by passing the AI's text as a string.
- AIMessage(content: str): Creates an AI message with the given text content.
This message can then be used in chat chains or conversation memory.
python
from langchain.schema import AIMessage ai_message = AIMessage("Hello from AI!")
Example
This example shows how to create an AIMessage and print its content. It demonstrates how to use the AIMessage class to represent AI responses in a chat.
python
from langchain.schema import AIMessage # Create an AI message with some text ai_message = AIMessage("Hello! How can I assist you today?") # Access and print the message content print(ai_message.content)
Output
Hello! How can I assist you today?
Common Pitfalls
Common mistakes when using AIMessage include:
- Passing non-string types as content, which causes errors.
- Confusing
AIMessagewith user messages; useHumanMessagefor user inputs. - Not importing
AIMessagefromlangchain.schema.
Always ensure the content is a string and use the correct message class for AI vs user messages.
python
from langchain.schema import AIMessage, HumanMessage # Wrong: content is not a string (causes error) # ai_message = AIMessage(123) # โ # Correct: content is a string ai_message = AIMessage("This is valid AI text.") # Use HumanMessage for user input user_message = HumanMessage("Hello AI!")
Quick Reference
| Term | Description |
|---|---|
| AIMessage | Represents a message from the AI with text content. |
| HumanMessage | Represents a message from the user/human. |
| content | The text string inside the message. |
| langchain.schema | Module where AIMessage is imported from. |
Key Takeaways
Use AIMessage to represent AI-generated text messages in LangChain chats.
Always pass a string as the content when creating an AIMessage.
Import AIMessage from langchain.schema before using it.
Distinguish AIMessage from HumanMessage to separate AI and user inputs.
AIMessage instances are used to build chat conversations and chains.