LangChain实战(三):深入理解Model I/O – Prompts模板

本文是《LangChain实战课》系列的第三篇,将深入探讨LangChain中Prompt模板的核心概念、使用方法和高级技巧,帮助你掌握提示工程的艺术。

前言
在前两篇文章中,我们完成了环境搭建并创建了第一个LangChain应用。今天,我们将深入探讨LangChain Model I/O模块的核心组成部分——Prompt模板。理解并熟练使用Prompt模板是构建高效、可靠大模型应用的关键。

什么是Prompt模板?
Prompt模板是预定义的提示结构,允许我们动态插入变量,创建针对特定任务的提示。它们就像是给大模型的”指令模板”,确保每次交互都遵循一致的格式和结构。

为什么需要Prompt模板?
1、一致性:确保相同类型的请求使用相同的格式

2、可维护性:集中管理提示逻辑,便于更新和优化

3、可复用性:可以在不同场景中复用相同的模板结构

4、变量化:动态插入上下文相关信息,提高灵活性

基础Prompt模板使用

创建简单模板
让我们从最基本的PromptTemplate开始:

python
from langchain.prompts import PromptTemplate
from langchain.llms import ChatGLM # 使用之前定义的自定义ChatGLM类

初始化模型

llm = ChatGLM()

创建简单模板

template = “请解释以下技术概念: {concept}”
prompt_template = PromptTemplate(
input_variables=[“concept”],
template=template
)

使用模板

filled_prompt = prompt_template.format(concept=“机器学习”)
response = llm(filled_prompt)
print(response)
2. 多变量模板
Prompt模板支持多个变量:

python

多变量模板

template = “作为一名{role},请用{style}风格解释{concept}”
prompt_template = PromptTemplate(
input_variables=[“role”, “style”, “concept”],
template=template
)

使用模板

filled_prompt = prompt_template.format(
role=“AI专家”,
style=“通俗易懂”,
concept=“神经网络”
)
response = llm(filled_prompt)
print(response)
3. 带默认值的模板
有时我们希望某些变量有默认值:

python

带默认值的模板

template = “请用{style}风格解释{concept}”
prompt_template = PromptTemplate(
input_variables=[“concept”],
partial_variables={“style”: “简洁明了”},
template=template
)

使用模板

filled_prompt = prompt_template.format(concept=“深度学习”)
response = llm(filled_prompt)
print(response)
高级Prompt模板技巧

模板组合
我们可以将多个模板组合起来创建更复杂的提示:

python
from langchain.prompts import PipelinePromptTemplate

创建基础模板

introduction_template = PromptTemplate(
input_variables=[“concept”],
template=“请解释以下技术概念: {concept}”
)

explanation_template = PromptTemplate(
input_variables=[“concept”, “explanation”],
template=“概念: {concept}
解释: {explanation}
请提供3个实际应用示例:”
)

组合模板

full_template = PipelinePromptTemplate(
final_prompt=explanation_template,
pipeline_prompts=[
(“introduction”, introduction_template),
(“explanation”, explanation_template)
]
)

使用组合模板

input_data = {“concept”: “自然语言处理”}
response = llm(full_template.format(**input_data))
print(response)
2. 少量示例提示(Few-Shot Prompting)
Few-shot提示通过提供示例帮助模型更好地理解任务:

python
from langchain.prompts import FewShotPromptTemplate, PromptTemplate

创建示例集合

examples = [
{
“input”: “机器学习”,
“output”: “机器学习是人工智能的一个分支,它使计算机系统能够从数据中学习并改进,而无需明确编程。”
},
{
“input”: “深度学习”,
“output”: “深度学习是机器学习的一个子领域,使用多层神经网络来处理复杂模式和大规模数据。”
}
]

创建单个示例的模板

example_template = “””
概念: {input}
解释: {output}
“””

example_prompt = PromptTemplate(
input_variables=[“input”, “output”],
template=example_template
)

创建FewShot提示模板

few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix=“请根据以下示例解释技术概念:”,
suffix=“概念: {input}
解释:”,
input_variables=[“input”],
example_separator=“


)

使用FewShot模板

filled_prompt = few_shot_prompt.format(input=“计算机视觉”)
response = llm(filled_prompt)
print(response)
3. 聊天提示模板
对于聊天场景,我们需要使用专门的消息模板:

python
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate

创建系统消息模板

system_template = “你是一个AI专家助手,擅长用{style}风格解释技术概念。”
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

创建人类消息模板

human_template = “请解释{concept},并给出{number}个实际应用示例。”
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

组合聊天提示模板

chat_prompt = ChatPromptTemplate.from_messages([
system_message_prompt,
human_message_prompt
])

使用聊天提示模板

formatted_messages = chat_prompt.format_prompt(
style=“通俗易懂”,
concept=“强化学习”,
number=3
).to_messages()

对于聊天模型,我们需要使用chat方法

response = llm.chat(formatted_messages)
print(response)
实战应用:构建专业提示模板

技术文档生成器
python

技术文档生成模板

tech_doc_template = “””
作为{role},请为{technology}编写一份技术文档。

文档要求:

概述{technology}的基本概念和原理列出{technology}的主要特性和优势提供{number}个实际应用场景包含简单的代码示例(如果适用)指出{technology}的局限性和挑战

请确保文档结构清晰,语言{style}。
“””

prompt_template = PromptTemplate(
input_variables=[“role”, “technology”, “number”, “style”],
template=tech_doc_template
)

使用模板

filled_prompt = prompt_template.format(
role=“资深技术作家”,
technology=“Transformer模型”,
number=5,
style=“专业且易懂”
)

response = llm(filled_prompt)
print(response)
2. 代码审查助手
python

代码审查模板

code_review_template = “””
作为{level}的{language}开发专家,请审查以下代码:

{code}

请提供:

代码质量评估(1-5分)潜在的性能问题可读性改进建议安全性考虑{number}个具体的改进建议

请使用{style}的语言提供反馈。
“””

prompt_template = PromptTemplate(
input_variables=[“level”, “language”, “code”, “number”, “style”],
template=code_review_template
)

示例代码

sample_code = “””
def calculate_average(numbers):
total = 0
for i in range(len(numbers)):
total += numbers[i]
return total / len(numbers)
“””

使用模板

filled_prompt = prompt_template.format(
level=“高级”,
language=“Python”,
code=sample_code,
number=3,
style=“建设性且专业”
)

response = llm(filled_prompt)
print(response)
3. 多角色对话系统
python
from langchain.prompts import MessagesPlaceholder

多角色对话模板

dialogue_template = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(
“你正在扮演{character}角色。你的性格特点是{personality}。”
),
MessagesPlaceholder(variable_name=“history”),
HumanMessagePromptTemplate.from_template(“{input}”)
])

使用模板

formatted_messages = dialogue_template.format_prompt(
character=“一位严厉但公平的技术导师”,
personality=“知识渊博但要求严格,喜欢用反问句引导学生思考”,
history=[], # 在实际应用中,这里会是对话历史
input=“请解释一下注意力机制在Transformer中的作用”
).to_messages()

response = llm.chat(formatted_messages)
print(response)
Prompt模板的最佳实践

清晰明确的指令
确保你的提示模板提供清晰、明确的指令:

python

不好的示例

template = “写点关于AI的东西”

好的示例

template = “””
请撰写一篇关于人工智能在医疗领域应用的短文,包括:

当前的主要应用场景(至少3个)面临的挑战和限制未来发展趋势
文章长度约500字,语言风格专业但易懂。
“””提供上下文和约束
为模型提供足够的上下文和约束,以获得更准确的响应:

python
template = “””
作为{domain}领域的专家,请回答以下问题:
{question}

请确保:

回答基于最新研究和实践提供具体示例和数据支持指出任何不确定或有争议的方面使用{tone}的语气

回答长度限制在{word_limit}字以内。
“””
3. 结构化输出
引导模型产生结构化的输出:

python
template = “””
请分析{company}的商业模式,并按照以下结构回答:

核心价值主张

[简要描述公司的核心价值主张]

目标客户群体

[描述公司的主要目标客户]

收入来源

[列出公司的主要收入来源]

关键竞争优势

[分析公司的关键竞争优势]

潜在风险

[指出公司面临的潜在风险和挑战]

请确保每个部分简洁明了,使用项目符号列出关键点。
“””
4. 迭代优化提示
Prompt工程是一个迭代过程,需要不断测试和优化:

python

不同版本的提示模板

prompt_versions = [
“解释{concept}”,
“用简单语言解释{concept},就像对初学者一样”,
“作为领域专家,用专业但易懂的语言解释{concept},并提供3个实际应用示例”
]

测试不同提示版本

concept = “区块链”
for i, template in enumerate(prompt_versions):
prompt = PromptTemplate(
input_variables=[“concept”],
template=template
)
filled_prompt = prompt.format(concept=concept)
response = llm(filled_prompt)
print(f”版本 {i+1}:
{response}
{‘-’*50}”)
常见问题与解决方案
Q1: 如何处理模板中的变量缺失?
A: 使用validate_template方法检查模板完整性:

python
template = “请解释{concept},并给出{number}个示例”
prompt_template = PromptTemplate(
input_variables=[“concept”, “number”],
template=template
)

验证模板

try:
prompt_template.validate_template()
print(“模板有效”)
except Exception as e:
print(f”模板错误: {e}”)
Q2: 如何创建可复用的模板组件?
A: 将常用模板片段保存为变量:

python

可复用的模板组件

intro_component = “作为{role},”
task_component = “请{task},”
constraint_component = “确保使用{style}风格,长度约{length}。”

组合成完整模板

full_template = intro_component + task_component + constraint_component
prompt_template = PromptTemplate(
input_variables=[“role”, “task”, “style”, “length”],
template=full_template
)
Q3: 如何处理长文本和上下文限制?
A: 使用文本分割和摘要技术:

python
from langchain.text_splitter import CharacterTextSplitter

def process_long_text(text, template, llm, chunk_size=1000):
# 分割长文本
text_splitter = CharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=200
)
chunks = text_splitter.split_text(text)


# 处理每个分块
results = []
for chunk in chunks:
    prompt = template.format(text=chunk)
    response = llm(prompt)
    results.append(response)

return "
".join(results)

总结
通过本文,我们深入探讨了LangChain中Prompt模板的核心概念和高级用法:

✅ 理解了Prompt模板的重要性和优势

✅ 掌握了基础PromptTemplate的使用方法

✅ 学习了高级技巧如模板组合、Few-shot提示和聊天提示

✅ 实践了专业提示模板的构建方法

✅ 了解了Prompt工程的最佳实践和常见问题解决方案

Prompt模板是LangChain Model I/O模块的核心组件,掌握了它们,你就能够构建出更加高效、可靠的大模型应用。记住,优秀的提示工程是艺术和科学的结合,需要不断实践和优化。

下一步学习建议
尝试为你的特定领域创建专门的提示模板库

实验不同的提示结构和变量组合,找到最有效的方式

学习使用LangChain的输出解析器与提示模板配合使用

探索如何将提示模板与链(Chains)结合,构建复杂工作流

欢迎在评论区分享你的提示模板实践! 你创建了哪些有趣的提示模板?在使用过程中遇到了什么挑战?如果有任何疑问,欢迎在评论区留言,我们会尽力解答。

下一篇预告:《LangChain实战:深入理解Model I/O – LLMs与ChatModels》 – 我们将深入探讨LangChain中的LLMs和ChatModels模块,学习如何与不同类型的大语言模型进行交互。

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容