serializationdeserializationjson-deserializationlangchainlangchain-js

Deserializing LangChain messages


LangChain's BaseMessage has a function toJSON that returns a Serialized.

Once I have a list of BaseMessages, I can use toJSON to serialize them, but how can I later deserialize them?

const messages = [
  new HumanMessage("hello"),
  new AIMessage("foo"),
  new HumanMessage("bar"),
  new AIMessage("baz"),
];

const serialized = messages.map((message) => message.toJSON());

const deserialized = ???

Solution

  • Finally found the solution :)

    import { AIMessage, HumanMessage, mapChatMessagesToStoredMessages, mapStoredMessagesToChatMessages } from "@langchain/core/messages";
    
    
    const messages = [
      new HumanMessage("hello"),
      new AIMessage("foo"),
      new HumanMessage("bar"),
      new AIMessage("baz"),
    ];
    
    const serialized = mapChatMessagesToStoredMessages(messages);
    const deserialized = mapStoredMessagesToChatMessages(serialized);