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

发布于:2024-05-10 ⋅ 阅读:(26) ⋅ 点赞:(0)

构建向量存储

知识库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/


网站公告

今日签到

点亮在社区的每一天
去签到