基于本地文档的Q&A聊天Bot触发‘Message’对象无replace属性错误求助
问题分析与解决方案
核心问题
你遇到的'Message' object has no attribute 'replace'错误,根源是传入chain.acall()的参数类型错误。@cl.on_message装饰的函数接收到的message是Clarifai的Message对象,而LangChain的acall()方法需要字符串格式的输入内容,直接传入整个Message对象会导致内部处理时调用replace方法失败。
修复步骤
修改代码中调用chain.acall()的部分,将message替换为message.content,同时修正一处拼写错误:
@cl.on_message async def main(message): chain = cl.user_session.get("chain") cb = cl.AsyncLangchainCallbackHandler( stream_final_answer=True, answer_prefix_tokens=["FINAL", "ANSWER"] ) # cb = cl.AsyncLangchainCallbackHandler() cb.answer_reached = True # 修正拼写错误:ansert_reached → answer_reached res = await chain.acall(message.content, callbacks=[cb]) # 关键修改:传入消息内容而非Message对象 print("LangChain response:", res) answer = res["result"] sources = res["source_documents"] if sources: answer += f"\nSources: " + str(str(sources)) else: answer += f"\nNo Sources found" await cl.Message(content=answer).send()
额外提示
如果后续回调逻辑仍有异常,可以先注释掉自定义的CallbackHandler(使用代码中被注释的cb = cl.AsyncLangchainCallbackHandler()),先验证核心问答流程是否正常,再逐步排查回调相关逻辑。
内容的提问来源于stack exchange,提问作者pergau
相关产品推荐
相关产品推荐

