元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
LangChain简介
什么是LangChain
核心概念解析
典型应用场景
▶
环境搭建
Python环境配置
安装LangChain
开发工具准备
▶
快速入门
第一个示例程序
示例分步解析
代码结构说明
▶
核心组件
Models组件
Prompts模板
Chains工作流
▶
模型集成
OpenAI集成
HuggingFace接入
▶
Chain实战
简单Chain构建
Sequential Chain
▶
记忆管理
对话记忆原理
记忆存储实现
▶
应用案例
智能问答系统
文档摘要生成
▶
调试技巧
常见错误排查
日志记录分析
▶
后续学习
学习路线图
官方资源推荐
发布时间:
2025-03-29 18:53
↑
☰
# Prompts模板详解 本文将详细介绍LangChain中的Prompts模板系统,帮助你更好地管理和使用提示模板。 ## 基础概念 ### 1. 什么是Prompt模板 Prompt模板是一种结构化的文本模板,用于生成发送给语言模型的输入。它可以包含: - 固定的文本内容 - 可变的占位符 - 格式化指令 ### 2. 为什么需要Prompt模板 - 标准化提示格式 - 减少重复代码 - 提高可维护性 - 便于复用和修改 ## 模板类型 ### 1. PromptTemplate 最基础的模板类型: ```python from langchain.prompts import PromptTemplate # 创建基础模板 template = """请用{tone}的语气介绍{topic}。 要求: 1. {requirement1} 2. {requirement2} """ prompt = PromptTemplate( input_variables=["tone", "topic", "requirement1", "requirement2"], template=template ) # 使用模板 result = prompt.format( tone="专业", topic="人工智能", requirement1="包含具体例子", requirement2="解释核心概念" ) ``` ### 2. ChatPromptTemplate 专门用于对话场景的模板: ```python from langchain.prompts import ChatPromptTemplate from langchain.prompts.chat import SystemMessagePromptTemplate from langchain.prompts.chat import HumanMessagePromptTemplate # 创建系统消息模板 system_template = "你是一个{role},专门回答{field}相关的问题。" system_message_prompt = SystemMessagePromptTemplate.from_template(system_template) # 创建用户消息模板 human_template = "{question}" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) # 组合模板 chat_prompt = ChatPromptTemplate.from_messages([ system_message_prompt, human_message_prompt ]) # 格式化消息 messages = chat_prompt.format_messages( role="AI教师", field="Python编程", question="什么是装饰器?" ) ``` ### 3. FewShotPromptTemplate 包含示例的模板: ```python from langchain.prompts import FewShotPromptTemplate from langchain.prompts import PromptTemplate # 定义示例 examples = [ {"word": "快乐", "antonym": "悲伤"}, {"word": "高", "antonym": "低"}, {"word": "冷", "antonym": "热"} ] # 创建示例模板 example_template = "词语: {word}\n反义词: {antonym}\n" example_prompt = PromptTemplate( input_variables=["word", "antonym"], template=example_template ) # 创建few-shot模板 few_shot_prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix="给出以下词语的反义词:\n", suffix="词语: {input}\n反义词:", input_variables=["input"], example_separator="\n" ) ``` ## 高级用法 ### 1. 模板组合 ```python from langchain.prompts import PipelinePromptTemplate # 创建多个模板 full_template = """{introduction} {example} {question}""" intro_template = "让我来为你解释{topic}。" example_template = "这里有一个例子:{example}" question_template = "现在,{question}" # 创建子模板 intro_prompt = PromptTemplate(template=intro_template, input_variables=["topic"]) example_prompt = PromptTemplate(template=example_template, input_variables=["example"]) question_prompt = PromptTemplate(template=question_template, input_variables=["question"]) # 组合模板 pipeline_prompt = PipelinePromptTemplate( final_prompt=PromptTemplate(template=full_template, input_variables=["introduction", "example", "question"]), pipeline_prompts=[ ("introduction", intro_prompt), ("example", example_prompt), ("question", question_prompt) ] ) ``` ### 2. 自定义模板 ```python from langchain.prompts import StringPromptTemplate from typing import List class CustomPromptTemplate(StringPromptTemplate): template: str input_variables: List[str] def format(self, **kwargs) -> str: # 添加自定义处理逻辑 processed_kwargs = {} for key, value in kwargs.items(): processed_kwargs[key] = value.upper() return self.template.format(**processed_kwargs) # 使用自定义模板 custom_prompt = CustomPromptTemplate( template="这是{text}", input_variables=["text"] ) ``` ## 最佳实践 ### 1. 模板设计原则 1. **清晰具体** - 明确任务目标 - 提供具体要求 - 包含示例说明 2. **结构化组织** - 逻辑分段 - 合理使用格式 - 适当的空白 3. **灵活可配置** - 提取可变部分 - 合理使用默认值 - 支持条件控制 ### 2. 错误处理 ```python from langchain.prompts import PromptTemplate def safe_format_prompt(prompt: PromptTemplate, **kwargs) -> str: try: return prompt.format(**kwargs) except KeyError as e: print(f"缺少必要的变量:{e}") return "" except Exception as e: print(f"格式化错误:{e}") return "" ``` ### 3. 模板管理 ```python # prompts/qa_prompts.py from langchain.prompts import PromptTemplate QA_TEMPLATE = """ 问题:{question} 请提供详细的回答,包括: 1. 核心概念解释 2. 实际应用例子 3. 相关知识链接 """ qa_prompt = PromptTemplate( template=QA_TEMPLATE, input_variables=["question"] ) ``` ## 总结 Prompts模板系统是LangChain的重要组成部分: - 提供多种模板类型 - 支持灵活的组合 - 便于扩展和自定义 - 提高代码可维护性 掌握Prompts模板的使用,将帮助你更好地构建AI应用。