第四章:大模型(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 生成。

相关推荐
跨境卫士情报站几秒前
TikTok跨境电商第二增长曲线:从“跑量”到“跑利润”的精细化运营
大数据·人工智能·产品运营·跨境电商·tiktok·营销策略
自己的九又四分之三站台2 分钟前
9:MemNet记忆层使用,实现大模型对话上下文记忆
人工智能·算法·机器学习
CoderJia程序员甲6 分钟前
GitHub 热榜项目 - 日榜(2026-02-02)
人工智能·ai·大模型·github·ai教程
AndrewHZ7 分钟前
【AI黑话日日新】什么是大模型的test-time scaling?
人工智能·深度学习·大模型·llm·推理加速·测试时缩放
逻极9 分钟前
OpenClaw「Clawdbot/Moltbot」 深入解析:核心架构深度剖析
python·ai·架构·agent·ai编程·moltbot·openclaw
sayang_shao11 分钟前
C++ ONNX Runtime 与 Python Ultralytics 库实现 YOLOv8 模型检测的区别
c++·python·yolo
曹牧12 分钟前
Java:强类型转换
开发语言·python
李昊翔的博客20 分钟前
大模型正在反向收割互联网红利
人工智能
爱学习的阿磊21 分钟前
Python入门:从零到一的第一个程序
jvm·数据库·python