0
0
LangchainHow-ToBeginner ยท 3 min read

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 AIMessage with user messages; use HumanMessage for user inputs.
  • Not importing AIMessage from langchain.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

TermDescription
AIMessageRepresents a message from the AI with text content.
HumanMessageRepresents a message from the user/human.
contentThe text string inside the message.
langchain.schemaModule 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.