LangChainJS中ZepMemory与ConversationChain的Prompt配置异常问题
问题解决:ZepMemory搭配自定义ConversationChain Prompt时出现
message._getType is not a function错误 问题原因
- 你使用的LangChain 0.0.89版本中,ZepMemory返回的聊天记录是普通对象,并非LangChain内置的
HumanMessage/AIMessage等ChatMessage子类——这些子类才自带_getType方法。 - 不设置自定义prompt时,ConversationChain默认的prompt会自动处理历史消息的格式转换;但自定义prompt使用
MessagesPlaceholder时,会直接传入原始的历史消息对象,导致ChatOpenAI处理时找不到_getType方法报错。
解决方案
手动将ZepMemory获取的历史消息转换为LangChain的标准ChatMessage类型,最优雅的方式是扩展ZepMemory类并重写loadMemoryVariables方法:
const { ZepMemory, HumanMessage, AIMessage } = require("langchain/memory"); const { ChatPromptTemplate, SystemMessagePromptTemplate, MessagesPlaceholder, HumanMessagePromptTemplate } = require("langchain/prompts"); const { ConversationChain } = require("langchain/chains"); const { ChatOpenAI } = require("langchain/chat_models/openai"); // 自定义ZepMemory,自动转换历史消息格式 class CustomZepMemory extends ZepMemory { async loadMemoryVariables(_) { const result = await super.loadMemoryVariables(_); // 将Zep返回的普通消息对象转为LangChain标准ChatMessage const formattedHistory = result.history.map(msg => { if (msg.role === "human") { return new HumanMessage(msg.content); } else if (msg.role === "ai") { return new AIMessage(msg.content); } // 若Zep返回其他角色类型,可在此扩展处理逻辑 return msg; }); return { ...result, history: formattedHistory }; } } // 替换原ZepMemory为自定义版本 const memory = new CustomZepMemory({ sessionId: dynamicSessionId, baseURL: cfg.zepUrl }); const model = new ChatOpenAI({ modelName: 'gpt-3.5-turbo', temperature: 0, openAIApiKey: cfg.openaikey }); const chatPrompt = ChatPromptTemplate.fromPromptMessages([ SystemMessagePromptTemplate.fromTemplate( // 你的系统Prompt内容 "你是专业助手,结合历史对话回答用户问题" ), new MessagesPlaceholder('history'), HumanMessagePromptTemplate.fromTemplate('{input}') ]); const chain = new ConversationChain({ prompt: chatPrompt, memory, llm: model });
注意事项
- 确保Zep返回的消息对象包含
role字段(值为human或ai),若Zep的角色字段名不同,需调整代码中的判断逻辑。 - 若不想扩展类,也可以在获取历史消息后手动转换格式,但重写
loadMemoryVariables能让所有依赖该内存的模块自动使用转换后的标准消息。
内容的提问来源于stack exchange,提问作者Jayy
相关产品推荐
相关产品推荐

