LangChain PromptTemplate 详解:把 Prompt 当代码管理
895 字
4 分钟
LangChain PromptTemplate 详解:把 Prompt 当代码管理
PromptTemplate 是 LangChain 的核心模块之一,作用是 组织和动态生成 Prompt。
它解决的问题是:Prompt 不能写死,需要和用户输入 / 任务上下文结合,保持复用和一致性。
1. PromptTemplate 的核心作用
- 模板化 Prompt:用
{} 占位,把变量和固定内容分离。 - 动态渲染:运行时把用户输入填充进去。
- 减少重复代码:把 Prompt 逻辑集中管理,而不是散落在代码里。
- 结构化输出:结合 parser,可以要求模型输出 JSON / YAML 等格式。
2. 基本用法
(1)最简单的创建方式
from langchain.prompts import PromptTemplate
template = "把以下中文翻译成英文: {text}"prompt = PromptTemplate.from_template(template)
# 渲染print(prompt.format(text="你好,世界"))# => "把以下中文翻译成英文: 你好,世界"(2)带多个变量
template = "请写一首关于 {animal} 和 {place} 的诗"prompt = PromptTemplate.from_template(template)
print(prompt.format(animal="小猫", place="月亮"))输出:
请写一首关于 小猫 和 月亮 的诗(3)显式指定输入变量
prompt = PromptTemplate( input_variables=["product", "style"], template="请写一个关于 {product} 的广告文案,风格是 {style}")
print(prompt.format(product="咖啡", style="幽默"))3. 高级功能
(1)PromptTemplate + Partial(部分固定)
有时候某些变量是 固定的,可以先“绑定”住。
prompt = PromptTemplate.from_template( "把以下内容翻译成 {language}: {text}")
# 固定 languagepartial_prompt = prompt.partial(language="English")print(partial_prompt.format(text="早上好"))(2)多层 Prompt 组合
你可以把小模板组合成复杂的 Prompt。
intro_prompt = PromptTemplate.from_template("用户问题是: {question}")task_prompt = PromptTemplate.from_template("请根据以下问题生成 SQL: {question}")
full_prompt = intro_prompt.format(question="查询今天销量")print(full_prompt)print(task_prompt.format(question="查询今天销量"))(3)和输出解析器结合
LangChain 提供 OutputParser,可以结合 PromptTemplate,指导模型输出 JSON、列表等结构化结果。
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
schemas = [ ResponseSchema(name="summary", description="文本总结"), ResponseSchema(name="keywords", description="关键词"),]
parser = StructuredOutputParser.from_response_schemas(schemas)format_instructions = parser.get_format_instructions()
prompt = PromptTemplate.from_template("""请分析以下文本:{text}
请严格按照以下格式输出:{format_instructions}""")
print(prompt.format(text="今天股市上涨,投资人情绪积极", format_instructions=format_instructions))这样 Prompt 会明确告诉模型输出 JSON,并能用 parser.parse() 解析。
(4)Few-shot Prompting
PromptTemplate 可以和 示例库(FewShotPromptTemplate) 配合,让模型参考样例。
from langchain.prompts import FewShotPromptTemplate
examples = [ {"word": "猫", "translation": "cat"}, {"word": "狗", "translation": "dog"},]
example_template = "中文: {word} -> 英文: {translation}"example_prompt = PromptTemplate.from_template(example_template)
prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, suffix="中文: {input} -> 英文:", input_variables=["input"])
print(prompt.format(input="苹果"))输出大致为:
中文: 猫 -> 英文: cat中文: 狗 -> 英文: dog中文: 苹果 -> 英文:(5)动态选择模板(Selector)
如果你的输入场景复杂,可以让 LangChain 自动挑选最合适的模板。
例如:
- 用户输入太短 → 用简单 Prompt
- 用户输入很长 → 用总结型 Prompt
(这里可以结合 LengthBasedExampleSelector 等工具)
4. PromptTemplate 的常见技巧
-
用大括号
{{ }} 转义
如果你要在模板里输出固定的花括号(比如 JSON),要用双层:template = "输出 JSON: {{'a': '{value}'}}"prompt = PromptTemplate.from_template(template)print(prompt.format(value="测试"))✅ 否则会被误认为是占位符。
-
加入格式约束
- 在 Prompt 里明确说明输出必须是 JSON / Markdown / 表格。
- 给出样例输出,效果更稳定。
-
分层管理 Prompt
- 用不同的 PromptTemplate 管不同任务(翻译 / 总结 / 检索)。
- 在 Chain 里组合,减少重复。
-
调试 Prompt
-
prompt.format() 先看看渲染结果,再丢给 LLM。 - 建议用 LangSmith 或日志系统跟踪实际 Prompt。
-
5. 总结
- PromptTemplate = 占位 + 模板渲染。
- 支持:单变量、多变量、部分固定、FewShot、解析器、动态选择。
- 核心技巧:转义、格式约束、样例提示、日志调试。
- 价值:让 Prompt 结构化、复用、可控,避免硬编码。
如何输出json
文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
LangChain PromptTemplate 详解:把 Prompt 当代码管理
https://guoxin.wiki/posts/langchain-prompt-template/相关文章智能推荐
1
LangChain VectorStore 的几种检索方式
AI 与 Agentsimilarity_search、带分数检索、MMR 等几种向量检索方式的差异和适用场景。
2
LangChain Agent 入门:LLM + 工具集 + 推理策略
AI 与 AgentAgent 的组成部分、Zero-shot / ReAct / Plan-and-Act 策略对比,以及工具设计、内存、token 控制方面的注意事项。
3
LangChain 的 Tools 体系:给 LLM 装上手和脚
AI 与 AgentTool 的接口定义、结构化工具(StructuredTool)、工具集与工具包的组织方式,以及 Agent 选择工具的原理。
4
Windows 11 上封锁 Claude Code 出网:防火墙 + DNS + hosts 三层实战
运维与工具用防火墙规则、DNS 重定向和 hosts 三层手段封锁 Claude Code 的出网流量,并给出一套可验证、可回滚的完整脚本与自检流程。
5
React 学习 Day1:基础语法与整体框架(含 JS 关键基础)
前端建立对 React 的整体认识,并补齐编写 React 所必需的 JavaScript 语法基础:组件化、Props/State、JSX 与常用概念。
随机文章随机推荐














