Published

Marqo 如何通过 Vanna Python 库使用 AI 生成 SQL

Marqo 是一个端到端的多模态向量搜索引擎。用户可以存储和查询非结构化数据,如文本、图像和代码

Vanna 现在支持 Marqo 作为原生集成,以帮助使用 AI 生成 SQL

Marqo是什么?

Marqo

Marqo 是一个端到端的多模态向量搜索引擎。用户可以存储和查询非结构化数据,如文本、图像和代码。你可以了解更多关于 Marqo 的信息 here 。一旦你启动并运行了一个 Marqo 实例,你可以借助 Vanna Python 库来生成 SQL。

Vanna是什么?

Vanna 是一个使用 Retrieval Augmented Generation (RAG) 生成 SQL 查询的 Python 库。 Vanna

基本上它提供了2个高级功能:

  1. vn.train() - This is used to store information in a vector database or vector search like Marqo.
  2. vn.ask() - This will retrieve information from the vector database and use it to construct a prompt for the LLM. The LLM will then generate SQL queries based on the prompt.

如何使用它来帮助生成SQL?

你可以向Vanna Python库提供关于你的数据库的信息,然后让它为你生成SQL查询。元数据将存储在Marqo中,然后通过你喜欢的LLM生成SQL查询。

启动Marqo Docker容器

vanna-marqo-start

安装 Vanna Python 库和 Marqo Python 库

pip install vanna
pip install marqo

配置 Vanna 使用 Marqo 作为向量存储,并搭配您喜欢的 LLM

在这种情况下,我们使用的是OpenAI的GPT-4模型。

from vanna.marqo.marqo import Marqo_VectorStore
from vanna.openai.openai_chat import OpenAI_Chat

class MyVanna(Marqo_VectorStore, OpenAI_Chat):
    def __init__(self, config=None):
        Marqo_VectorStore.__init__(self, config=config) # You can pass additional Marqo configuration options like the url and model name here
        OpenAI_Chat.__init__(self, config=config)

vn = MyVanna(config={'api_key': os.environ['OPENAI_API_KEY'], 'model': 'gpt-4'})

添加训练数据

训练数据的一个例子可能是DDL语句、SQL查询,或者你拥有的关于数据库、业务或行业的任何其他基于文本的文档。

这里我们将向向量存储添加一个简单的DDL语句。

vn.train(ddl='CREATE TABLE users (id INT, name VARCHAR(255), email VARCHAR(255), PRIMARY KEY (id))')

实际上,您会希望添加更多的训练数据。您可以添加任意数量的数据。添加的数据越多,结果就会越好。请参阅 this example notebook 了解如何做到这一点。

提问

现在我们可以提出问题并获取SQL、表格结果、自动生成的Plotly代码以及可能的后续问题。

vn.ask('How many users are there?')

Vanna Jupyter Notebook

连接到数据库

你也可以连接到数据库来运行查询并获取表格结果、图表等。查看 this example notebook 了解如何做到这一点。该笔记本还展示了如何连接到各种数据库和其他LLM。

用户界面

你可以将此与Streamlit或任何其他基于Python的UI框架一起使用。我们有两个开源的streamlit应用程序,你可以作为起点使用。

Vanna Streamlit

将此作为Notebook运行

以笔记本形式运行