(msg) ValueError: Invalid input type <class 'dict'>. Must be a PromptValue, str,...
🚨 错误信息
Traceback (most recent call last):
File "D:\新建文件夹\langchain-base\Chatbot.py", line 43, in <module>
response = chain.invoke({"messages":[HumanMessage(content="Hello, I'm Niki")]})
File "D:\software\Python\Lib\site-packages\langchain_core\runnables\base.py", line 3243, in invoke
input_ = context.run(step.invoke, input_, config, **kwargs)
File "D:\software\Python\Lib\site-packages\langchain_core\language_models\chat_models.py", line 396, in invoke
[self._convert_input(input)],
~~~~~~~~~~~~~~~~~~~^^^^^^^
File "D:\software\Python\Lib\site-packages\langchain_core\language_models\chat_models.py", line 381, in _convert_input
raise ValueError(msg)
ValueError: Invalid input type <class 'dict'>. Must be a PromptValue, str, or list of BaseMessages.
🤖 AI解决方案
ValueError: Invalid input type . Must be a PromptValue, str, or list of BaseMessages.
无效的输入类型 。必须是 PromptValue、str 或 BaseMessages 的列表。
原因分析:chain.invoke 方法期望接收 PromptValue、str 或 BaseMessages 的列表作为输入,但你传入了一个字典 ({"messages": [...]})。
解决方案:
将字典结构调整为 Langchain 期望的 BaseMessages 列表,或者直接将列表作为 invoke 方法的参数。
python
from langchain_core.messages import HumanMessage方式一:直接传递 BaseMessages 列表
response = chain.invoke([HumanMessage(content="Hello, I'm Niki")])方式二:如果你的 chain 确实需要字典结构,请确保字典内的值是 Langchain 认识的类型
假设你的 chain 是 ChatPromptTemplate + ChatModel 组成的
from langchain_core.prompts import ChatPromptTemplateprompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("human", "{user_message}")
])
这里的 prompt.invoke 期望一个字典,其中 'user_message' 是一个占位符
response = chain.invoke({"user_message": "Hello, I'm Niki"})注意:你原始代码中的 chain.invoke({"messages":[HumanMessage(content="Hello, I'm Niki")]})
这种结构通常是由 Langchain 的 ChatPromptTemplate 内部处理的,
但直接传递给 chain.invoke 时,如果 chain 的输入类型不是精心设计的,可能会出现问题。
最直接的修改是如方式一所示,传递 BaseMessages 列表。
预防措施:
invoke 或 stream 方法时,仔细阅读相关组件(如 ChatPromptTemplate, RunnableSequence 等)的文档,了解其期望的输入类型。invoke 方法前,打印出将要传递的输入,以确认其类型和结构是否正确。