• 【LangChain系列 8】Prompt模版——少样本prompt模版(二)


    原文地址:【LangChain系列 8】Prompt模版——少样本prompt模版(二)

    本文速读:

    • 固定少样本prompt模版

    • 动态少样本prompt模版

    在上篇文章中介绍了少样本模版的基本用法,本文将介绍 对话模型(chat model) 中 少样本prompt模版的用法。

    LangChain封装了一些像FewShotChatMessagePromptTemplate的少样本prompt模版,在此基础上我们可以灵活的设计我们需要的 少样本prompt模版 。

    少样本prompt模版 的目标就是可以根据输入去动态地选择样本,然后将选择的样本格式化到最后的prompt中去。

    01 固定少样本prompt模版


    最基本的少样本prompt技术是使用固定的prompt样本,所以对于一个少样本prompt模版至少要包含:

    • examples:用于prompt的样本数据

    • example_prompt:将每个样本数据转换成message

    话不多说,下面将通过一个示例来介绍 固定少样本prompt模版 的使用。

    1. 导入相关模块

    1. from langchain.prompts import (
    2. FewShotChatMessagePromptTemplate,
    3. ChatPromptTemplate,
    4. )

    2. 定义examples

    1. examples = [
    2. {"input": "2+2", "output": "4"},
    3. {"input": "2+3", "output": "5"},
    4. ]

    3. 定义example_prompt

    1. # This is a prompt template used to format each individual example.
    2. example_prompt = ChatPromptTemplate.from_messages(
    3. [
    4. ("human", "{input}"),
    5. ("ai", "{output}"),
    6. ]
    7. )
    8. few_shot_prompt = FewShotChatMessagePromptTemplate(
    9. example_prompt=example_prompt,
    10. examples=examples,
    11. )
    12. print(few_shot_prompt.format())

    执行代码,输出结果:

    1. Human: 2+2
    2. AI: 4
    3. Human: 2+3
    4. AI: 5

    4. 拼装最终的prompt​​​​​​​

    1. final_prompt = ChatPromptTemplate.from_messages(
    2. [
    3. ("system", "You are a wondrous wizard of math."),
    4. few_shot_prompt,
    5. ("human", "{input}"),
    6. ]
    7. )
    1. from langchain.chat_models import ChatAnthropic
    2. chain = final_prompt | ChatAnthropic(temperature=0.0)
    3. chain.invoke({"input": "What's the square of a triangle?"})

    ChatAnthropic是一个对话大语言模型,将最终的prompt输入给它,然后得到一个回答。执行代码,输出结果:

    AIMessage(content=' Triangles do not have a "square". A square refers to a shape with 4 equal sides and 4 right angles. Triangles have 3 sides and 3 angles.\n\nThe area of a triangle can be calculated using the formula:\n\nA = 1/2 * b * h\n\nWhere:\n\nA is the area \nb is the base (the length of one of the sides)\nh is the height (the length from the base to the opposite vertex)\n\nSo the area depends on the specific dimensions of the triangle. There is no single "square of a triangle". The area can vary greatly depending on the base and height measurements.', additional_kwargs={}, example=False)

    02 动态少样本prompt模版


    有时我们可能需要从所有样本中动态选择更加符合要求的样本,此时我们只需要把examples替换成example_selector就可以了;那么动态的少样本prompt模版应该包含:

    • example_selector:根据输入从所有样本中选择部分样本数据

    • example_prompt:将每个样本数据转换成message

    下面将介绍如何使用动态少样本prompt模版。

    1. 导入相关包​​​​​​​

    from langchain.prompts import SemanticSimilarityExampleSelectorfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.vectorstores import Chroma

    2. 定义example,并向量化

    1. examples = [
    2. {"input": "2+2", "output": "4"},
    3. {"input": "2+3", "output": "5"},
    4. {"input": "2+4", "output": "6"},
    5. {"input": "What did the cow say to the moon?", "output": "nothing at all"},
    6. {
    7. "input": "Write me a poem about the moon",
    8. "output": "One for the moon, and one for me, who are we to talk about the moon?",
    9. },
    10. ]
    11. to_vectorize = [" ".join(example.values()) for example in examples]
    12. embeddings = OpenAIEmbeddings()
    13. vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)

    ​​​​​​​

    3. 创建example_selector

    1. example_selector = SemanticSimilarityExampleSelector(
    2. vectorstore=vectorstore,
    3. k=2,
    4. )
    5. # The prompt template will load examples by passing the input do the `select_examples` method
    6. example_selector.select_examples({"input": "horse"})
    1. [{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'},
    2. {'input': '2+4', 'output': '6'}]

    4. 创建prompt模版

    1. from langchain.prompts import (
    2. FewShotChatMessagePromptTemplate,
    3. ChatPromptTemplate,
    4. )
    5. # Define the few-shot prompt.
    6. few_shot_prompt = FewShotChatMessagePromptTemplate(
    7. # The input variables select the values to pass to the example_selector
    8. input_variables=["input"],
    9. example_selector=example_selector,
    10. # Define how each example will be formatted.
    11. # In this case, each example will become 2 messages:
    12. # 1 human, and 1 AI
    13. example_prompt=ChatPromptTemplate.from_messages(
    14. [("human", "{input}"), ("ai", "{output}")]
    15. ),
    16. )
    17. print(few_shot_prompt.format(input="What's 3+3?"))

    输出结果:​​​​​​​

    1. Human: 2+3
    2. AI: 5
    3. Human: 2+2
    4. AI: 4

    few_shot_prompt会根据input,动态地从examples中去选择合适的example数据。

    5. 拼装最终的prompt​​​​​​​

    1. final_prompt = ChatPromptTemplate.from_messages(
    2. [
    3. ("system", "You are a wondrous wizard of math."),
    4. few_shot_prompt,
    5. ("human", "{input}"),
    6. ]
    7. )
    1. from langchain.chat_models import ChatAnthropic
    2. chain = final_prompt | ChatAnthropic(temperature=0.0)
    3. chain.invoke({"input": "What's 3+3?"})

    运行代码,输出结果:

    AIMessage(content=' 3 + 3 = 6', additional_kwargs={}, example=False)

    本文小结

    本文主要介绍了在对话模型(chat model)中,使用少样本prompt模版的两种方式:固定样本和动态样本。动态样本可以根据用户输入,动态地从所有样本中选择合适的样本,最终组成prompt输入给LLM,从而LLM可以更好地理解prompt,给出更加符合要求的答案。

    更多最新文章,请关注公众号:大白爱爬山

  • 相关阅读:
    private static final long serialVersionUID = 1L的作用是什么?
    Mock.js 的语法规范学习
    Red Hat 8中安装Python3.8.8和pip3
    442-C++基础语法(111-120)
    Spring Security加密和匹配
    扒一扒集成运放uA741的内部电路
    vue2中如何跨组件调用方法涉及路由跳转以及实现方式
    [watevrCTF 2019]Crypto over the intrawebs
    element-ui的form校验失败
    leetcode 63. 不同路径 II(dp)
  • 原文地址:https://blog.csdn.net/LClansefengbao/article/details/132864499