LangChain提示词

115 阅读2分钟

提示词

构建提示词在大模型中非常有用,好的提示能让模型回答的效果更加贴近应用场景。关于提示词怎么写不在本教程的讨论范围内,本节主要介绍如何应用LangChain来给模型增加提示词。

在LangChain中创建提示词通常采用以下流程:

prompt创建流程.png

准备提示词文本

system_template = "Translate the following from English into {language}"

在提示词文本中,我们增加了"language"这个变量,后续我们可以对该文本做渲染,使得我们的提示词能够满足更多的场景。

创建提示词模板对象

from langchain_core.prompts import ChatPromptTemplate

system_template = "Translate the following from English into {language}"

prompt = ChatPromptTemplate.from_messages(
    [("system", system_template), ("user", "{text}")]
)

这种创建方式比较贴近OpenAI的使用习惯,消息类型有以下几种:

  • System:用于设置对话的背景或上下文,通常用于定义模型的行为或角色;
  • User:表示用户输入的内容,通常是用户提出的问题或请求;
  • Assistant:表示模型的回复内容,通常是模型生成的回答;
  • Function:表示模型调用外部函数的结果,通常用于 Function Calling 功能;
  • Tool:表示模型调用工具的结果,通常用于 Assistants API 中的工具调用。

当然你也可以用以下方式,两者没有差别。目前LangChain内只提供了对System,Human(对应User),AI(对应Assistant)几种消息的封装结构:

# 创建消息模板
system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_message_prompt = HumanMessagePromptTemplate.from_template("{text}")

# 使用 from_messages 创建 ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
    system_message_prompt,
    human_message_prompt
])

ChatPromptTemplate还有一个from_template方法通常也会用来创建模板对象,其本质上也是调用from_messages,适合比较简单的用户对话场景。

提示词模板渲染

我们可以根据自身业务需要,对提示词模板进行渲染,方式如下:

formatted_prompt = prompt.format_prompt(language="French", text="Hello, how are you?")
print(formatted_prompt.to_messages())

可以看到打印的结果

[SystemMessage(content='Translate the following from English into French', additional_kwargs={}, response_metadata={}), HumanMessage(content='Hello, how are you?', additional_kwargs={}, response_metadata={})]

发起模型调用

初始化好模型后,直接传入我们定义好的prompt:

response = model.invoke(formatted_prompt)
print(response.content)

得到模型的返回:

Bonjour, comment ça va ?

后续只需要我们对渲染的参数稍加修改,就可以得到完全不同的返回结果:

formatted_prompt = prompt.format_prompt(language="Chinese", text="Hello, how are you?")

response = model.invoke(formatted_prompt)
print(response.content)

返回的结果是:

你好,你怎么样?

完整代码如下:


from langchain_core.prompts import ChatPromptTemplate

system_template = "Translate the following from English into {language}"

prompt = ChatPromptTemplate.from_messages(
    [("system", system_template), ("user", "{text}")]
)

# 格式化提示
formatted_prompt = prompt.format_prompt(language="French", text="Hello, how are you?")

from langchain_openai import ChatOpenAI
import os
import getpass

# 设置 DeepSeek 的 API 密钥
if not os.environ.get("LLM_API_KEY"):
  os.environ["LLM_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

# 初始化大模型
model = ChatOpenAI(
    model='deepseek-chat',
    openai_api_key=os.environ.get("LLM_API_KEY"),
    openai_api_base='https://api.deepseek.com'
)

# 对提示词模板进行渲染
formatted_prompt = prompt.format_prompt(language="Chinese", text="Hello, how are you?")

# 调用大模型
response = model.invoke(formatted_prompt)
print(response.content)