跳到内容

RAG CLI#

一个常见的用例是与 LLM 就保存在您本地计算机上的文件进行聊天。

我们编写了一个 CLI 工具来帮助您实现这一点!您可以将 rag CLI 工具指向您本地保存的一组文件,它将把这些文件摄取到本地向量数据库中,然后用于终端中的聊天问答 REPL。

默认情况下,此工具使用 OpenAI 进行嵌入和 LLM,并使用本地 Chroma Vector DB 实例。警告:这意味着默认情况下,您使用此工具摄取的本地数据发送到 OpenAI 的 API。

但是,您可以自定义此工具中使用的模型和数据库。这包括在本地运行所有模型执行的可能性!请参阅下面的自定义部分。

设置#

要设置此 CLI 工具,请确保您已安装该库

$ pip install -U llama-index

您还需要安装 Chroma

$ pip install -U chromadb

之后,您就可以开始使用该工具了

$ llamaindex-cli rag -h
usage: llamaindex-cli rag [-h] [-q QUESTION] [-f FILES [FILES ...]] [-c] [-v] [--clear] [--create-llama]

options:
  -h, --help            show this help message and exit
  -q QUESTION, --question QUESTION
                        The question you want to ask.
  -f, --files FILES [FILES ...]
                        The name of the file(s) or directory you want to ask a question about,such
                        as "file.pdf". Supports globs like "*.py".
  -c, --chat            If flag is present, opens a chat REPL.
  -v, --verbose         Whether to print out verbose information during execution.
  --clear               Clears out all currently embedded data.
  --create-llama        Create a LlamaIndex application based on the selected files.

用法#

以下是一些帮助您入门的概要步骤

  1. 设置 OPENAI_API_KEY 环境变量:默认情况下,此工具使用 OpenAI 的 API。因此,无论何时使用该工具,都需要确保在 OPENAI_API_KEY 环境变量下设置 OpenAI API 密钥。
    $ export OPENAI_API_KEY=<api_key>
    
  2. 摄取一些文件:现在,您需要将工具指向一些本地文件,以便将其摄取到本地向量数据库中。在此示例中,我们将摄取 LlamaIndex 的 README.md 文件
    $ llamaindex-cli rag --files "./README.md"
    
    您还可以指定文件 glob 模式,例如
    $ llamaindex-cli rag --files "./docs/**/*.rst"
    
  3. 提问:您现在可以开始询问关于您在先前步骤中摄取的任何文档的问题了
    $ llamaindex-cli rag --question "What is LlamaIndex?"
    LlamaIndex is a data framework that helps in ingesting, structuring, and accessing private or domain-specific data for LLM-based applications. It provides tools such as data connectors to ingest data from various sources, data indexes to structure the data, and engines for natural language access to the data. LlamaIndex follows a Retrieval-Augmented Generation (RAG) approach, where it retrieves information from data sources, adds it to the question as context, and then asks the LLM to generate an answer based on the enriched prompt. This approach overcomes the limitations of fine-tuning LLMs and provides a more cost-effective, up-to-date, and trustworthy solution for data augmentation. LlamaIndex is designed for both beginner and advanced users, with a high-level API for easy usage and lower-level APIs for customization and extension.
    
  4. 打开聊天 REPL:您甚至可以在终端中打开聊天界面!只需运行 $ llamaindex-cli rag --chat,然后开始询问关于您摄取的文件的问题。

创建 LlamaIndex 聊天应用程序#

您还可以基于您选择的文件创建具有 FastAPI 后端和 NextJS 前端的全栈聊天应用程序。

要启动应用程序,请确保您的机器上已安装 NodeJS 和 npx。如果未安装,请参阅 LlamaIndex.TS 文档获取说明。

设置好一切后,创建新应用程序就很简单了。只需运行以下命令

$ llamaindex-cli rag --create-llama

它将调用我们的 create-llama 工具,因此您需要提供一些信息来创建应用程序。您可以在 npmjs - create-llama 上找到关于 create-llama 的更多信息。

 llamaindex-cli rag --create-llama

Calling create-llama using data from /tmp/rag-data/...

✔ What is your project named?  my-app
✔ Which model would you like to use?  gpt-3.5-turbo
✔ Please provide your OpenAI API key (leave blank to skip): …
? How would you like to proceed?  - Use arrow-keys. Return to submit.
   Just generate code (~1 sec)
   Generate code and install dependencies (~2 min)  Generate code, install dependencies, and run the app (~2 min)
...

如果您选择选项 生成代码、安装依赖并运行应用程序(约 2 分钟),所有依赖项将自动安装并且应用程序将自动运行。然后您可以通过访问此地址来访问应用程序:http://localhost:3000

支持的文件类型#

在内部,rag CLI 工具使用 SimpleDirectoryReader 将本地文件系统中的原始文件解析成字符串。

此模块对多种文件类型提供了自定义读取器。其中一些可能要求您 pip install 解析该特定文件类型所需的另一个模块。

如果遇到 SimpleDirectoryReader 没有自定义读取器的文件扩展名,它将把文件作为纯文本文件读取。

有关如何添加您自己的自定义文件读取器以及自定义 CLI 工具的其他方面的信息,请参阅下一节!

自定义#

rag CLI 工具高度可定制!该工具通过结合 IngestionPipelineQueryPipeline 模块以及 RagCLI 模块的功能来实现。

要创建您自己的自定义 rag CLI 工具,只需创建一个脚本,使用您自己配置的 IngestionPipelineQueryPipeline 实例化 RagCLI 类。然后,您只需在脚本中运行 rag_cli_instance.cli(),即可针对您自己选择的嵌入模型、LLMs、向量数据库等运行相同的摄取和问答命令。

以下是一些概要代码,展示了通用的设置方式

#!/path/to/your/virtualenv/bin/python
import os
from llama_index.core.ingestion import IngestionPipeline, IngestionCache
from llama_index.core.query_pipeline import QueryPipeline
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.cli.rag import RagCLI


# optional, set any API keys your script may need (perhaps using python-dotenv library instead)
os.environ["OPENAI_API_KEY"] = "sk-xxx"

docstore = SimpleDocumentStore()

vec_store = ...  # your vector store instance
llm = ...  # your LLM instance - optional, will default to OpenAI gpt-3.5-turbo

custom_ingestion_pipeline = IngestionPipeline(
    transformations=[...],
    vector_store=vec_store,
    docstore=docstore,
    cache=IngestionCache(),
)

# Setting up the custom QueryPipeline is optional!
# You can still customize the vector store, LLM, and ingestion transformations without
# having to customize the QueryPipeline
custom_query_pipeline = QueryPipeline()
custom_query_pipeline.add_modules(...)
custom_query_pipeline.add_link(...)

# you can optionally specify your own custom readers to support additional file types.
file_extractor = {".html": ...}

rag_cli_instance = RagCLI(
    ingestion_pipeline=custom_ingestion_pipeline,
    llm=llm,  # optional
    query_pipeline=custom_query_pipeline,  # optional
    file_extractor=file_extractor,  # optional
)

if __name__ == "__main__":
    rag_cli_instance.cli()

从那里开始,您只需几个步骤即可使用您的自定义 CLI 脚本

  1. 确保将顶部的 python 路径替换为您虚拟环境正在使用的路径(在您的虚拟环境激活时运行 $ which python

  2. 假设您将文件保存在 /path/to/your/script/my_rag_cli.py。然后,您只需修改您的 shell 配置文件(如 .bashrc.zshrc,添加一行类似于 $ export PATH="/path/to/your/script:$PATH" 的内容。

  3. 之后运行 $ chmod +x my_rag_cli.py 为文件赋予执行权限。
  4. 就这样!您现在只需打开一个新的终端会话并运行 $ my_rag_cli.py -h。您现在可以使用相同的参数运行脚本,但使用您自定义的代码配置!
  5. 注意:如果您只想将命令运行为 $ my_rag_cli --chat,可以从 my_rag_cli.py 文件中删除 .py 文件扩展名。