2026年7月2日 周四晚上19:30,报名腾讯会议了解“如何构建自进化的动态知识库(Brain)”(限30人)
免费POC, 零成本试错
FDE知识库

FDE知识库

学习大模型的前沿技术与行业落地应用


收藏

利用langchain 做大模型few-shot样本提示,包括固定和向量相似的动态样本筛选

发布日期:2024-08-25 21:42:01 浏览次数: 3015
作者:倪晶晶

微信搜一搜,关注“倪晶晶”

few-shot

相比大模型微调,在有些情况下,我们更想使用 Few-shot Learning 通过给模型喂相关样本示例,让模型能够提升相应任务的能力。

若仅仅通过提示就能完成任务,没有必要去微调大模型。

固定样本提示  VS 动态样本提示

固定样本提示:每次都用同样的样本提示去推理;动态样本提示:根据当前要推理的样本,基于向量相似度算法,在训练集中找出相似的样本作为提示去推理。

Few-shot Learning (少样本提示学习)

  • 定义:Few-shot learning 是通过给模型提供少量示例(例如 1-5 个)来进行任务的学习方式。这些示例通常包括输入和相应的输出。

  • 实现方式:在大多数情况下,few-shot learning 是在模型的输入中直接包含这些示例作为提示。这意味着模型本身没有经过任何额外的训练或调整。

  • 优点:可以快速适应新任务,无需额外的训练时间和资源。

Fixed Examples 固定样本

以聊天模型为例,

from langchain import PromptTemplate, FewShotPromptTemplate
from langchain_openai import ChatOpenAI

parser = StrOutputParser()

model = ChatOpenAI(model="gpt-4o-mini")
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

examples = [
    {"input""2 ? 2""output""4"},
    {"input""2 ? 3""output""5"},
]

? 代表加法。想让大模型根据给出的例子学会? 代表加法。

# This is a prompt template used to format each individual example.
example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human""{input}"),
        ("ai""{output}"),
    ]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)
few_shot_prompt.invoke({}).messages

Output:

[HumanMessage(content='2 ? 2'),
 AIMessage(content='4'),
 HumanMessage(content='2 ? 3'),
 AIMessage(content='5')]
few_shot_prompt.format()

Output:

'Human: 2 ? 2\nAI: 4\nHuman: 2 ? 3\nAI: 5'
final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system""You are a wondrous wizard of math."),
        few_shot_prompt,
        ("human""{input}"),
    ]
)
# chain = model | final_prompt
chain = final_prompt | model

chain.invoke({"input""What's 3 ? 3?"})

Output:

AIMessage(content='Based on the previous pattern, the ? operation appears to be addition. Therefore:\n\n\\[ 3 ? 3 = 3 + 3 = 6 \\]', response_metadata={'token_usage': {'completion_tokens'37'prompt_tokens'30'total_tokens'67}, 'model_name''gpt-4o-2024-05-13''system_fingerprint''''finish_reason''stop''logprobs'None}, id='run-xxx', usage_metadata={'input_tokens'30'output_tokens'37'total_tokens'67})

如上模型的输出结果所示,模型已经能够学到?是加法,并返回  3 ? 3 = 3 + 3 = 6 。

Dynamic few-shot prompting 动态样本提示

为什么要有一个动态的 few-shot 呢?

在上一节 Fixed Examples中,无论输入什么问题,都只使用固定的例子作为提示。

动态例子提示是:针对不同的问题,使用不同的例子进行提示。目的是为了提高模型的性能。

如果你想评估 动态few-shot的效果,那么便逐个遍历测试集的样本数据,根据测试集的样本使用向量相似度算法从训练集中拿到最相似的几个样本,再去做 few-shot prompting。

我们考虑在下一篇文章,为大家评估动态few-shot的效果。当前文章只是教学文章,不想整的太复杂。

在前一个章节中使用:
ChatPromptTemplateFewShotChatMessagePromptTemplate

在本章节中使用:
PromptTemplateFewShotPromptTemplate

上述一一对应,不能混用。

from langchain_core.prompts import PromptTemplate

example_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")

下述代码展示了 example_prompt 使用效果:

print(example_prompt.invoke(qa_examples[0]).text)

Output:

Question: Who lived longer, Muhammad Ali or Alan Turing?

            Are follow up questions needed here: Yes.
            Follow up: How old was Muhammad Ali when he died?
            Intermediate answer: Muhammad Ali was 74 years old when he died.
            Follow up: How old was Alan Turing when he died?
            Intermediate answer: Alan Turing was 41 years old when he died.
            So the final answer is: Muhammad Ali

下述的 qa_examples 是一个训练集,供模型推理时,在其中选择向量最相似的样本。

qa_examples = [
    {
        "question""Who lived longer, Muhammad Ali or Alan Turing?",
        "answer""""
            Are follow up questions needed here: Yes.
            Follow up: How old was Muhammad Ali when he died?
            Intermediate answer: Muhammad Ali was 74 years old when he died.
            Follow up: How old was Alan Turing when he died?
            Intermediate answer: Alan Turing was 41 years old when he died.
            So the final answer is: Muhammad Ali
            """
,
    },
    {
        "question""When was the founder of craigslist born?",
        "answer""""
            Are follow up questions needed here: Yes.
            Follow up: Who was the founder of craigslist?
            Intermediate answer: Craigslist was founded by Craig Newmark.
            Follow up: When was Craig Newmark born?
            Intermediate answer: Craig Newmark was born on December 6, 1952.
            So the final answer is: December 6, 1952
            """
,
    },
    {
        "question""Who was the maternal grandfather of George Washington?",
        "answer""""
            Are follow up questions needed here: Yes.
            Follow up: Who was the mother of George Washington?
            Intermediate answer: The mother of George Washington was Mary Ball Washington.
            Follow up: Who was the father of Mary Ball Washington?
            Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
            So the final answer is: Joseph Ball
            """
,
    },
    {
        "question""Are both the directors of Jaws and Casino Royale from the same country?",
        "answer""""
            Are follow up questions needed here: Yes.
            Follow up: Who is the director of Jaws?
            Intermediate Answer: The director of Jaws is Steven Spielberg.
            Follow up: Where is Steven Spielberg from?
            Intermediate Answer: The United States.
            Follow up: Who is the director of Casino Royale?
            Intermediate Answer: The director of Casino Royale is Martin Campbell.
            Follow up: Where is Martin Campbell from?
            Intermediate Answer: New Zealand.
            So the final answer is: No
            """
,
    },
]

example_prompt 作为参数 放入到 FewShotPromptTemplate 模版中,实现对 qa_examples中的数据进行封装。

from langchain_core.prompts import FewShotPromptTemplate

prompt = FewShotPromptTemplate(
    examples=qa_examples,
    example_prompt=example_prompt,
    # prefix="You are a helpful assistant.",
    suffix="Question: {input}",
    input_variables=["input"],

)

print(
    prompt.invoke({"input""Who was the father of Mary Ball Washington?"}).to_string()
)

这里是不使用向量筛选器prompt。若调用 invoke 方法,FewShotPromptTemplate会把qa_examples中所有的样本都封装好作为上下文。

Output:

Question: Who lived longer, Muhammad Ali or Alan Turing?

            Are follow up questions needed here: Yes.
            Follow up: How old was Muhammad Ali when he died?
            Intermediate answer: Muhammad Ali was 74 years old when he died.
            Follow up: How old was Alan Turing when he died?
            Intermediate answer: Alan Turing was 41 years old when he died.
            So the final answer is: Muhammad Ali
                        ......
Question: Who was the father of Mary Ball Washington?

使用编码模型构建向量筛选器,将qa_examples经过编码后,保存到 Chroma 向量数据库中。

from langchain_chroma import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings

example_selector = SemanticSimilarityExampleSelector.from_examples(
    # This is the list of examples available to select from.
    qa_examples,
    # This is the embedding class used to produce embeddings which are used to measure semantic similarity.
    OpenAIEmbeddings(),
    # This is the VectorStore class that is used to store the embeddings and do a similarity search over.
    Chroma,
    # This is the number of examples to produce.
    k=1,
)

使用 example_selector 根据用户输入的问题,找一个最相似的样本出来:

# Select the most similar example to the input.
question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"Examples most similar to the input: {question}")
for example in selected_examples:
    print("\n")
    print('【')
    for k, v in example.items():
        print(f"{k}{v}")
    print('】')

Output:

Examples most similar to the input: Who was the father of Mary Ball Washington?



answer: 
            Are follow up questions needed here: Yes.
            Follow up: Who was the mother of George Washington?
            Intermediate answer: The mother of George Washington was Mary Ball Washington.
            Follow up: Who was the father of Mary Ball Washington?
            Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
            So the final answer is: Joseph Ball

question: Who was the maternal grandfather of George Washington?

使用向量选择器example_selector和提示词封装器example_prompt,构建最终的prompt。

同时可以在 FewShotPromptTemplate 添加后缀和前缀。一般前缀用来添加系统提示词,后缀用来添加问题。

prompt = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    # prefix="You are a helpful assistant.",
    suffix="Question: {input}",
    input_variables=["input"],
)

print(
    prompt.invoke({"input""Who was the father of Mary Ball Washington?"}).to_string()
)

Output:

Question: Who was the maternal grandfather of George Washington?

            Are follow up questions needed here: Yes.
            Follow up: Who was the mother of George Washington?
            Intermediate answer: The mother of George Washington was Mary Ball Washington.
            Follow up: Who was the father of Mary Ball Washington?
            Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
            So the final answer is: Joseph Ball


Question: Who was the father of Mary Ball Washington?
chain = prompt | model
chain.invoke({"input""Who was the father of Mary Ball Washington?"})

Output:

AIMessage(content='The father of Mary Ball Washington was Joseph Ball.', response_metadata={'token_usage': {'completion_tokens'10'prompt_tokens'103'total_tokens'113}, 'model_name''gpt-4o-mini-2024-07-18''system_fingerprint''fp_0f03d4f0ee''finish_reason''stop''logprobs'None}, id='run-ae96f9c7-ac89-47ba-8074-69197b89bef5-0', usage_metadata={'input_tokens'103'output_tokens'10'total_tokens'113})

辅助

与huggingface 通过代理连接

import os
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询

扫码登录
登录即表示您同意《53AI网站服务协议》
服务协议

欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。

在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。

一、 定义

本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。

会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。

知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。

二、 账号注册与登录

登录方式:本网站支持以下登录方式,您可根据实际情况选择:

微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。

手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。

账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。

实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。

未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。

三、 服务内容与规范

知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。

服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。

禁止行为:您在使用服务时不得实施以下行为:

利用技术手段批量爬取、下载、转存知识库内容;

将知识库内容用于商业目的或未经授权地向第三方传播;

干扰本网站正常运行或侵犯其他用户合法权益;

发布违法违规信息或从事违反公序良俗的活动。

四、 知识产权声明

权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。

有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。

侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。

五、 个人信息保护

我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。

您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。

您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。

六、 免责声明

内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。

不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。

第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。

七、 违约责任

如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。

如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。

八、 法律适用与争议解决

本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。

因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。

九、 其他

本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。

本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。

我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。


已查阅