如何反序列化LangChain中经toJSON序列化后的BaseMessage列表?
解决LangChain BaseMessage序列化后的反序列化问题
在LangChain JavaScript中,要反序列化通过toJSON()得到的消息数据,有两种实用方法:
方式一:调用消息类的静态fromJSON方法
HumanMessage、AIMessage等消息类型都自带静态的fromJSON方法,可直接传入序列化后的对象还原实例:
import { HumanMessage, AIMessage } from "langchain/schema"; const messages = [ new HumanMessage("hello"), new AIMessage("foo"), new HumanMessage("bar"), new AIMessage("baz"), ]; const serialized = messages.map((message) => message.toJSON()); // 反序列化逻辑 const deserialized = serialized.map(msg => { switch(msg.type) { case "human": return HumanMessage.fromJSON(msg); case "ai": return AIMessage.fromJSON(msg); // 如需支持其他消息类型(如SystemMessage、FunctionMessage),添加对应case即可 default: throw new Error(`未知消息类型: ${msg.type}`); } });
方式二:使用LangChain内置的messageFromJSON工具函数
LangChain提供了messageFromJSON函数,它会自动根据序列化数据中的type字段匹配对应消息类,无需手动判断类型:
import { HumanMessage, AIMessage, messageFromJSON } from "langchain/schema"; const messages = [ new HumanMessage("hello"), new AIMessage("foo"), new HumanMessage("bar"), new AIMessage("baz"), ]; const serialized = messages.map((message) => message.toJSON()); // 反序列化逻辑 const deserialized = serialized.map(msg => messageFromJSON(msg));
注意事项
- 序列化后的
Serialized对象必须包含type字段,这是LangChain消息类序列化时自动生成的标识,反序列化时依赖它识别消息类型。 - 若自定义了消息子类,需确保子类实现
fromJSON静态方法,或在messageFromJSON中注册对应的类型映射。
内容的提问来源于stack exchange,提问作者Magnar Myrtveit
相关产品推荐
相关产品推荐

