← 返回首页
LangChain的Prompt-提示词
发表时间:2025-05-13 15:30:22
LangChain的Prompt-提示词

1.Prompt(提示)是什么

Prompt(提示)是一种指导语言模型生成特定类型输出的文本模板。它通常包含一些预设的文本框架,以及一些变量占位符,当实际运行时,这些占位符会被具体的值所替换。Prompt的作用在于引导语言模型按照预期的方式生成回复,确保输出符合特定的格式、语境或者目的。

2.Langchain使用Prompt

2.1 单个变量

PromptTemplate 是一个基础的模板类,用于构建格式化的提示字符串。它允许你定义一个模板字符串,并在运行时根据传入的变量替换其中的占位符。对于单个变量(句子里有一个占位符可以自定义)可以通过以下两种方式格式化Prompt。

from langchain_core.prompts import PromptTemplate

# 定义一个包含单个变量的模板字符串
template = """
今天{location}天气怎么样?
"""

# 方式一:
# 使用PromptTemplate类从模板字符串中创建一个提示对象
prompt = PromptTemplate.from_template(template=template)
# format方法填入变量
print(prompt.format(location="北京"))

# 方式二:
# 创建PromptTemplate对象来显式的输入变量和模板字符串
prompt = PromptTemplate(input_variables=["location"], template=template)
print(prompt.format(location="上海"))

运行效果:

今天北京天气怎么样?


今天上海天气怎么样?

2.2 多个变量

PromptTemplate 是一个基础的模板类,用于构建格式化的提示字符串。它允许你定义一个模板字符串,并在运行时根据传入的变量替换其中的占位符。对于多个变量(句子里有多个占位符可以自定义)可以通过以下两种方式格式化Prompt。

from langchain_core.prompts import PromptTemplate

# 多个变量
template = """
{date}{location}天气怎么样?
"""

prompt = PromptTemplate.from_template(template=template)
print(prompt.format(date="今天", location="北京"))

prompt = PromptTemplate(input_variables=["date", "location"], template=template)
print(prompt.format(date="明天", location="上海"))

运行效果:

今天北京天气怎么样?


明天上海天气怎么样?

2.3 聊天提示模板

PromptTemplate形式和Message的区别在于是否可以在中间挖空。使用Message就是直接写死,使用PromptTemplate就是使用模板从而动态调整提示词。

聊天提示模板方式一:

from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate


# 创建一个系统消息,用于定义机器人的角色
system_message = SystemMessagePromptTemplate.from_template("你是一个有用的助手,帮助用户学习编程。")
# 添加一些额外的需要存储的信息,比如时间戳
system_message.additional_kwargs = {
    "timestamp": "2024",
    "source": "system"
}

# 创建一个人类的消息,user消息
hunman_message = HumanMessagePromptTemplate.from_template("用户问:{user_question}")

# 创建一个AI消息
ai_message = AIMessagePromptTemplate.from_template("")

chat_message = ChatPromptTemplate.from_messages([
    system_message,
    hunman_message,
    ai_message
])

user_input = "怎么学习python?"
print(chat_message.format(user_question=user_input))

聊天提示模板方式二:

from langchain.schema import AIMessage, HumanMessage, SystemMessage
from langchain.prompts import ChatPromptTemplate


chat_message = ChatPromptTemplate.from_messages([
    SystemMessage(content="你是一个有用的助手,你会帮助用户学习编程。"),
    HumanMessage(content="用户问:如何开始学习python?"),
    AIMessage(content="")
])

print(chat_message.format_messages())