You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Chain添加Memory时触发TypeError:Member对象无法序列化

问题

开发的基于Discord的AI应答机器人,on_message事件中的AI回复功能原本正常运行,未添加Memory时代码无问题。但为Chain集成Memory后,出现错误:TypeError: Object of type Member is not serializable。相关代码如下:

class WhiteTiger(discord.Client):
    def __init__(self, intents):
        super().__init__(intents=intents)
        self.target_channel = None
        self.llm = ChatOllama(
            model="llama3.2",
            temperature=0,
        )
        self.prompt = ChatPromptTemplate.from_messages(
            [
                (
                    "system",
                    "<context>",
                ),
                MessagesPlaceholder(variable_name="messages"),
            ]
        )
        self.chain = self.prompt | self.llm

        self.init_memory()

    def init_memory(self):
        workflow = StateGraph(state_schema=DiscordMessagesState)

        def call_model(state: DiscordMessagesState):
            response = self.chain.invoke(state)
            return {"messages": [response]}

        workflow.add_edge(START, "model")
        workflow.add_node("model", call_model)

        self.memory = MemorySaver()
        self.app = workflow.compile(checkpointer=self.memory)
        self.config = {"configurable": {"thread_id": "abc1234"}}


    async def on_message(self, message):
        if (
            self.target_channel
            and message.channel.id == self.target_channel.id
            and message.author.id != self.user.id
        ):
            print(f"Message from {message.author}: {message.content}")

            print(f"{message.author}: {message.content}")

            reply = self.app.invoke(
                {
                    "messages": [HumanMessage(f"{message.author}: {message.content}")],
                    "author": message.author,
                },
                self.config
            )

            await message.reply(
                reply["messages"][-1].pretty_print(), mention_author=True
            )
解决方案

问题原因

报错核心是:MemorySaver需要序列化整个工作流状态(state),但传入的message.author是Discord的Member对象,该对象无法被JSON序列化,因此触发类型错误。

修复步骤

  1. 移除不可序列化的Member对象:如果不需要单独存储用户对象,直接删除state中的"author": message.author字段——因为你已经在HumanMessage里包含了用户标识({message.author}: {message.content}),无需重复传入。

  2. 若需存储用户信息,改用可序列化数据:如果业务需要保留用户相关信息,不要直接传Member对象,改用其可序列化的属性,比如用户ID(整数)、用户名(字符串):
    修改on_message中的app.invoke参数:

    reply = self.app.invoke(
        {
            "messages": [HumanMessage(f"{message.author}: {message.content}")],
            "author_id": message.author.id,
            "author_name": message.author.name
        },
        self.config
    )
    
  3. 同步修改状态 schema:如果你的DiscordMessagesState中定义了author字段,需要将其类型改为int或str,对应上面的author_id或author_name,确保状态结构可被序列化。

修改后的关键代码示例

async def on_message(self, message):
    if (
        self.target_channel
        and message.channel.id == self.target_channel.id
        and message.author.id != self.user.id
    ):
        print(f"Message from {message.author}: {message.content}")

        print(f"{message.author}: {message.content}")

        # 移除或替换不可序列化的author字段
        reply = self.app.invoke(
            {
                "messages": [HumanMessage(f"{message.author}: {message.content}")]
                # 若需用户信息则添加:
                # "author_id": message.author.id,
                # "author_name": message.author.name
            },
            self.config
        )

        await message.reply(
            reply["messages"][-1].pretty_print(), mention_author=True
        )

内容的提问来源于stack exchange,提问作者thecodingsage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:22:46