第四章:大模型(LLM)】06.langchain原理-(3)LangChain Prompt 用法

第四章:大模型(LLM)

第六部分:LangChain 原理

第三节:LangChain Prompt 用法

Prompt 在 LangChain 中处于核心地位。它决定了模型接收的上下文和指令,从而直接影响输出质量。LangChain 针对 Prompt 做了高度抽象和封装,主要包含以下几个方面:


1. Prompt 的基本概念

  • Prompt:输入给 LLM 的文本(可能包含占位符、上下文、指令等)。

  • PromptTemplate :LangChain 对 Prompt 的抽象,用来支持动态插值可复用模板

  • MessagePromptTemplate:用于多轮对话,支持 System / Human / AI 多角色消息。

  • ChatPromptTemplate:封装一组消息模板,便于和聊天模型结合。


2. PromptTemplate 使用

python 复制代码
from langchain.prompts import PromptTemplate

template = "请用一句话总结以下内容:{text}"
prompt = PromptTemplate(
    input_variables=["text"],
    template=template,
)

# 渲染
final_prompt = prompt.format(text="LangChain 是一个用于构建大模型应用的框架。")
print(final_prompt)
# 输出: 请用一句话总结以下内容:LangChain 是一个用于构建大模型应用的框架。

特点:

  • 模板中使用 {变量名} 作为占位符。

  • input_variables 定义可替换的变量。


3. ChatPromptTemplate(对话型提示)

python 复制代码
from langchain.prompts import ChatPromptTemplate

chat_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个乐于助人的助手。"),
    ("human", "请将以下内容翻译成英文:{text}")
])

final_prompt = chat_prompt.format_messages(text="你好,世界!")
print(final_prompt)

输出是多条消息,适配聊天模型(如 OpenAI ChatCompletion)。


4. Few-shot Prompt(小样本提示)

python 复制代码
from langchain.prompts import FewShotPromptTemplate

examples = [
    {"question": "2+2等于几?", "answer": "4"},
    {"question": "3+5等于几?", "answer": "8"},
]

example_prompt = PromptTemplate(
    input_variables=["question", "answer"],
    template="Q: {question}\nA: {answer}"
)

few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Q: {input}\nA:",
    input_variables=["input"],
)

print(few_shot_prompt.format(input="10+15等于几?"))

通过示例引导模型学习回答模式。


5. Prompt 的链式组合

Prompt 可以和 ChainMemory 结合:

  • Chain + Prompt:先动态生成 Prompt,再传给 LLM。

  • Memory + Prompt:记忆组件自动填充 Prompt 的历史对话部分。


6. 实战技巧

  1. 少即是多:Prompt 过长可能导致 LLM 迷失重点。

  2. 角色扮演:在 Prompt 中设置 AI 的身份,可改善回答风格。

  3. 输出约束:通过 JSON Schema、格式提示,提高结果可解析性。

  4. 动态拼接:结合外部数据源动态注入 Prompt。


7. 小结

  • LangChain 的 Prompt 系统提供了 灵活可重用的模板机制

  • PromptTemplateChatPromptTemplate,再到 FewShotPromptTemplate,逐步增强了 Prompt 的表达能力。

  • 配合 Chain / Memory,可以实现高度自动化的 Prompt 生成。

相关推荐
冷雨夜中漫步5 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
33三 三like5 小时前
《基于知识图谱和智能推荐的养老志愿服务系统》开发日志
人工智能·知识图谱
芝士爱知识a5 小时前
【工具推荐】2026公考App横向评测:粉笔、华图与智蛙面试App功能对比
人工智能·软件推荐·ai教育·结构化面试·公考app·智蛙面试app·公考上岸
郝学胜-神的一滴5 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再5 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
JH30736 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
腾讯云开发者6 小时前
港科大熊辉|AI时代的职场新坐标——为什么你应该去“数据稀疏“的地方?
人工智能
工程师老罗6 小时前
YoloV1数据集格式转换,VOC XML→YOLOv1张量
xml·人工智能·yolo
喵手7 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控