LangChain初体验之对话模型提示词模版

聊天模型提示词模版

本笔记本介绍了如何在聊天模型中使用少镜头示例。关于如何最好地进行少镜头提示,似乎没有可靠的共识,最佳提示编译可能因模型而异。因此,我们提供了像FewShotChatMessagePromptTemplate这样的少镜头提示模板作为一个灵活的起点,您可以根据需要修改或替换它们。

少量提示模板的目标是根据输入动态选择示例,然后在最终提示中格式化示例以提供模型。

注意:以下代码示例适用于聊天模型。有关完成模型(LLM)的类似少拍提示示例,请参阅少拍提示模板指南。

固定示例

最基本(也是最常见)的少镜头提示技术是使用固定的提示示例。这样您就可以选择一条链,对其进行评估,并避免担心生产中的额外活动部件。

模板的基本组件是:-示例:要包含在最终提示中的字典示例列表。-example_prompt:通过其format_messages方法将每个示例转换为1条或更多消息。一个常见的示例是将每个示例转换为一条人类消息和一条人工智能消息响应,或者一条人类消息后跟一条函数调用消息。

下面是一个简单的演示。首先,导入此示例的模块:

from langchain_core.prompts import (
    ChatPromptTemplate,
    FewShotChatMessagePromptTemplate,
)
定义您要包含的示例
examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
]
接下来,将它们组装成少拍提示模板
example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}"),
        ("ai", "{output}"),
    ]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

print(few_shot_prompt.format())
Human: 2+2
AI: 4
Human: 2+3
AI: 5
最后,组装您的最终提示并将其与模型一起使用
final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)
from langchain_community.chat_models import ChatOllama

chain = final_prompt | ChatOllama(model="llama3")

chain.invoke({"input": "What's the square of a triangle?"})
AIMessage(content='I think there might be some confusion! A triangle doesn\'t have a square. In mathematics, "square" typically refers to the result of multiplying a number by itself (e.g., 2 squared is 2^2 = 4). Triangles are geometric shapes with three sides and three angles, but they don\'t have a square property.\n\nIf you meant something else, please feel free to clarify or ask another question!', response_metadata={'model': 'llama3', 'created_at': '2024-04-26T06:01:55.37120868Z', 'message': {'role': 'assistant', 'content': ''}, 'done': True, 'total_duration': 11088345307, 'load_duration': 9798867934, 'prompt_eval_count': 65, 'prompt_eval_duration': 73913000, 'eval_count': 87, 'eval_duration': 990416000}, id='run-b661ef55-087a-4cc1-abc4-0bfc7d3f4a64-0')
动态few-shot提示

有时,您可能希望根据输入设置显示哪些示例的条件。为此,您可以将示例替换为example_selector。其他组件与上述相同!要查看,动态少镜头提示模板如下所示:

  • example_selector:负责为给定的输入选择少量示例(以及它们返回的顺序)。这些实现了BaseExampleSelector 接口。一个常见的例子是vectorstore支持的SemanticSimilarityExampleSelector
  • example_prompt:通过其format_messages方法将每个示例转换为1个或多个消息。一个常见的例子是将每个示例转换为一个人工消息和一个人工智能消息响应,或者一个人工消息后跟一个函数调用消息。

这些可以再次与其他消息和聊天模板组合,以组装您的最终提示

from langchain_chroma import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_community.embeddings import OllamaEmbeddings
examples = [
    {"input": "2+2", "output": "4"},
    {"input": "2+3", "output": "5"},
    {"input": "2+4", "output": "6"},
    {"input": "What did the cow say to the moon?", "output": "nothing at all"},
    {
        "input": "Write me a poem about the moon",
        "output": "One for the moon, and one for me, who are we to talk about the moon?",
    },
]

to_vectorize = [" ".join(example.values()) for example in examples]
embeddings = OllamaEmbeddings(model='nomic-embed-text')
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)
创建example_selector

创建向量库后,您可以创建example_selector。在这里,我们将只获取前2个示例

example_selector = SemanticSimilarityExampleSelector(
    vectorstore=vectorstore,
    k=2,
)

# The prompt template will load examples by passing the input do the `select_examples` method
example_selector.select_examples({"input": "horse"})
[{'input': '2+4', 'output': '6'}, {'input': '2+2', 'output': '4'}]
创建提示模板

使用上面创建的example_selector组装提示模板。

from langchain_core.prompts import (
    ChatPromptTemplate,
    FewShotChatMessagePromptTemplate,
)

# Define the few-shot prompt.
few_shot_prompt = FewShotChatMessagePromptTemplate(
    # The input variables select the values to pass to the example_selector
    input_variables=["input"],
    example_selector=example_selector,
    # Define how each example will be formatted.
    # In this case, each example will become 2 messages:
    # 1 human, and 1 AI
    example_prompt=ChatPromptTemplate.from_messages(
        [("human", "{input}"), ("ai", "{output}")]
    ),
)
print(few_shot_prompt.format(input="What's 3+3?"))
Human: 2+3
AI: 5
Human: 2+4
AI: 6
组装最终的提示模板:
final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human", "{input}"),
    ]
)
print(few_shot_prompt.format(input="What's 3+3?"))
Human: 2+3
AI: 5
Human: 2+4
AI: 6
与LLM一起使用

现在,您可以将模型连接到few-shot提示。

from langchain_community.chat_models import ChatOllama

chain = final_prompt | ChatOllama(model="llama3")

chain.invoke({"input": "What's 3+3?"})
AIMessage(content='Easy peasy!\n\n3 + 3 = 6', response_metadata={'model': 'llama3', 'created_at': '2024-04-26T06:17:36.758995083Z', 'message': {'role': 'assistant', 'content': ''}, 'done': True, 'total_duration': 10296945893, 'load_duration': 9867175164, 'prompt_eval_count': 64, 'prompt_eval_duration': 72984000, 'eval_count': 12, 'eval_duration': 131307000}, id='run-7f4d4ec0-6cfe-4d17-8ed6-200c881908e3-0')

更多:https://github.com/tanzhixu/AI_Tutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值