欢迎光临
我们一直在努力

LangChain 中的提示词模板(Prompt Template)

   提示词模板是 LangChain 中管理、复用和动态构建提示词的核心工具。它解决了硬编码提示词带来的维护困难和灵活性差的问题。

一、为什么需要提示词模板?

# 不好的做法:硬编码
response = llm.invoke("请用中文回答:什么是机器学习?")

# 好的做法:使用模板
from langchain.prompts import PromptTemplate

template = PromptTemplate.from_template("请用{language}回答:{question}")
prompt = template.format(language="中文", question="什么是机器学习?")
response = llm.invoke(prompt)

核心价值:

优势说明
可复用 同一模板可用于不同场景
可维护 修改提示词只需改一处
可组合 多个模板可以串联使用
可版本化 模板可以像代码一样管理

二、字符串提示词模板(PromptTemplate)

1. 基本使用

from langchain.prompts import PromptTemplate

# 方式1:from_template(推荐)
template = PromptTemplate.from_template(
"你是一位{role}专家,请用{style}的风格回答:{question}"
)

# 方式2:直接构造
template = PromptTemplate(
input_variables=["role", "style", "question"],
template="你是一位{role}专家,请用{style}的风格回答:{question}"
)

# 使用
prompt = template.format(
role="Python",
style="幽默",
question="什么是装饰器?"
)

2. 部分变量(Partial)

预先固定某些变量,生成新的模板。

from langchain.prompts import PromptTemplate

# 原始模板
template = PromptTemplate.from_template(
"请用{language}回答:{question}"
)

# 方式1:字符串部分变量
partial_template = template.partial(language="中文")

# 使用
prompt = partial_template.format(question="什么是AI?")
print(prompt) # 请用中文回答:什么是AI?

# 方式2:函数部分变量(动态值)
from datetime import datetime

template = PromptTemplate.from_template(
"今天是{date},天气{weather},请推荐活动"
)

def get_today():
return datetime.now().strftime("%Y-%m-%d")

partial_template = template.partial(date=get_today)

3. 使用 invoke 方法

from langchain.prompts import PromptTemplate

template = PromptTemplate.from_template(
"你是一个{role},请回答:{question}"
)

# 使用 invoke 方法(推荐)
result = template.invoke({"role": "老师", "question": "什么是1+1?"})
print(result.to_string())

三、对话提示词模板(ChatPromptTemplate)

适用于多轮对话场景,支持 system、human、ai 等不同角色。

1. 基本使用

from langchain.prompts import ChatPromptTemplate

# 方式1:使用消息模板
template = ChatPromptTemplate.from_messages([
("system", "你是一个{role}专家,请用{style}的风格回答。"),
("human", "{question}"),
])

# 方式2:使用 Message 对象
from langchain_core.messages import SystemMessage, HumanMessage

template = ChatPromptTemplate.from_messages([
SystemMessage(content="你是一个{role}专家"),
HumanMessage(content="{question}"),
])

# 使用
prompt = template.invoke({
"role": "Python",
"style": "幽默",
"question": "什么是装饰器?"
})

response = llm.invoke(prompt)

2. 带历史消息的模板

from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

template = ChatPromptTemplate.from_messages([
("system", "你是一个友好的助手。"),
MessagesPlaceholder(variable_name="chat_history"), # 历史消息占位
("human", "{input}"),
])

# 构建消息
from langchain_core.messages import AIMessage, HumanMessage

chat_history = [
HumanMessage(content="我叫张三"),
AIMessage(content="你好张三!有什么我可以帮你的?"),
]

prompt = template.invoke({
"chat_history": chat_history,
"input": "我叫什么名字?"
})

四、Few-Shot 提示词模板(FewShotPromptTemplate)

用于提供示例,引导模型按预期格式输出。

1. 基本使用

from langchain.prompts import FewShotPromptTemplate, PromptTemplate

# 示例
examples = [
{"input": "开心", "output": "positive"},
{"input": "伤心", "output": "negative"},
{"input": "兴奋", "output": "positive"},
]

# 示例格式化模板
example_template = PromptTemplate.from_template(
"输入: {input}\\n输出: {output}"
)

# Few-Shot 模板
few_shot_template = FewShotPromptTemplate(
examples=examples,
example_prompt=example_template,
prefix="请判断以下输入的情绪类型(positive/negative):",
suffix="输入: {input}\\n输出:",
input_variables=["input"],
)

# 使用
prompt = few_shot_template.format(input="愤怒")
print(prompt)

2. 动态选择示例(ExampleSelector)

from langchain.prompts import FewShotPromptTemplate, PromptTemplate
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS

examples = [
{"input": "happy", "output": "positive"},
{"input": "sad", "output": "negative"},
{"input": "excited", "output": "positive"},
# … 更多示例
]

# 语义相似度选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
examples,
OpenAIEmbeddings(),
FAISS,
k=2 # 选择最相似的2个示例
)

dynamic_template = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_template,
prefix="根据示例判断情绪:",
suffix="输入: {input}\\n输出:",
input_variables=["input"],
)

# 会自动选择与"angry"最相似的示例
prompt = dynamic_template.format(input="angry")

五、PipelinePromptTemplate(管道模板)

将多个模板组合成一个。

from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts import PromptTemplate

# 定义子模板
intro = PromptTemplate.from_template("你是{role}专家")
main = PromptTemplate.from_template("请回答:{question}")
closing = PromptTemplate.from_template("请用{style}风格回答")

# 组合成管道
full_template = PipelinePromptTemplate(
final_prompt=PromptTemplate.from_template(
"{intro}\\n{main}\\n{closing}"
),
pipeline_prompts=[
("intro", intro),
("main", main),
("closing", closing),
]
)

prompt = full_template.format(
role="Python",
question="什么是装饰器?",
style="幽默"
)

六、自定义输出解析器配合模板

提示词模板常与输出解析器配合使用,规范模型输出。

from langchain.prompts import PromptTemplate
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field

class Person(BaseModel):
name: str = Field(description="姓名")
age: int = Field(description="年龄")

parser = PydanticOutputParser(pydantic_object=Person)

template = PromptTemplate(
template="从以下文本中提取信息:\\n{text}\\n{format_instructions}",
input_variables=["text"],
partial_variables={"format_instructions": parser.get_format_instructions()}
)

prompt = template.format(text="张三今年25岁")
print(prompt)

七、模板管理:load_prompt 从文件加载

1. 保存模板到文件

// prompt.json
{
"name": "expert",
"template": "你是一个{role}专家,请回答:{question}",
"input_variables": ["role", "question"]
}

2. 从文件加载

from langchain.prompts import load_prompt

template = load_prompt("prompt.json")
prompt = template.format(role="Python", question="什么是装饰器?")

八、其他

模板类型适用场景特点
PromptTemplate 简单字符串提示 轻量直接
ChatPromptTemplate 多轮对话 支持 system/human/ai 角色
FewShotPromptTemplate 需要示例引导 展示输入输出示例
PipelinePromptTemplate 复杂组合 多个模板拼接
赞(0)
未经允许不得转载:171主机测评 » LangChain 中的提示词模板(Prompt Template)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址