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

关于LangChain PromptTemplate中input_variables参数的作用与用法咨询

LangChain PromptTemplate中input_variables参数的作用与用法

核心用途

input_variables的核心作用有两个:

  • 强制验证:实例化PromptTemplate时,会把这个参数里的变量和模板字符串中的占位符做比对,不匹配就直接报错,提前发现问题。
  • 明确依赖:当模板内容不是硬编码(比如来自外部配置、数据库或动态生成)时,显式声明需要的输入变量,让代码逻辑更清晰,避免因模板变更导致的隐性错误。

你的示例分析

你写的这段代码:

from langchain.prompts import PromptTemplate

invalid_prompt = PromptTemplate(
    "Tell me a {adjective} joke about {content}."
)

属于不规范写法(虽然LangChain会自动解析模板里的占位符作为输入变量)。如果不显式指定input_variables,当模板字符串被意外修改(比如不小心删掉了{content}),后续调用format方法时传入content参数就会报错,且错误只会在运行时才暴露。

正确配置示例

场景1:硬编码模板,显式验证

把模板中的变量全部声明在input_variables里,实例化时就会做校验,提前发现问题:

from langchain.prompts import PromptTemplate

# 正确配置:input_variables与模板占位符完全匹配
valid_prompt = PromptTemplate(
    input_variables=["adjective", "content"],
    template="Tell me a {adjective} joke about {content}."
)

# 使用时传入对应变量
result = valid_prompt.format(adjective="silly", content="cats")

如果此时你把input_variables写成["adjective"],实例化时就会直接抛出ValidationError,提示模板里的content未被声明,避免后续运行时出错。

场景2:动态模板(你猜测的场景)

当模板内容来自外部(比如配置文件、接口返回),你无法直接从代码里看到模板的占位符,这时input_variables就用来明确告诉PromptTemplate需要哪些输入变量:

from langchain.prompts import PromptTemplate

# 假设template来自外部(比如配置读取)
template = "Recommend a {adjective} {category} for me."

# 显式声明需要的输入变量
dynamic_prompt = PromptTemplate(
    input_variables=["adjective", "category"],
    template=template
)

# 使用时传入对应变量
result = dynamic_prompt.format(adjective="cozy", category="cafe")

这种场景下,即使后续模板内容变更,只要input_variables和模板占位符保持一致,就能确保代码逻辑的可靠性。

总结

  • 硬编码模板时,显式指定input_variables是最佳实践,能提前发现变量不匹配的问题。
  • 动态模板场景下,input_variables是关键配置,用来明确依赖,避免因模板变化导致的隐性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:22:43