Converting HumanMessage and AIMessage to Strings in LangChain
LangChain usually represents messages as it’s own message types like HumanMessage, AIMessage, SystemMessage, etc
Sometime, you might want to convert it into plan string which you can do it using get_buffer_string
Here is how to do it
Python
from langchain_core import AIMessage, HumanMessage
from langchain_core.messages.utils import get_buffer_string
messages = [
HumanMessage(content="Hi, how are you?"),
AIMessage(content="Good, how are you?"),
]
messages_string = get_buffer_string(messages)
# Output: "Human: Hi, how are you?\n\nAI: Good, how are you?"
Javascript / Typescript
import { AIMessage, HumanMessage } from '@langchain/core/messages';
import { getBufferString } from '@langchain/core/messages';
const messages = [
new HumanMessage(message.content),
new AIMessage(message.content)
];
const messagesAsString = getBufferString(messages)
Happy converting strings!