Skip to main content
prompt template 收到缺失或无效的输入变量时发生。 发生这种情况的一种意外方式是,如果您直接将 JSON 对象添加到提示模板中:
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";

const prompt = PromptTemplate.fromTemplate(`You are a helpful assistant.

Here is an example of how you should respond:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 21
}

Now, answer the following question:

{question}`);
您可能认为上面的提示模板应该需要一个名为 question 的单一输入键,但 JSON 对象将被解释为额外的变量,因为花括号 ({) 没有被转义,应该在它们前面加上第二个花括号,如下所示:
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";

const prompt = PromptTemplate.fromTemplate(`You are a helpful assistant.

Here is an example of how you should respond:

{{
  "firstName": "John",
  "lastName": "Doe",
  "age": 21
}}

Now, answer the following question:

{question}`);

故障排除

要解决此错误,您可以:
  1. 检查您的提示模板是否正确。使用 f-string 格式时,确保正确转义花括号:
    • 在 f-strings 中使用 {{ 表示单个花括号
    • 在 f-strings 中使用 {{{{ 表示双花括号
  2. 使用 MessagesPlaceholder 组件时,确认为正在传递消息数组或类似消息的对象。如果使用简写元组,请将变量名用花括号括起来,如 ["placeholder", "{messages}"]
  3. 通过使用 LangSmith 或日志记录来检查提示模板的实际输入,以验证它们是否符合预期
  4. 如果从 LangChain Prompt Hub 获取提示,请隔离并使用示例输入测试提示,以确保其按预期运行