admin管理员组

文章数量:1666728

FewShotPromptTemplate总结

加载本地模型完成嵌入

一般常用的模型是OpenAIEmbeddings,但是这要求很好的网络和一个OpenAI的key。因此能用本地模型实现嵌入是一个理想的替代方案。

langchain提供了多种嵌入的方式,这个网址里面包含了所有langchain支持的嵌入模型。
由于Huggingface支持的模型很多,加载本地模型采用HuggingFaceEmbedding的方式适用面更广。而且,如果目标语言是中文,需要嵌入中文效果非常好的模型。为此,使用本地模型完成嵌入的代码如下:

# 嵌入
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
# 加载从huggingface下载到本地的模型
embedding = HuggingFaceEmbeddings(model_name='path-on-machine')

注意:需要将huggingface仓库里的所有文件下载下来,尤其是1_Pooling文件夹,这个文件夹没有下载模型是无法从本地加载成功的。

构建模版

在prompt模版构建过程中,langchain采用的format格式化的方式填充数据。format的底层原理是f-string语法,通过识别{}来填充数据,而当模版中存在{}时,使用f-string来填充数据会报missing some input keys的错误。这个问题的解决方法在github参考上有讨论,详细见参考[2]。一种很直接的方式是换一种模版。langchain还支持其他两种模版,jinja2和mustache。

# langchain_core/prompts/few_shot.py#121
template_format: Literal["f-string", "mustache", "jinja2"] = "f-string"

使用jinja2模版语法的代码如下,jinja相关的语法见参考[3]:

context_prompt = """
问题:{{ prompt }}
回答:{{ response }}"""
example_prompt = PromptTemplate(input_variables=["prompt", "response"], template=context_prompt,template_format="jinja2")

向量数据库

langchain支持了很多的向量数据库,如Chroma、FAISS等,见参考[4]。如果一个向量数据不起作用,可以尝试另一个向量数据库。笔者在实践过程中,Chroma对于k设置为任何值都只返回第一个查询结果,然后重复k次,后面换了FAISS数据库才得以解决。

# 构造选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    # This is the list of examples available to select from.
    examples,
    # This is the embedding class used to produce embeddings which are used to measure semantic similarity.
    embedding,
    # This is the VectorStore class that is used to store the embeddings and do a similarity search over.
    FAISS,
    # Chroma只能返回一个结果
    # Chroma,
    # This is the number of examples to produce.
    k=3,
)

整个FewShotPromptTemplate的代码框架如下:

# 数据加载

# 嵌入
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
# 向量数据库
from langchain_chroma import Chroma
from langchain_community.vectorstores import FAISS

# 选择器
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
# prompt模板
from langchain_core.prompts.few_shot import FewShotPromptTemplate
from langchain_core.prompts.prompt import PromptTemplate


import pandas as pd
import json

# 原始数据
examples = [{"prompt":11,"response":22},{"prompt":333,"response":444}]

# 嵌入模型
embedding = HuggingFaceEmbeddings(model_name='./huggingface/text2vec-base-chinese')


context_prompt = """
问题:{{ prompt }}
回答:{{ response }}"""

example_prompt = PromptTemplate(input_variables=["prompt", "response"], template=context_prompt,template_format="jinja2")

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {{ input }}",
    input_variables=["input"],
    template_format = 'jinja2'
)

# print(prompt.format(input="今天天气真好"))

# 构造选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    # This is the list of examples available to select from.
    examples,
    # This is the embedding class used to produce embeddings which are used to measure semantic similarity.
    embedding,
    # This is the VectorStore class that is used to store the embeddings and do a similarity search over.
    FAISS,
    # Chroma只能返回一个结果
    # Chroma,
    # This is the number of examples to produce.
    k=3,
)
# Select the most similar example to the input.
# question = "who am I?"
# selected_examples = example_selector.select_examples({"prompt": question})
# print(f"Examples most similar to the input: {question}")
# for example in selected_examples:
#     print("\n")
#     print(example)
#     for k, v in example.items():
#         print(f"{k}: {v}")
# 使用FewShotPromptTemplate
prompt = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    suffix="Question: {{ input }}",
    input_variables=["input"],
    template_format = 'jinja2'
)

# # 字段
print(prompt.format(input="Love yourself!"))



参考

[1] 大规模文本嵌入的排行榜

[2] langchain的template构造过程缺少输入关键词missing input keys

[3] jinja2语法

[4] langchain中的vector store

本文标签: LangChainFewShotPromptTemplate