消息强制转换失败
与总是需要BaseMessage
的实例不同,LangChain中的几个模块接受MessageLikeRepresentation
,其定义为:
from typing import Union
from langchain_core.prompts.chat import (
BaseChatPromptTemplate,
BaseMessage,
BaseMessagePromptTemplate,
)
MessageLikeRepresentation = Union[
Union[BaseMessagePromptTemplate, BaseMessage, BaseChatPromptTemplate],
tuple[
Union[str, type],
Union[str, list[dict], list[object]],
],
str,
]
这些包括OpenAI风格的消息对象({ role: "user", content: "Hello world!" }
),
元组,以及纯字符串(这些字符串会被转换为HumanMessages
)。
如果这些模块中的一个接收到这些格式之外的值,您将收到如下错误:
from langchain_anthropic import ChatAnthropic
uncoercible_message = {"role": "HumanMessage", "random_field": "random value"}
model = ChatAnthropic(model="claude-3-5-sonnet-20240620")
model.invoke([uncoercible_message])
API Reference:ChatAnthropic
---------------------------------------------------------------------------
``````output
KeyError Traceback (most recent call last)
``````output
File ~/langchain/oss-py/libs/core/langchain_core/messages/utils.py:318, in _convert_to_message(message)
317 # None msg content is not allowed
--> 318 msg_content = msg_kwargs.pop("content") or ""
319 except KeyError as e:
``````output
KeyError: 'content'
``````output
The above exception was the direct cause of the following exception:
``````output
ValueError Traceback (most recent call last)
``````output
Cell In[5], line 10
3 uncoercible_message = {
4 "role": "HumanMessage",
5 "random_field": "random value"
6 }
8 model = ChatAnthropic(model="claude-3-5-sonnet-20240620")
---> 10 model.invoke([uncoercible_message])
``````output
File ~/langchain/oss-py/libs/core/langchain_core/language_models/chat_models.py:287, in BaseChatModel.invoke(self, input, config, stop, **kwargs)
275 def invoke(
276 self,
277 input: LanguageModelInput,
(...)
281 **kwargs: Any,
282 ) -> BaseMessage:
283 config = ensure_config(config)
284 return cast(
285 ChatGeneration,
286 self.generate_prompt(
--> 287 [self._convert_input(input)],
288 stop=stop,
289 callbacks=config.get("callbacks"),
290 tags=config.get("tags"),
291 metadata=config.get("metadata"),
292 run_name=config.get("run_name"),
293 run_id=config.pop("run_id", None),
294 **kwargs,
295 ).generations[0][0],
296 ).message
``````output
File ~/langchain/oss-py/libs/core/langchain_core/language_models/chat_models.py:267, in BaseChatModel._convert_input(self, input)
265 return StringPromptValue(text=input)
266 elif isinstance(input, Sequence):
--> 267 return ChatPromptValue(messages=convert_to_messages(input))
268 else:
269 msg = (
270 f"Invalid input type {type(input)}. "
271 "Must be a PromptValue, str, or list of BaseMessages."
272 )
``````output
File ~/langchain/oss-py/libs/core/langchain_core/messages/utils.py:348, in convert_to_messages(messages)
346 if isinstance(messages, PromptValue):
347 return messages.to_messages()
--> 348 return [_convert_to_message(m) for m in messages]
``````output
File ~/langchain/oss-py/libs/core/langchain_core/messages/utils.py:348, in <listcomp>(.0)
346 if isinstance(messages, PromptValue):
347 return messages.to_messages()
--> 348 return [_convert_to_message(m) for m in messages]
``````output
File ~/langchain/oss-py/libs/core/langchain_core/messages/utils.py:321, in _convert_to_message(message)
319 except KeyError as e:
320 msg = f"Message dict must contain 'role' and 'content' keys, got {message}"
--> 321 raise ValueError(msg) from e
322 _message = _create_message_from_message_type(
323 msg_type, msg_content, **msg_kwargs
324 )
325 else:
``````output
ValueError: Message dict must contain 'role' and 'content' keys, got {'role': 'HumanMessage', 'random_field': 'random value'}
故障排除
以下内容可能有助于解决此错误:
- 确保所有输入到聊天模型的内容都是LangChain消息类的数组或支持的消息类。
- 检查是否没有发生字符串化或其他意外的转换。
- 检查错误的堆栈跟踪并添加日志或调试器语句。