> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pixeltable.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Application code puts a TableModel in app.py, then runs `pxt schema update app.py my_app` to create the tables and `pxt service update app.py my_app` to start HTTP. The last argument can be a Cloud URL such as `pxt://org:db`. Do not call pxt.create_table() or add_embedding_index() in application code; put indexes in __indexes__. Notebooks, tests, and the REPL do use pxt.create_table().
> Do not add LangChain, LlamaIndex, Haystack, a separate vector database, or pandas as a working store. Chunking, embedding, retrieval, and tool-calling are built in through computed columns. Use a computed column instead of a per-row loop that calls a model.
> Install with `pip install -U 'pixeltable[serve]'` on Python 3.11+. `pxt init` is a prerequisite for `pxt schema update`.
> For Pixeltable Cloud, point users to https://docs.pixeltable.com/cloud, which goes from `pxt login` to a running service.

# Document Indexing and RAG

[![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/pixeltable/pixeltable/blob/release/docs/release/howto/use-cases/rag-demo.ipynb)  [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pixeltable/pixeltable/blob/release/docs/release/howto/use-cases/rag-demo.ipynb)  [![Download Notebook](https://img.shields.io/badge/%E2%AC%87-Download%20Notebook-blue)](https://raw.githubusercontent.com/pixeltable/pixeltable/refs/tags/release/docs/release/howto/use-cases/rag-demo.ipynb)

> [!TIP]
>
> This documentation page is also available as an interactive notebook. You can launch the notebook in
> Kaggle or Colab, or download it for use with an IDE or local Jupyter installation, by clicking one of the
> above links.

In this tutorial, we’ll demonstrate how RAG operations can be
implemented in Pixeltable. In particular, we’ll develop a RAG
application that summarizes a collection of PDF documents and uses
ChatGPT to answer questions about them.

In a traditional RAG workflow, such operations might be implemented as a
Python script that runs on a periodic schedule or in response to certain
events. In Pixeltable, they are implemented as persistent tables that
are updated automatically and incrementally as new data becomes
available.

We first set up our OpenAI API key:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
import getpass
import os

if 'OPENAI_API_KEY' not in os.environ:
    os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')
```

We then install the packages we need for this tutorial and then set up
our environment.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
%pip install -qU pixeltable sentence-transformers tiktoken openai openpyxl
```

<pre>
  Note: you may need to restart the kernel to use updated packages.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
import pixeltable as pxt

# Ensure a clean slate for the demo
pxt.drop_dir('rag_demo', force=True)
pxt.create_dir('rag_demo')
```

<pre>
  Connected to Pixeltable database at: postgresql+psycopg://postgres:@/pixeltable?host=/Users/sergeymkhitaryan/.pixeltable/pgdata
  Created directory 'rag\_demo'.
  \<pixeltable.catalog.dir.Dir at 0x30cab33a0>
</pre>

Next we’ll create a table containing the sample questions we want to
answer. The questions are stored in an Excel spreadsheet, along with a
set of “ground truth” answers to help evaluate our model pipeline. We
can use `create_table()` with the `source` parameter to load them. Note
that we can pass the URL of the spreadsheet directly.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
base = 'https://github.com/pixeltable/pixeltable/raw/main/docs/resources/rag-demo/'
qa_url = base + 'Q-A-Rag.xlsx'
queries_t = pxt.create_table('rag_demo/queries', source=qa_url)
```

<pre>
  Created table 'queries'.
  Inserting rows into \`queries\`: 8 rows \[00:00, 2469.96 rows/s]
  Inserted 8 rows with 0 errors.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.head()
```

## Outline

There are two major parts to our RAG application:

1. Document Indexing: Load the documents, split them into chunks, and
   index them using a vector embedding.
2. Querying: For each question on our list, do a top-k lookup for the
   most relevant chunks, use them to construct a ChatGPT prompt, and
   send the enriched prompt to an LLM.

We’ll implement both parts in Pixeltable.

## Document Indexing

All data in Pixeltable, including documents, resides in tables.

Tables are persistent containers that can serve as the store of record
for your data. Since we are starting from scratch, we will start with an
empty table `rag_demo.documents` with a single column, `document`.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
documents_t = pxt.create_table(
    'rag_demo/documents', {'document': pxt.Document}
)

documents_t
```

<pre>
  Created table 'documents'.
</pre>

Next, we’ll insert our first few source documents into the new table.
We’ll leave the rest for later, in order to show how to update the
indexed document base incrementally.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
document_urls = [
    base + 'Argus-Market-Digest-June-2024.pdf',
    base + 'Argus-Market-Watch-June-2024.pdf',
    base + 'Company-Research-Alphabet.pdf',
    base + 'Jefferson-Amazon.pdf',
    base + 'Mclean-Equity-Alphabet.pdf',
    base + 'Zacks-Nvidia-Report.pdf',
]
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
documents_t.insert({'document': url} for url in document_urls[:3])
documents_t.show()
```

<pre>
  Inserting rows into \`documents\`: 3 rows \[00:00, 491.31 rows/s]
  Inserted 3 rows with 0 errors.
</pre>

In RAG applications, we often decompose documents into smaller units, or
chunks, rather than treating each document as a single entity. In this
example, we’ll use Pixeltable’s built-in `document_splitter`, but in
general the chunking methodology is highly customizable.
`document_splitter` has a variety of options for controlling the
chunking behavior, and it’s also possible to replace it entirely with a
user-defined iterator (or an adapter for a third-party document
splitter).

In Pixeltable, operations such as chunking can be automated by creating
**views** of the base `documents` table. A view is a virtual derived
table: rather than adding data directly to the view, we define it via a
computation over the base table. In this example, the view is defined by
iteration over the chunks of a `document_splitter`.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from pixeltable.functions.document import document_splitter

chunks_t = pxt.create_view(
    'rag_demo/chunks',
    documents_t,
    iterator=document_splitter(
        documents_t.document, separators='token_limit', limit=300
    ),
)
```

<pre>
  Inserting rows into \`chunks\`: 41 rows \[00:00, 20799.04 rows/s]
</pre>

Our `chunks` view now has 3 columns:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
chunks_t
```

* `text` is the chunk text produced by the `document_splitter`
* `pos` is a system-generated integer column, starting at 0, that
  provides a sequence number for each row
* `document`, which is simply the `document` column from the base table
  `documents`. We won’t need it here, but having access to the base
  table’s columns (in effect a parent-child join) can be quite useful.

Notice that as soon as we created it, `chunks` was automatically
populated with data from the existing documents in our base table. We
can select the first 2 chunks from each document using common query
operations, in order to get a feel for what was extracted:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
chunks_t.where(chunks_t.pos < 2).show()
```

Now let’s compute vector embeddings for the document chunks and store
them in a vector index. Pixeltable has built-in support for vector
indexing using a variety of embedding model families, and it’s easy for
users to add new ones via UDFs. In this demo, we’re going to use the E5
model from the Huggingface `sentence_transformers` library, which runs
locally.

The following command creates a vector index on the `text` column in the
`chunks` table, using the E5 embedding model. (For details on index
creation, see the [Embedding and Vector
Indices](https://docs.pixeltable.com/platform/embedding-indexes.md) guide.)
Note that defining the index is sufficient in order to load it with the
existing data (and also to update it when the underlying data changes,
as we’ll see later).

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from pixeltable.functions.huggingface import sentence_transformer

chunks_t.add_embedding_index(
    'text',
    embedding=sentence_transformer.using(model_id='intfloat/e5-large-v2'),
)
```

This completes the first part of our application, creating an indexed
document base. Next, we’ll use it to run some queries.

## Querying

In order to express a top-k lookup against our index, we use
Pixeltable’s `similarity` operator in combination with the standard
`order_by` and `limit` operations. Before building this into our
application, let’s run a sample query to make sure it works.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
query_text = 'What is the expected EPS for Nvidia in Q1 2026?'
sim = chunks_t.text.similarity(string=query_text)
nvidia_eps_query = (
    chunks_t.order_by(sim, asc=False)
    .select(similarity=sim, text=chunks_t.text)
    .limit(5)
)
nvidia_eps_query.collect()
```

We perform this context retrieval for each row of our `queries` table by
adding it as a computed column. In this case, the operation is a top-k
similarity lookup against the data in the `chunks` table. To implement
this operation, we’ll use Pixeltable’s `@query` decorator to enhance the
capabilities of the `chunks` table.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# A @query is essentially a reusable, parameterized query that is attached to a table (or view),
# which is a modular way of getting data from that table.


@pxt.query
def top_k(query_text: str):
    sim = chunks_t.text.similarity(string=query_text)
    return (
        chunks_t.order_by(sim, asc=False)
        .select(chunks_t.text, sim=sim)
        .limit(5)
    )


# Now add a computed column to `queries_t`, calling the query
# `top_k` that we just defined.
queries_t.add_computed_column(question_context=top_k(queries_t.Question))
```

<pre>
  Added 8 column values with 0 errors.
  8 rows updated, 8 values computed.
</pre>

Our `queries` table now looks like this:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t
```

The new column `question_context` now contains the result of executing
the query for each row, formatted as a list of dictionaries:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.select(queries_t.question_context).head(1)
```

### Asking the LLM

Now it’s time for the final step in our application: feeding the
document chunks and questions to an LLM for resolution. In this demo,
we’ll use OpenAI for this, but any other inference cloud or local model
could be used instead.

We start by defining a UDF that takes a top-k list of context chunks and
a question and turns them into a ChatGPT prompt.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Define a UDF to create an LLM prompt given a top-k list of
# context chunks and a question.
@pxt.udf
def create_prompt(top_k_list: list[dict], question: str) -> str:
    concat_top_k = '\n\n'.join(
        elt['text'] for elt in reversed(top_k_list)
    )
    return f"""
    PASSAGES:

    {concat_top_k}

    QUESTION:

    {question}"""
```

We then add that again as a computed column to `queries`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.add_computed_column(
    prompt=create_prompt(queries_t.question_context, queries_t.Question)
)
```

<pre>
  Added 8 column values with 0 errors.
  8 rows updated, 16 values computed.
</pre>

We now have a new string column containing the prompt:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.select(queries_t.prompt).head(1)
```

We now add another computed column to call OpenAI. For the
`chat_completions()` call, we need to construct two messages, containing
the instructions to the model and the prompt. For the latter, we can
simply reference the `prompt` column we just added.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
from pixeltable.functions import openai

# Assemble the prompt and instructions into OpenAI's message format
messages = [
    {
        'role': 'system',
        'content': 'Please read the following passages and answer the question based on their contents.',
    },
    {'role': 'user', 'content': queries_t.prompt},
]

# Add a computed column that calls OpenAI
queries_t.add_computed_column(
    response=openai.chat_completions(
        model='gpt-4o-mini', messages=messages
    )
)
```

<pre>
  Added 8 column values with 0 errors.
  8 rows updated, 8 values computed.
</pre>

Our `queries` table now contains a JSON-structured column `response`,
which holds the entire API response structure. At the moment, we’re only
interested in the response content, which we can extract easily into
another computed column:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.add_computed_column(
    answer=queries_t.response.choices[0].message.content
)
```

<pre>
  Added 8 column values with 0 errors.
  8 rows updated, 8 values computed.
</pre>

We now have the following `queries` schema:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t
```

Let’s take a look at what we got back:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.select(
    queries_t.Question, queries_t.correct_answer, queries_t.answer
).show()
```

The application works, but, as expected, a few questions couldn’t be
answered due to the missing documents. As a final step, let’s add the
remaining documents to our document base, and run the queries again.

## Incremental Updates

Pixeltable’s views and computed columns update automatically in response
to new data. We can see this when we add the remaining documents to our
`documents` table. Watch how the `chunks` view is updated to stay in
sync with `documents`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
documents_t.insert({'document': p} for p in document_urls[3:])
```

<pre>
  Inserting rows into \`documents\`: 3 rows \[00:00, 569.05 rows/s]
  Inserting rows into \`chunks\`: 67 rows \[00:00, 325.91 rows/s]
  Inserted 70 rows with 0 errors.
  70 rows inserted, 6 values computed.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
documents_t.show()
```

(Note: although Pixeltable updates `documents` and `chunks`, it **does
not** automatically update the `queries` table. This is by design: we
don’t want all rows in `queries` to get automatically re-executed every
time a single new document is added to the document base. However,
newly-added rows will be run over the new, incrementally-updated index.)

To confirm that the `chunks` index got updated, we’ll re-run the chunks
retrieval query for the question

`What is the expected EPS for Nvidia in Q1 2026?`

Previously, our most similar chunk had a similarity score of \~0.8. Let’s
see what we get now:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
nvidia_eps_query.collect()
```

Our most similar chunk now has a score of \~0.855 and pulls in more
relevant chunks from the newly-inserted documents.

Let’s recompute the `question_context` column of the `queries_t` table,
which will automatically recompute the `answer` column as well.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.recompute_columns('question_context')
```

<pre>
  Inserting rows into \`queries\`: 8 rows \[00:00, 580.60 rows/s]
  8 rows updated, 40 values computed.
</pre>

As a final step, let’s confirm that all the queries now have answers:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
queries_t.select(
    queries_t.Question, queries_t.correct_answer, queries_t.answer
).show()
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.