如何利用 distilabel 為 Argilla 2.0 建立聊天機械人
How we leveraged distilabel to create an Argilla 2.0 Chatbot
Hugging Face Blog 示範如何用 distilabel 為 Argilla 2.0 技術文件建立 RAG 聊天機械人。流程包括從文件建立切塊與合成查詢三元組、微調領域嵌入模型、建立向量資料庫,並將 Gradio 應用部署至 Hugging Face Spaces。聊天互動會記錄在 Argilla,供持續評估與改進。
文章串起文件切塊、合成查詢三元組、微調領域嵌入模型、向量檢索與對話評估,提供一套可複用的文件問答 RAG 實作流程。
撮要
瞭解如何為你選擇的工具(本例為 Argilla 2.0)建立聊天機械人,讓它理解技術文件並與使用者就相關內容對話。
本文會示範如何運用 distilabel,並微調特定領域的嵌入模型,打造既準確又吸引的對話模型。
本文會介紹為 Argilla 2.0 建立聊天機械人的流程。我們將會:
- 從技術文件建立合成資料集,以微調特定領域的嵌入模型;
- 建立向量資料庫,以儲存及檢索文件;以及
- 將最終聊天機械人部署到 Hugging Face Space,讓使用者與它互動,並把互動紀錄儲存在 Argilla,以便持續評估及改進。
按此處前往應用程式。
目錄
- 生成合成資料以微調特定領域的嵌入模型
- 下載及分塊資料
- 使用 distilabel 為嵌入模型生成合成資料
- 在 Argilla 探索資料集
- 微調嵌入模型
- 向量資料庫
- 連接資料庫
- 建立存放文件分塊的資料表
- 建立聊天機械人
- Gradio 應用程式
- 在 Hugging Face Spaces 部署聊天機械人應用程式
- 試玩聊天機械人
- 後續步驟
生成合成資料以微調自訂嵌入模型
想快速重温 RAG 嗎?可透過這份實用的入門筆記本複習基礎知識。我們等你準備好再繼續!
下載及分塊資料
資料分塊是指把文字資料切成易於處理的小段,每段約 256 個 token(稍後 RAG 會採用的分塊大小)。
先來看看第一步:處理目標儲存庫的文件。你可以使用 llama-index 等程式庫讀取儲存庫內容並解析 Markdown 檔案,令工作更簡單。具體而言,langchain 提供 MarkdownTextSplitter 等實用工具,而 llama-index 則提供 MarkdownNodeParser,協助你擷取所需資訊。如果想採用更直接的方法,可考慮使用 corpus-creator 應用程式,作者是 davanstrien。
為了令流程更簡單有效率,我們編寫了一個自訂 Python 指令碼,代你處理繁重工作。你可以在我們的儲存庫此處找到它。
此指令碼會自動從 GitHub 儲存庫擷取文件,並將其儲存為 Hugging Face Hub 上的資料集。更方便的是,它非常易用!以下看看如何執行:
python docs_dataset.py \
"argilla-io/argilla-python" \
--dataset-name "plaguss/argilla_sdk_docs_raw_unstructured"
這個指令碼雖然易用,你仍可透過額外參數按需要調整。不過,你必須提供兩項必要輸入:
存放文件的 GitHub 儲存庫路徑
要用來儲存資料集的 Hugging Face Hub 資料集 ID
提供這些必要參數後,指令碼便會處理其餘工作。以下是背後的流程:
指令碼會從指定的 GitHub 儲存庫將文件下載至本機目錄。預設會在
/docs目錄尋找文件,你也可以指定其他路徑。從已下載的文件中擷取所有 Markdown 檔案。
將擷取出的 Markdown 檔案分成易於處理的小段。
最後,將整理好的資料集推送至 Hugging Face Hub,供後續使用。
為了讓你更瞭解指令碼的內部運作,以下程式碼片段概述了核心邏輯:
# The function definitions are omitted for brevity, visit the script for more info!
from github import Github
gh = Github()
repo = gh.get_repo("repo_name")
# Download the folder
download_folder(repo, "/folder/with/docs", "dir/to/download/docs")
# Extract the markdown files from the downloaded folder with the documentation from the GitHub repository
md_files = list(docs_path.glob("**/*.md"))
# Loop to iterate over the files and generate chunks from the text pieces
data = create_chunks(md_files)
# Create a dataset to push it to the hub
create_dataset(data, repo_name="name/of/the/dataset")
指令碼包含簡短函數,用於下載文件、將 Markdown 檔案分塊,以及建立資料集。要加入更多功能或採用更複雜的分塊策略,應該也相當直接。
你可以查看可用參數:
按一下查看 docs_dataset.py 説明訊息
$ python docs_dataset.py -h
usage: docs_dataset.py [-h] [--dataset-name DATASET_NAME] [--docs_folder DOCS_FOLDER] [--output_dir OUTPUT_DIR] [--private | --no-private] repo [repo ...]
Download the docs from a github repository and generate a dataset from the markdown files. The dataset will be pushed to the hub.
positional arguments:
repo Name of the repository in the hub. For example 'argilla-io/argilla-python'.
options:
-h, --help show this help message and exit
--dataset-name DATASET_NAME
Name to give to the new dataset. For example 'my-name/argilla_sdk_docs_raw'.
--docs_folder DOCS_FOLDER
Name of the docs folder in the repo, defaults to 'docs'.
--output_dir OUTPUT_DIR
Path to save the downloaded files from the repo (optional)
--private, --no-private
Whether to keep the repository private or not. Defaults to False.
使用 distilabel 為嵌入模型生成合成資料
我們會根據文件生成合成問題,確保每個文件分塊都能回答相應問題;亦會生成容易區分的無關問題,作為困難負例。之後便可用這些問題、困難負例及文件,組成微調資料集所需的三元組。
完整的流程指令碼可在參考儲存庫的 pipeline_docs_queries.py 查看;現在逐一看看各個步驟:
load_data:
流程的第一步是載入包含重要文件分塊的資料集。仔細查看後可見,存放這些分塊的欄位名為 chunks。為了讓模型順利運作,我們需要重新命名此欄位,改為 anchor,因為後續步驟會以此作為輸入。我們會使用 output_mappings 完成欄位轉換:
load_data = LoadDataFromHub(
name="load_data",
repo_id="plaguss/argilla_sdk_docs_raw_unstructured",
output_mappings={"chunks": "anchor"},
batch_size=10,
)
generate_sentence_pair
現在來到流程中最有趣的部分:把文件片段轉化為合成查詢。這時 GenerateSentencePair 任務便是主角。這個強大的任務可用多種方式生成高品質句子配對,建議你查看文件,充分發揮其功能。
在這個案例中,我們會運用 GenerateSentencePair 的功能建立合成查詢,從而提升模型效能。以下深入看看如何設定此任務以達成目標。
llm = InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3-70B-Instruct",
)
generate_sentence_pair = GenerateSentencePair(
name="generate_sentence_pair",
triplet=True, # Generate positive and negative
action="query",
context="The generated sentence has to be related with Argilla, a data annotation tool for AI engineers and domain experts.",
llm=llm,
input_batch_size=10,
output_mappings={"model_name": "model_name_query"},
)
以下逐項拆解上方的程式碼片段。
設定 triplet=True 後,任務便會產生一系列三元組,包括 anchor、正例句子及負例句子。正如 Sentence Transformers 程式庫的訓練概覽所述,這種格式非常適合用於微調。
action="query" 參數是此任務的重要部分,因為它會指示 LLM 為正例句子生成查詢。文件分塊就在這一步轉化為有意義的查詢。
為進一步協助模型,我們加入了 context 引數。當 anchor 句子缺乏足夠背景(簡短的文件分塊經常如此)時,這個引數會向 LLM 提供額外資訊。
最後,我們會使用 meta-llama/Meta-Llama-3-70B-Instruct 模型,並透過 InferenceEndpointsLLM 元件存取。這項選擇讓我們能運用該模型的能力,生成高品質合成查詢,最終提升自身模型的效能。
multiply_queries
使用 GenerateSentencePair 步驟後,我們得到的訓練樣本數與分塊數相同,本例為 251 個。不過,我們認為這些樣本可能不足以微調自訂模型,讓它準確掌握此特定用途的細節。
為解決這個限制,我們會使用另一個 LLM 生成更多查詢,擴大訓練資料集,為模型提供更豐富的學習基礎。
這便帶我們來到流程的下一步:自訂的 MultipleQueries Task,用來進一步擴充資料集。
multiply_queries = MultipleQueries(
name="multiply_queries",
num_queries=3,
system_prompt=(
"You are an AI assistant helping to generate diverse examples. Ensure the "
"generated queries are all in separated lines and preceded by a dash. "
"Do not generate anything else or introduce the task."
),
llm=llm,
input_batch_size=10,
input_mappings={"query": "positive"},
output_mappings={"model_name": "model_name_query_multiplied"},
)
現在深入看看這個用來擴充訓練資料集的自訂 Task 設定。關鍵是 num_queries 參數,本例設為 3。這表示每個樣本會額外生成三個「正例」查詢;假設部分樣本生成失敗,資料集規模仍可有效增加至約四倍。
為確保大型語言模型(LLM)不偏離方向,我們編寫了 system_prompt,清楚説明指示。由於所選模型能力強,而樣本亦簡單,因此無須採用結構化生成技術;但在較複雜的情境中,這種方法可能很有用。
想了解自訂 Task 的內部運作嗎?按一下下方的下拉區域,查看完整定義:
MultipleQueries 定義
multiply_queries_template = (
"Given the following query:\n{original}\nGenerate {num_queries} similar queries by varying "
"the tone and the phrases slightly. "
"Ensure the generated queries are coherent with the original reference and relevant to the context of data annotation "
"and AI dataset development."
)
class MultipleQueries(Task):
system_prompt: Optional[str] = None
num_queries: int = 1
@property
def inputs(self) -> List[str]:
return ["query"]
def format_input(self, input: Dict[str, Any]) -> ChatType:
prompt = [
{
"role": "user",
"content": multiply_queries_template.format(
original=input["query"],
num_queries=self.num_queries
),
},
]
if self.system_prompt:
prompt.insert(0, {"role": "system", "content": self.system_prompt})
return prompt
@property
def outputs(self) -> List[str]:
return ["queries", "model_name"]
def format_output(
self, output: Union[str, None], input: Dict[str, Any]
) -> Dict[str, Any]:
queries = output.split("- ")
if len(queries) > self.num_queries:
queries = queries[1:]
queries = [q.strip() for q in queries]
return {"queries": queries}
merge_columns
流程接近尾聲時,重點轉為資料處理。我們的最終目標是建立整理完善的資料集,每列包含適合微調的三元組。不過,生成多個查詢後,資料集現在有兩個不同欄位:positive 和 queries。positive 欄位以單一字串保存原始查詢,而 queries 欄位則以字串清單儲存同一項目所生成的額外查詢。
為了把這兩個欄位合併成一個完整清單,我們會使用 MergeColumns 步驟,將原始查詢與生成的查詢合併,形成統一的:
merge_columns = MergeColumns(
name="merge_columns",
columns=["positive", "queries"],
output_column="positive"
)
expand_columns
最後,我們使用 ExpandColumns,把先前的正例欄位拆分到不同列。結果是每個 positive 查詢各佔一列,而 anchor 和 negative 欄位則會複製,以配合展開後的正例查詢。經過這項資料處理,便會得到適合微調的理想資料集結構:
expand_columns = ExpandColumns(columns=["positive"])
按一下下拉區域查看完整流程定義:
Distilabel 流程
from pathlib import Path
from typing import Any, Dict, List, Union, Optional
from distilabel.pipeline import Pipeline
from distilabel.steps import LoadDataFromHub
from distilabel.llms import InferenceEndpointsLLM
from distilabel.steps.tasks import GenerateSentencePair
from distilabel.steps.tasks.base import Task
from distilabel.steps.tasks.typing import ChatType
from distilabel.steps import ExpandColumns, CombineKeys
multiply_queries_template = (
"Given the following query:\n{original}\nGenerate {num_queries} similar queries by varying "
"the tone and the phrases slightly. "
"Ensure the generated queries are coherent with the original reference and relevant to the context of data annotation "
"and AI dataset development."
)
class MultipleQueries(Task):
system_prompt: Optional[str] = None
num_queries: int = 1
@property
def inputs(self) -> List[str]:
return ["query"]
def format_input(self, input: Dict[str, Any]) -> ChatType:
prompt = [
{
"role": "user",
"content": multiply_queries_template.format(
original=input["query"],
num_queries=self.num_queries
),
},
]
if self.system_prompt:
prompt.insert(0, {"role": "system", "content": self.system_prompt})
return prompt
@property
def outputs(self) -> List[str]:
return ["queries", "model_name"]
def format_output(
self, output: Union[str, None], input: Dict[str, Any]
) -> Dict[str, Any]:
queries = output.split("- ")
if len(queries) > self.num_queries:
queries = queries[1:]
queries = [q.strip() for q in queries]
return {"queries": queries}
with Pipeline(
name="embedding-queries",
description="Generate queries to train a sentence embedding model."
) as pipeline:
load_data = LoadDataFromHub(
name="load_data",
repo_id="plaguss/argilla_sdk_docs_raw_unstructured",
output_mappings={"chunks": "anchor"},
batch_size=10,
)
llm = InferenceEndpointsLLM(
model_id="meta-llama/Meta-Llama-3-70B-Instruct",
tokenizer_id="meta-llama/Meta-Llama-3-70B-Instruct",
)
generate_sentence_pair = GenerateSentencePair(
name="generate_sentence_pair",
triplet=True, # Generate positive and negative
action="query",
context="The generated sentence has to be related with Argilla, a data annotation tool for AI engineers and domain experts.",
llm=llm,
input_batch_size=10,
output_mappings={"model_name": "model_name_query"},
)
multiply_queries = MultipleQueries(
name="multiply_queries",
num_queries=3,
system_prompt=(
"You are an AI assistant helping to generate diverse examples. Ensure the "
"generated queries are all in separated lines and preceded by a dash. "
"Do not generate anything else or introduce the task."
),
llm=llm,
input_batch_size=10,
input_mappings={"query": "positive"},
output_mappings={"model_name": "model_name_query_multiplied"},
)
merge_columns = MergeColumns(
name="merge_columns",
columns=["positive", "queries"],
output_column="positive"
)
expand_columns = ExpandColumns(
columns=["positive"],
)
(
load_data
>> generate_sentence_pair
>> multiply_queries
>> merge_columns
>> expand_columns
)
if __name__ == "__main__":
pipeline_parameters = {
"generate_sentence_pair": {
"llm": {
"generation_kwargs": {
"temperature": 0.7,
"max_new_tokens": 512,
}
}
},
"multiply_queries": {
"llm": {
"generation_kwargs": {
"temperature": 0.7,
"max_new_tokens": 512,
}
}
}
}
distiset = pipeline.run(
parameters=pipeline_parameters
)
distiset.push_to_hub("plaguss/argilla_sdk_docs_queries")
在 Argilla 探索資料集
資料集生成後,現在可以使用 Argilla 深入檢視,並按需要加以完善。首先可查看我們的 argilla_datasets.ipynb 筆記本,當中逐步説明如何將資料集上載至 Argilla。
如果你尚未設定 Argilla 執行個體,不用擔心!按照文件中的簡易指南,建立一個載有 Argilla 的 Hugging Face Space。Space 啟動後,只要更新 api_url 指向該 Space,即可連線:
import argilla as rg
client = rg.Argilla(
api_url="https://plaguss-argilla-sdk-chatbot.hf.space",
api_key="YOUR_API_KEY"
)
包含技術文件分塊的 Argilla 資料集
Argilla 執行個體運作正常後,便可進入下一步:設定資料集的 Settings。好消息是,以下建立的預設 Settings 應可直接配合你的用途,無須再作調整:
settings = rg.Settings(
guidelines="Review the chunks of docs.",
fields=[
rg.TextField(
name="filename",
title="Filename where this chunk was extracted from",
use_markdown=False,
),
rg.TextField(
name="chunk",
title="Chunk from the documentation",
use_markdown=False,
),
],
questions=[
rg.LabelQuestion(
name="good_chunk",
title="Does this chunk contain relevant information?",
labels=["yes", "no"],
)
],
)
仔細看看我們建立的資料集結構。當中的 filename 和 chunk 欄位分別存放解析後的檔名和生成的分塊。為進一步改善資料集,我們可以定義一個簡單的標籤問題 good_chunk,讓人手標記每個分塊是否有用。這種人機協作方式有助完善自動生成流程。備妥這些基本元素後,就可以建立資料集:
dataset = rg.Dataset(
name="argilla_sdk_docs_raw_unstructured",
settings=settings,
client=client,
)
dataset.create()
現在從 Hugging Face Hub 取回早前建立的資料集。還記得我們在資料分塊章節生成的資料集嗎?我們會下載該資料集,並擷取後續所需的欄位:
from datasets import load_dataset
data = (
load_dataset("plaguss/argilla_sdk_docs_raw_unstructured", split="train")
.select_columns(["filename", "chunks"])
.to_list()
)
我們來到最後一個里程碑!現在把所有內容整合起來,將記錄寫入 Argilla。這樣便可在 Argilla 介面檢視資料集,以清晰直觀的方式探索及操作資料:
dataset.records.log(records=data, mapping={"filename": "filename", "chunks": "chunk"})
你預期會看到類似以下的例子:
包含三元組以微調嵌入模型的 Argilla 資料集
現在可用我們在上一節生成、已準備好微調的資料集,重複這個流程。 幸好步驟很簡單:只要下載相關資料集,並以指定名稱上載至 Argilla 即可。詳細操作請參閲 Jupyter 筆記本,當中載有所有必要指示:
settings = rg.Settings(
guidelines="Review the chunks of docs.",
fields=[
rg.TextField(
name="anchor",
title="Anchor (Chunk from the documentation).",
use_markdown=False,
),
rg.TextField(
name="positive",
title="Positive sentence that queries the anchor.",
use_markdown=False,
),
rg.TextField(
name="negative",
title="Negative sentence that may use similar words but has content unrelated to the anchor.",
use_markdown=False,
),
],
questions=[
rg.LabelQuestion(
name="is_positive_relevant",
title="Is the positive query relevant?",
labels=["yes", "no"],
),
rg.LabelQuestion(
name="is_negative_irrelevant",
title="Is the negative query irrelevant?",
labels=["yes", "no"],
)
],
)
仔細看看資料集結構,其中包含三個重要的 TextFields:anchor、positive 和 negative。anchor 欄位代表文字分塊本身;positive 欄位則放置可根據 anchor 文字回答的查詢。相反,negative 欄位存放無關查詢,作為三元組中的負例。正例和負例問題對模型區分樣本及學習有效嵌入至關重要。
以下圖片展示一個例子:
目前設定的資料集主要用於探索資料,但我們還可以更進一步。自訂這些設定後,我們可以找出並修正錯誤樣本、改善生成問題的質素,並透過反覆迭代讓資料集更符合需要。
用於追蹤聊天機械人對話的 Argilla 資料集
現在建立最後一個資料集,專門追蹤使用者與聊天機械人的互動。注意:完成 Gradio 應用程式後,你可能想回來重看本節,以更全面瞭解整體背景。現在先看看此資料集的 Settings:
settings_chatbot_interactions = rg.Settings(
guidelines="Review the user interactions with the chatbot.",
fields=[
rg.TextField(
name="instruction",
title="User instruction",
use_markdown=True,
),
rg.TextField(
name="response",
title="Bot response",
use_markdown=True,
),
],
questions=[
rg.LabelQuestion(
name="is_response_correct",
title="Is the response correct?",
labels=["yes", "no"],
),
rg.LabelQuestion(
name="out_of_guardrails",
title="Did the model answered something out of the ordinary?",
description="If the model answered something unrelated to Argilla SDK",
labels=["yes", "no"],
),
rg.TextQuestion(
name="feedback",
title="Let any feedback here",
description="This field should be used to report any feedback that can be useful",
required=False
),
],
metadata=[
rg.TermsMetadataProperty(
name="conv_id",
title="Conversation ID",
),
rg.IntegerMetadataProperty(
name="turn",
min=0,
max=100,
title="Conversation Turn",
)
]
)
在此資料集中,我們會定義兩個必要欄位:instruction 和 response。instruction 欄位會儲存初始查詢;如果對話繼續,亦會包含截至當時的完整對話記錄。另一方面,response 欄位會存放聊天機械人最近一次的回覆。為方便評估及收集意見,我們會加入三個問題:一個評估回覆是否正確,另一個判斷模型有否偏離主題,還有一個供使用者選填的回覆意見欄。另外會加入兩個中繼資料屬性,方便篩選及分析對話:唯一的對話 ID,以及對話中的回合編號。
以下圖片展示一個例子:
當聊天機械人累積足夠使用者互動後,此資料集便可成為完善及強化模型的重要資源,讓我們根據真實互動反覆改進其效能。
微調嵌入模型
自訂嵌入模型的資料集已準備就緒,現在開始深入瞭解訓練流程。
我們會參考 train_embedding.ipynb 筆記本進行這一步,內容參考了 Philipp Schmid 有關為 RAG 微調嵌入模型的網誌文章。該文全面介紹了整個流程,而本文會聚焦於此用途中特有的主要差異及細節。
如要深入瞭解背後的決策及詳細流程,請參閲原網誌文章,並查看筆記本中的逐步説明。
準備嵌入資料集
首先下載資料集,並選取必要欄位;這些欄位名稱剛好已符合 Sentence Transformers 的慣例。接著為每個樣本加入唯一 ID 欄,並把資料集分成訓練集和測試集,分配 90% 作訓練、10% 作測試。最後將整理好的資料集轉成 JSON 檔,供訓練器用來微調模型:
from datasets import load_dataset
# Load dataset from the hub
dataset = (
load_dataset("plaguss/argilla_sdk_docs_queries", split="train")
.select_columns(["anchor", "positive", "negative"]) # Select the relevant columns
.add_column("id", range(len(dataset))) # Add an id column to the dataset
.train_test_split(test_size=0.1) # split dataset into a 10% test set
)
# Save datasets to disk
dataset["train"].to_json("train_dataset.json", orient="records")
dataset["test"].to_json("test_dataset.json", orient="records")
載入基準模型
資料集準備妥當後,現在載入基準模型,作為微調流程的起點。我們會使用參考網誌文章中的同一模型,確保自訂嵌入模型的開發有一致的基礎:
from sentence_transformers import SentenceTransformerModelCardData, SentenceTransformer
model = SentenceTransformer(
"BAAI/bge-base-en-v1.5",
model_card_data=SentenceTransformerModelCardData(
language="en",
license="apache-2.0",
model_name="BGE base ArgillaSDK Matryoshka",
),
)
定義損失函數
根據資料集結構,我們會使用 TripletLoss 函數,較適合處理 (anchor-positive-negative) 三元組。此外亦會結合 MatryoshkaLoss;這種強大的損失函數已展現出良好成效。如要深入瞭解 MatryoshkaLoss,可參閲這篇文章:
from sentence_transformers.losses import MatryoshkaLoss, TripletLoss
inner_train_loss = TripletLoss(model)
train_loss = MatryoshkaLoss(
model, inner_train_loss, matryoshka_dims=[768, 512, 256, 128, 64]
)
定義訓練策略
基準模型和損失函數已準備就緒,現在要定義微調流程所需的訓練參數。由於這項工作是在 Apple M2 Pro 上進行,因此我們需要作出一些調整,確保訓練順利。
為配合機器有限的資源,我們會把 per_device_train_batch_size 和 per_device_eval_batch_size 調低,與原網誌文章的設定不同。此外,這部裝置不支援 tf32 和 bf16 精度選項,因此必須移除。最後,我們會替換 adamw_torch_fused 最佳化器;該最佳化器可在 Google Colab 筆記本中使用,以加快訓練。完成這些修改後,便可微調模型:
from sentence_transformers import SentenceTransformerTrainingArguments
# Define training arguments
args = SentenceTransformerTrainingArguments(
output_dir="bge-base-argilla-sdk-matryoshka", # output directory and hugging face model ID
num_train_epochs=3, # number of epochs
per_device_train_batch_size=8, # train batch size
gradient_accumulation_steps=4, # for a global batch size of 512
per_device_eval_batch_size=4, # evaluation batch size
warmup_ratio=0.1, # warmup ratio
learning_rate=2e-5, # learning rate, 2e-5 is a good value
lr_scheduler_type="cosine", # use constant learning rate scheduler
eval_strategy="epoch", # evaluate after each epoch
save_strategy="epoch", # save after each epoch
logging_steps=5, # log every 10 steps
save_total_limit=1, # save only the last 3 models
load_best_model_at_end=True, # load the best model when training ends
metric_for_best_model="eval_dim_512_cosine_ndcg@10", # optimizing for the best ndcg@10 score for the 512 dimension
)
訓練並儲存最終模型
from sentence_transformers import SentenceTransformerTrainer
trainer = SentenceTransformerTrainer(
model=model, # bg-base-en-v1
args=args, # training arguments
train_dataset=train_dataset.select_columns(
["anchor", "positive", "negative"]
), # training dataset
loss=train_loss,
evaluator=evaluator,
)
# Start training, the model will be automatically saved to the hub and the output directory
trainer.train()
# Save the best model
trainer.save_model()
# Push model to hub
trainer.model.push_to_hub("bge-base-argilla-sdk-matryoshka")
大功告成!現在可以查看新模型:plaguss/bge-base-argilla-sdk-matryoshka。也請細閲資料集卡片,當中載有模型的重要資訊及深入見解。
不只如此!下一節會測試模型,看看它實際運作的效果。
向量資料庫
到目前為止,我們已建立資料集並為 RAG 聊天機械人微調模型,取得不少進展。現在要建構向量資料庫,讓聊天機械人有效儲存及檢索相關資訊。
選擇向量資料庫時有很多方案。為求簡單直接,我們會使用 lancedb,這是一個輕量級嵌入式資料庫,毋須伺服器,與 SQLite 類似。稍後會看到,lancedb 可建立簡單檔案來儲存嵌入向量,方便搬移並快速擷取資料,非常適合此用途。
請參閲配套筆記本 vector_db.ipynb 跟隨操作。筆記本會詳細介紹如何建立及使用向量資料庫。
連接資料庫
安裝相依套件後,初始化資料庫:
import lancedb
# Create a database locally called `lancedb`
db = lancedb.connect("./lancedb")
執行程式碼後,目前工作目錄中應會出現新資料夾,表示向量資料庫已成功建立。
初始化微調後的模型
向量資料庫設定完成後,現在載入微調後的模型。我們會使用 sentence-transformers 登錄表載入模型,啟用其功能並準備使用:
import torch
from lancedb.embeddings import get_registry
model_name = "plaguss/bge-base-argilla-sdk-matryoshka"
device = "mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu"
model = get_registry().get("sentence-transformers").create(name=model_name, device=device)
建立存放文件分塊的資料表
載入微調後的模型後,就可以建立儲存嵌入向量的資料表。為定義資料表結構,我們會使用 LanceModel(類似 pydantic.BaseModel),以完善方式表示 Docs 實體。
from lancedb.pydantic import LanceModel, Vector
class Docs(LanceModel):
query: str = model.SourceField()
text: str = model.SourceField()
vector: Vector(model.ndims()) = model.VectorField()
table_name = "docs"
table = db.create_table(table_name, schema=Docs)
上一段程式碼為建立含有三個必要欄位的資料表做好準備:
query:用來儲存合成查詢text:存放已分塊的文件文字vector:使用微調後模型的維度,準備儲存嵌入向量
資料表結構準備妥當後,現在可以操作資料表。
填入資料表
資料表結構已建立,現在可以填入資料。載入包含查詢的最終資料集,並連同相應嵌入向量匯入資料庫。這個重要步驟會令向量資料庫正式運作,讓聊天機械人有效儲存及檢索相關資訊:
ds = load_dataset("plaguss/argilla_sdk_docs_queries", split="train")
batch_size = 50
for batch in tqdm.tqdm(ds.iter(batch_size), total=len(ds) // batch_size):
embeddings = model.generate_embeddings(batch["positive"])
df = pd.DataFrame.from_dict({"query": batch["positive"], "text": batch["anchor"], "vector": embeddings})
table.add(df)
在上一段程式碼中,我們以批次方式遍歷資料集,使用微調後的模型為 positive 欄中的合成查詢生成嵌入向量。然後建立 Pandas dataframe,包含 query、text 和 vector 欄位。這個 dataframe 依次結合 positive 欄、anchor 欄及新生成的嵌入向量。
現在測試一下向量資料庫!以「如何取得目前使用者?」(使用 Argilla SDK)作為範例查詢,我們會用自訂嵌入模型生成其嵌入向量,再以 cosine 指標衡量相似度,搜尋資料表中最相似的 3 項結果。最後擷取相關的 text 欄位,即最符合查詢的文件分塊:
query = "How can I get the current user?"
embedded_query = model.generate_embeddings([query])
retrieved = (
table
.search(embedded_query[0])
.metric("cosine")
.limit(3)
.select(["text"]) # Just grab the chunk to use for context
.to_list()
)
按一下查看結果
結果如下:
>>> retrieved
[{'text': 'python\nuser = client.users("my_username")\n\nThe current user of the rg.Argilla client can be accessed using the me attribute:\n\npython\nclient.me\n\nClass Reference\n\nrg.User\n\n::: argilla_sdk.users.User\n options:\n heading_level: 3',
'_distance': 0.1881886124610901},
{'text': 'python\nuser = client.users("my_username")\n\nThe current user of the rg.Argilla client can be accessed using the me attribute:\n\npython\nclient.me\n\nClass Reference\n\nrg.User\n\n::: argilla_sdk.users.User\n options:\n heading_level: 3',
'_distance': 0.20238929986953735},
{'text': 'Retrieve a user\n\nYou can retrieve an existing user from Argilla by accessing the users attribute on the Argilla class and passing the username as an argument.\n\n```python\nimport argilla_sdk as rg\n\nclient = rg.Argilla(api_url="", api_key="")\n\nretrieved_user = client.users("my_username")\n```',
'_distance': 0.20401990413665771}]
>>> print(retrieved[0]["text"])
python
user = client.users("my_username")
The current user of the rg.Argilla client can be accessed using the me attribute:
python
client.me
Class Reference
rg.User
::: argilla_sdk.users.User
options:
heading_level: 3
深入查看資料集的第一列,看看能找到甚麼。乍看之下,它似乎包含與查詢相關的資訊,正合預期。要取得目前使用者,可使用 client.me 方法。不過亦可見一些多餘內容,可能是所採用的分塊策略所致。這個策略雖然有效,仍可進一步改善。透過在 Argilla 檢視資料集,我們可以更瞭解如何最佳化分塊方式,最終令資料集更精簡。目前而言,這是值得繼續完善的良好起點。
將資料庫儲存至 Hugging Face Hub
現在有了資料庫,我們會把它作為另一個成品儲存在資料集儲存庫。你可以前往儲存庫查看可用函數,實際上只要執行以下函數即可:
import Path
import os
local_dir = Path.home() / ".cache/argilla_sdk_docs_db"
upload_database(
local_dir / "lancedb",
repo_id="plaguss/argilla_sdk_docs_queries",
token=os.getenv("HF_API_TOKEN")
)
資料庫儲存流程只差最後一個指令!執行該函數後,便會建立名為 lancedb.tar.gz 的新檔案,將向量資料庫打包妥當。你可在 Hugging Face Hub 上的 plaguss/argilla_sdk_docs_queries 儲存庫預覽該檔案,它與其他必要檔案一同存放。
db_path = download_database(repo_id)
現在到了驗收時刻!資料庫成功下載後,我們可以確認一切正常。檔案預設會存放在 Path.home() / ".cache/argilla_sdk_docs_db",也可輕易自訂位置。再次連線後,便可檢查運作是否符合預期:
db = lancedb.connect(str(db_path))
table = db.open_table(table_name)
query = "how can I delete users?"
retrieved = (
table
.search(query)
.metric("cosine")
.limit(1)
.to_pydantic(Docs)
)
for d in retrieved:
print("======\nQUERY\n======")
print(d.query)
print("======\nDOC\n======")
print(d.text)
# ======
# QUERY
# ======
# Is it possible to remove a user from Argilla by utilizing the delete function on the User class?
# ======
# DOC
# ======
# Delete a user
# You can delete an existing user from Argilla by calling the delete method on the User class.
# ```python
# import argilla_sdk as rg
# client = rg.Argilla(api_url="", api_key="")
# user_to_delete = client.users('my_username')
# deleted_user = user_to_delete.delete()
# ```
文件檢索資料庫已完成,接下來建立應用程式!
建立聊天機械人
聊天機械人所需的元件都已備妥;現在要把它們連接起來,並透過介面提供使用。
Gradio 應用程式
現在讓 RAG 應用程式動起來!使用 gradio,即可輕鬆建立聊天機械人應用程式。本例會設計一個簡單而有效的介面,展示聊天機械人的功能。要查看實際效果,可參閲 GitHub 上 Argilla SDK Chatbot 儲存庫中的 app.py 指令碼。
深入探討聊天機械人應用程式的建構細節前,先退一步看看最後成果。只用了幾行程式碼,我們便建立出易用的介面,讓 RAG 聊天機械人投入運作。
import gradio as gr
gr.ChatInterface(
chatty,
chatbot=gr.Chatbot(height=600),
textbox=gr.Textbox(placeholder="Ask me about the new argilla SDK", container=False, scale=7),
title="Argilla SDK Chatbot",
description="Ask a question about Argilla SDK",
theme="soft",
examples=[
"How can I connect to an argilla server?",
"How can I access a dataset?",
"How can I get the current user?"
],
cache_examples=True,
retry_btn=None,
).launch()
就是這樣!如果你想進一步瞭解如何建立自己的聊天機械人,記得查看 Gradio 的優秀指南:使用 Gradio 建立聊天機械人。當中資料豐富,助你迅速建立自己的聊天機械人。
現在深入瞭解 app.py 指令碼的內部運作。我們會拆解主要元件,聚焦於令聊天機械人運作的必要部分。為求簡潔,部分細節會略過。
首先看看 Database 類別,它是聊天機械人知識及功能的核心。這個元件負責儲存及擷取對話所需資料,作用至關重要:
按一下查看 Database 類別
class Database:
def __init__(self, settings: Settings) -> None:
self.settings = settings
self._table: lancedb.table.LanceTable = self.get_table_from_db()
def get_table_from_db(self) -> lancedb.table.LanceTable:
lancedb_db_path = self.settings.LOCAL_DIR / self.settings.LANCEDB
if not lancedb_db_path.exists():
lancedb_db_path = download_database(
self.settings.REPO_ID,
lancedb_file=self.settings.LANCEDB_FILE_TAR,
local_dir=self.settings.LOCAL_DIR,
token=self.settings.TOKEN,
)
db = lancedb.connect(str(lancedb_db_path))
table = db.open_table(self.settings.TABLE_NAME)
return table
def retrieve_doc_chunks(
self, query: str, limit: int = 12, hard_limit: int = 4
) -> str:
# Embed the query to use our custom model instead of the default one.
embedded_query = model.generate_embeddings([query])
field_to_retrieve = "text"
retrieved = (
self._table.search(embedded_query[0])
.metric("cosine")
.limit(limit)
.select([field_to_retrieve]) # Just grab the chunk to use for context
.to_list()
)
return self._prepare_context(retrieved, hard_limit)
@staticmethod
def _prepare_context(retrieved: list[dict[str, str]], hard_limit: int) -> str:
# We have repeated questions (up to 4) for a given chunk, so we may get repeated chunks.
# Request more than necessary and filter them afterwards
responses = []
unique_responses = set()
for item in retrieved:
chunk = item["text"]
if chunk not in unique_responses:
unique_responses.add(chunk)
responses.append(chunk)
context = ""
for i, item in enumerate(responses[:hard_limit]):
if i > 0:
context += "\n\n"
context += f"---\n{item}"
return context
有了 Database 類別,聊天機械人的對話流程便成功連接到資料庫中儲存的知識。現在把所有部分整合起來!下載嵌入模型後(指令碼會自動完成),即可初始化 Database 類別,將資料庫部署至指定位置,本例即 Hugging Face Space。
這是聊天機械人開發過程中的重要里程碑。資料庫已整合並準備就緒,距離發揮聊天機械人的完整潛力只差一步。
database = Database(settings=settings) # The settings can be seen in the following snippet
context = database.retrieve_doc_chunks("How can I delete a user?", limit=2, hard_limit=1)
>>> print(context)
# ---
# Delete a user
# You can delete an existing user from Argilla by calling the delete method on the User class.
# ```python
# import argilla_sdk as rg
# client = rg.Argilla(api_url="", api_key="")
# user_to_delete = client.users('my_username')
# deleted_user = user_to_delete.delete()
# ```
按一下查看 Settings 類別
@dataclass
class Settings:
LANCEDB: str = "lancedb"
LANCEDB_FILE_TAR: str = "lancedb.tar.gz"
TOKEN: str = os.getenv("HF_API_TOKEN")
LOCAL_DIR: Path = Path.home() / ".cache/argilla_sdk_docs_db"
REPO_ID: str = "plaguss/argilla_sdk_docs_queries"
TABLE_NAME: str = "docs"
MODEL_NAME: str = "plaguss/bge-base-argilla-sdk-matryoshka"
DEVICE: str = (
"mps"
if torch.backends.mps.is_available()
else "cuda"
if torch.cuda.is_available()
else "cpu"
)
MODEL_ID: str = "meta-llama/Meta-Llama-3-70B-Instruct"
最後一塊拼圖已就位,資料庫準備好支援聊天機械人對話。接下來要準備模型,以處理大量使用者查詢。這時便可運用推論端點的功能。這些專用端點提供流暢的方法部署及管理模型,確保它隨時能回應使用者輸入。
幸好,使用推論端點非常簡單,這要歸功於 inference client;它由 huggingface_hub 程式庫提供:
def get_client_and_tokenizer(
model_id: str = settings.MODEL_ID, tokenizer_id: Optional[str] = None
) -> tuple[InferenceClient, AutoTokenizer]:
if tokenizer_id is None:
tokenizer_id = model_id
client = InferenceClient()
base_url = client._resolve_url(model=model_id, task="text-generation")
# Note: We could move to the AsyncClient
client = InferenceClient(model=base_url, token=os.getenv("HF_API_TOKEN"))
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
return client, tokenizer
# Load the client and tokenizer
client, tokenizer = get_client_and_tokenizer()
元件準備好後,便要編寫傳送給 client 的提示詞。提示詞會作為輸入,引導機器學習模型生成準確且有資訊量的回覆,同時避免回答無關問題。本節會深入介紹如何編寫結構良好的提示詞,讓模型發揮所長。prepare_input 函數會整理對話,套用提示詞及聊天範本,再傳送給模型:
def prepare_input(message: str, history: list[tuple[str, str]]) -> str:
# Retrieve the context from the database
context = database.retrieve_doc_chunks(message)
# Prepare the conversation for the model.
conversation = []
for human, bot in history:
conversation.append({"role": "user", "content": human})
conversation.append({"role": "assistant", "content": bot})
conversation.insert(0, {"role": "system", "content": SYSTEM_PROMPT})
conversation.append(
{
"role": "user",
"content": ARGILLA_BOT_TEMPLATE.format(message=message, context=context),
}
)
return tokenizer.apply_chat_template(
[conversation],
tokenize=False,
add_generation_prompt=True,
)[0]
此函數會接收兩個引數:message 和 history,由 gradio 的 ChatInterface 傳入;然後從資料庫取得文件片段,協助 LLM 撰寫回覆,並準備要傳送給 LLM 模型的提示詞。
按一下查看 system prompt 和機械人範本
這裏展示所使用的 system_prompt 和提示詞範本,主要參考 Weights and Biases 的 wandbot。
SYSTEM_PROMPT = """\
You are a support expert in Argilla SDK, whose goal is help users with their questions.
As a trustworthy expert, you must provide truthful answers to questions using only the provided documentation snippets, not prior knowledge.
Here are guidelines you must follow when responding to user questions:
##Purpose and Functionality**
- Answer questions related to the Argilla SDK.
- Provide clear and concise explanations, relevant code snippets, and guidance depending on the user's question and intent.
- Ensure users succeed in effectively understanding and using Argilla's features.
- Provide accurate responses to the user's questions.
**Specificity**
- Be specific and provide details only when required.
- Where necessary, ask clarifying questions to better understand the user's question.
- Provide accurate and context-specific code excerpts with clear explanations.
- Ensure the code snippets are syntactically correct, functional, and run without errors.
- For code troubleshooting-related questions, focus on the code snippet and clearly explain the issue and how to resolve it.
- Avoid boilerplate code such as imports, installs, etc.
**Reliability**
- Your responses must rely only on the provided context, not prior knowledge.
- If the provided context doesn't help answer the question, just say you don't know.
- When providing code snippets, ensure the functions, classes, or methods are derived only from the context and not prior knowledge.
- Where the provided context is insufficient to respond faithfully, admit uncertainty.
- Remind the user of your specialization in Argilla SDK support when a question is outside your domain of expertise.
- Redirect the user to the appropriate support channels - Argilla [community](https://join.slack.com/t/rubrixworkspace/shared_invite/zt-whigkyjn-a3IUJLD7gDbTZ0rKlvcJ5g) when the question is outside your capabilities or you do not have enough context to answer the question.
**Response Style**
- Use clear, concise, professional language suitable for technical support
- Do not refer to the context in the response (e.g., "As mentioned in the context...") instead, provide the information directly in the response.
**Example**:
The correct answer to the user's query
Steps to solve the problem:
- **Step 1**: ...
- **Step 2**: ...
...
Here's a code snippet
```python
# Code example
...
```
**Explanation**:
- Point 1
- Point 2
...
"""
ARGILLA_BOT_TEMPLATE = """\
Please provide an answer to the following question related to Argilla's new SDK.
You can make use of the chunks of documents in the context to help you generating the response.
## Query:
{message}
## Context:
{context}
"""
我們的對話式 AI 系統已來到最後整合階段:chatty 函數。此函數負責協調目前建立的各個元件,主要工作是呼叫 prepare_input 函數,編寫要傳送給 client 的提示詞。接著會逐步輸出生成中的文字;回覆完成後,系統會儲存對話記錄,讓我們能據此檢視及完善模型,確保每次迭代都持續進步。
def chatty(message: str, history: list[tuple[str, str]]) -> Generator[str, None, None]:
prompt = prepare_input(message, history)
partial_response = ""
for token_stream in client.text_generation(prompt=prompt, **client_kwargs):
partial_response += token_stream
yield partial_response
global conv_id
new_conversation = len(history) == 0
if new_conversation:
conv_id = str(uuid.uuid4())
else:
history.append((message, None))
# Register to argilla dataset
argilla_dataset.records.log(
[
{
"instruction": create_chat_html(history) if history else message,
"response": partial_response,
"conv_id": conv_id,
"turn": len(history)
},
]
)
現在到了測試應用程式的時候!只要在本機環境執行 python app.py,即可查看實際效果。不過先確保你能連接到已部署在推論端點的模型。本例使用功能強大的 Llama 3 70B,你也可試用其他符合需要的模型。透過調整模型及微調應用程式,便能發揮其完整潛力,探索 AI 開發的新可能。
在 Hugging Face Spaces 部署聊天機械人應用程式
應用程式已啟動並運作,現在要與大家分享!為部署應用程式並讓其他人使用,我們會按照 Gradio 的分享應用程式指南操作。我們選用 Hugging Face Spaces 作為託管平台,它非常適合展示 AI 專案。
首先要在儲存庫加入 requirements.txt 檔案,列出執行應用程式所需的相依套件。這是確保應用程式易於重現及部署的重要一步。你可在 Hugging Face Spaces 的Spaces 相依套件文件瞭解更多。
接著按照這份指南,將 Hugging Face API token 設為 secret。如此應用程式便可向 Hugging Face 生態系統進行驗證。
上載 app.py 檔案後,Space 便會開始建置,我們可透過以下連結使用應用程式:
https://huggingface.co/spaces/plaguss/argilla-sdk-chatbot-space
可在此查看範例 Space 檔案,瞭解各部分如何組合。按照這些步驟,你便能與大家分享自己的 AI 應用程式,並與 Hugging Face 社羣合作。
試玩聊天機械人
現在可以測試聊天機械人。我們提供了一些預設查詢供你開始使用,也歡迎你試問自己的問題。例如可以問:What are the Settings in the new SDK?
從下方螢幕截圖可見,聊天機械人已準備好為你的查詢提供實用回覆:
除此之外,你也可以要求聊天機械人為特定資料集生成設定,例如本教學早前建立的資料集。舉例來説,可要求它為用於微調嵌入模型的資料集建議設定,類似我們在包含三元組以微調嵌入模型的 Argilla 資料集一節中探討的資料集。
查看下方螢幕截圖,看看聊天機械人如何回應這類查詢。
現在就提出問題,看看聊天機械人能提供甚麼見解!
後續步驟
在本教學中,我們成功建立了一個聊天機械人,可回答有關 Argilla SDK 及其應用的問題。透過 Llama 3 70B 和 Gradio,我們打造了易用介面,協助開發者瞭解如何操作資料集及微調嵌入模型。
不過,聊天機械人只是起點,我們還有很多方法可以改善及擴充其功能。以下是一些可行的後續工作:
改善分塊策略:試驗不同的分塊策略、參數及大小,以最佳化聊天機械人的效能和回覆質素。
實作去重及篩選:在訓練資料集中加入去重及篩選機制,移除重複和無關資訊,確保聊天機械人提供準確精簡的回覆。
在回覆中附上來源:加入相關文件及來源連結,讓使用者能深入瞭解主題並繼續探索,從而改善聊天機械人的回覆。
處理這些方向後,便可進一步提升聊天機械人,令它成為使用 Argilla SDK 的開發者更有價值的資源。可能性無限,我們期待這個專案未來的發展。敬請留意後續更新及改進!
來源:Hugging Face Blog · huggingface.co





