【Langchain实践】Few-shot examples for chat models 学习记录

构建向量存储

知识库examples是一个列表,列表元素是字典。与输入相关的文本放在from_text函数的第一个参数。embedding是嵌入模型,这部分如何使用本地模型,参考上一篇博客。metadatas是原始数据,也就是知识库。

to_vectorize = [" ".join(example.values()) for example in examples]
vectorstore = FAISS.from_texts(to_vectorize,embedding,metadatas=examples)

构建chat prompt的模版

首先要导入相关的库,ChatPromptTemplate和FewShotChatMessagePromptTemplate。
接着是选择器,选择器的构建在上一篇也有提到,这里采用的是语义相似度选择器,向量数据库是前一步构造的,k是返回的数量。
最后是构造chatprompt模版,人类输入是知识库中的对应的输入,ai输出是知识库对应的输出,字段要对应。
ChatPromptTemplate格式要正确。

from langchain_core.prompts import (
    ChatPromptTemplate,
    FewShotChatMessagePromptTemplate,
)


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

# Define the few-shot prompt.
few_shot_prompt = FewShotChatMessagePromptTemplate(
    # The input variables select the values to pass to the example_selector
    input_variables=["prompt"],
    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", "{prompt}"), ("ai", "{response}")]
    ),
)
# few_shot_prompt.format(prompt = "test your self")

final_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system_prompt),
        few_shot_prompt,
        ("human", "{prompt}"),
    ]
)
final_prompt.format(prompt="test yourself")

加载本地Chat模型

使用HuggingFacePipeline来加载从Huggingface上下载的模型。


# 使用本地模型进行交互
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

# 模型的id或者本地路径
model_id = "Qwen1.5-14B-Chat"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10)
hf = HuggingFacePipeline(pipeline=pipe)

与模型交互

与模型交互是一种链式的形式,数据从前往后传递。


chain = final_prompt | hf

question = "Love yourself!"

print(chain.invoke({"prompt": question}))

参考

[1] langchain官方文档 https://python.langchain.com/v0.1/docs/modules/model_io/prompts/few_shot_examples_chat/
[2] langchain官方文档 https://python.langchain.com/v0.1/docs/integrations/llms/huggingface_pipelines/

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值