llamafile
讓我們載入 llamafile 嵌入類別。
設定
首先,有 3 個設定步驟
- 下載一個 llamafile。在本筆記本中,我們使用
TinyLlama-1.1B-Chat-v1.0.Q5_K_M
,但在 HuggingFace 上還有許多其他可用的。 - 使 llamafile 可執行。
- 在伺服器模式下啟動 llamafile。
您可以執行以下 bash 腳本來完成所有這些操作
%%bash
# llamafile setup
# Step 1: Download a llamafile. The download may take several minutes.
wget -nv -nc https://huggingface.co/jartine/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile
# Step 2: Make the llamafile executable. Note: if you're on Windows, just append '.exe' to the filename.
chmod +x TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile
# Step 3: Start llamafile server in background. All the server logs will be written to 'tinyllama.log'.
# Alternatively, you can just open a separate terminal outside this notebook and run:
# ./TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile --server --nobrowser --embedding
./TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile --server --nobrowser --embedding > tinyllama.log 2>&1 &
pid=$!
echo "${pid}" > .llamafile_pid # write the process pid to a file so we can terminate the server later
使用 LlamafileEmbeddings 嵌入文字
現在,我們可以使用 LlamafileEmbeddings
類別與目前在 https://127.0.0.1:8080 提供 TinyLlama 模型的 llamafile 伺服器互動。
from langchain_community.embeddings import LlamafileEmbeddings
API 參考:LlamafileEmbeddings
embedder = LlamafileEmbeddings()
text = "This is a test document."
若要產生嵌入,您可以查詢個別文字,也可以查詢文字清單。
query_result = embedder.embed_query(text)
query_result[:5]
doc_result = embedder.embed_documents([text])
doc_result[0][:5]
%%bash
# cleanup: kill the llamafile server process
kill $(cat .llamafile_pid)
rm .llamafile_pid