LangChain —— Prompt Templates

文章目录

  • [一、什么是 Prompt Templates](#一、什么是 Prompt Templates)
    • [1、String PromptTemplates](#1、String PromptTemplates)
    • 2、ChatPromptTemplates
    • [3、MessagesPlaceholder 留言占位符](#3、MessagesPlaceholder 留言占位符)
  • [二、如何使用 Prompt Templates](#二、如何使用 Prompt Templates)

一、什么是 Prompt Templates

 提示模板有助于将用户输入和参数转换为语言模型的指令。这可用于指导模型的响应,帮助它理解上下文并生成相关和连贯的基于语言的输出。

 提示模板将字典作为输入,其中 每个键 表示提示模板中要填写的 变量

 提示模板输出提示 PromptValue 值 。此 PromptValue 可以传递给 LLM 或 ChatModel,也可以转换为 字符串消息列表。此 PromptValue 存在的原因是便于在字符串和消息之间切换。

 有几种不同类型的提示模板:

1、String PromptTemplates

 这种提示模板用于 格式化单个字符串,通常用于更简单的输入。例如,构造和使用PromptTemplate的常见方法如下:

python 复制代码
from langchain_core.prompts import PromptTemplate

prompt_template = PromptTemplate.from_template("Tell me a joke about {topic}")

prompt_template.invoke({"topic": "cats"})

2、ChatPromptTemplates

 这些提示模板用于格式化消息列表。这些"模板"由模板本身的列表组成。例如,构造和使用ChatPromptTemplate的常见方法如下:

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant"),
    ("user", "Tell me a joke about {topic}")
])

prompt_template.invoke({"topic": "cats"})

 在上面的示例中,此 ChatPromptTemplate 在调用时将构造两条消息。第一个是 SystemMessage,它没有要格式化的变量。第二个是 HumanMessage,将由用户传入的 topic 变量进行格式化。

3、MessagesPlaceholder 留言占位符

 此提示模板负责在特定位置添加消息列表。

 在上面的 ChatPromptTemplate 中,我们看到了如何格式化两条消息,每条消息都是字符串。但是,如果我们想让用户传入一个消息列表,并且要把它们放在一个特定的位置呢?这就需要使用 MessagesPlaceholder 的方法。

python 复制代码
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant"),
    MessagesPlaceholder("msgs")
])

prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]})

 这将生成一个包含两条消息的列表,第一条是 SystemMessage,第二条是我们传入的 HumanMessage。如果我们传入了5条消息,那么它总共会产生6条消息 (系统消息加上传入的5条消息)。这对于将消息列表放入特定位置非常有用。

 在不显式使用 MessagesPalaceholder 类的情况下,完成相同任务的另一种方法是:

python 复制代码
prompt_template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant"),
    ("placeholder", "{msgs}") # <-- This is the changed part
])

二、如何使用 Prompt Templates

 Prompt Templates (提示模板),负责将用户输入格式化为可以传递给语言模型的格式。

相关推荐
swipe3 小时前
DeepAgents 多 Agent 深度调研助手工程实战:从 createDeepAgent 到可控调研工作流
javascript·面试·langchain
贺国亚7 小时前
RAG检索增强-向量库与Chunking
prompt·embedding
sleven fung9 小时前
Milvus 向量数据库
开发语言·数据库·python·langchain·milvus
Jing_jing_X9 小时前
从 Prompt 对话到 OpenClaw:Agent 是怎么一步步发展出来的?
ai·prompt·个人开发·ai应用开发
code bean9 小时前
【LangChain】RunnableWithMessageHistory 完全指南(下):流式、截断与自定义
langchain
城事漫游Molly9 小时前
AI与质性研究的融合(三):AI赋能质性数据分析——从编码到理论构建的新范式
大数据·人工智能·机器学习·prompt·ai for science·智能体·定性研究
麦哲思科技任甲林10 小时前
白话skills之二:Prompt和Skills的区别是什么?
prompt·sop·skills
小碗羊肉11 小时前
【Agent笔记 | 第五篇】LangChain&LangGraph
笔记·langchain
abigale0311 小时前
LangChain 多轮对话记忆:基于 session_id 实现多会话隔离
typescript·langchain·uuid·session_id
人工智能培训11 小时前
数字孪生赋能建筑行业 解锁工程全周期智慧管理
大数据·人工智能·机器学习·prompt·agent