> ## 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.

# 10-Minute Tour

[![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/overview/ten-minute-tour.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/overview/ten-minute-tour.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/overview/ten-minute-tour.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.

Welcome to Pixeltable! In this tutorial, we’ll survey how to create
tables, populate them with data, and enhance them with built-in and
user-defined transformations and AI operations.

This notebook uses `pxt.create_table()` so you can run cells without a
project. An app puts the same columns on a `TableModel` in `app.py` and
creates the tables with `pxt schema update`.

## Install Python packages

First run the following command to install Pixeltable and related
libraries needed for this tutorial.

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

## Creating a table

Let’s begin by creating a `demo` directory (if it doesn’t already exist)
and a table that can hold image data, `demo/first`. The table will
initially have just a single column to hold our input images, which
we’ll call `input_image`. We also need to specify a type for the column:
`pxt.Image`.

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

# Create the directory `demo`, dropping it first (if it exists)
# to ensure a clean environment.
pxt.drop_dir('demo', force=True)
pxt.create_dir('demo')

# Create the table `demo/first` with a single column `input_image`
t = pxt.create_table('demo/first', {'input_image': pxt.Image})
```

<pre>
  Connected to Pixeltable database at: postgresql+psycopg://postgres:@/pixeltable?host=/Users/asiegel/.pixeltable/pgdata
  Created directory 'demo'.
  Created table 'first'.
</pre>

We can use `t.describe()` to examine the table schema. We see that it
now contains a single column, as expected.

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

The new table is initially empty, with no rows:

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

<pre>
  0
</pre>

Now let’s put an image into it! We can add images simply by giving
Pixeltable their URLs. The example images in this demo come from the
[COCO dataset](https://cocodataset.org/), and we’ll be referencing
copies of them in the Pixeltable github repo. But in practice, the
images can come from anywhere: an S3 bucket, say, or the local file
system.

When we add the image, we see that Pixeltable gives us some useful
status updates indicating that the operation was successful.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.insert(
    [
        {
            'input_image': 'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000025.jpg'
        }
    ]
)
```

<pre>
  Inserted 1 row with 0 errors in 0.21 s (4.86 rows/s)
  1 row inserted.
</pre>

We can use `t.head()` to examine the contents of the table.

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

## Adding computed columns

Great! Now we have a table containing some data. Let’s add an object
detection model to our workflow. Specifically, we’re going to use the
ResNet-50 object detection model, which runs using the Huggingface DETR
(“DEtection TRansformer”) model class. Pixeltable contains a built-in
adapter for this model family, so all we have to do is call the
`detr_for_object_detection` Pixeltable function. A nice thing about the
Huggingface models is that they run locally, so you don’t need an
account with a service provider in order to use them.

This is our first example of a **computed column**, a key concept in
Pixeltable. Recall that when we created the `input_image` column, we
specified a type, `pxt.Image`, indicating our intent to populate it with
data in the future. When we create a *computed* column, we instead
specify a function that operates on other columns of the table. By
default, when we add the new computed column, Pixeltable immediately
evaluates it against all existing data in the table - in this case, by
calling the `detr_for_object_detection` function on the image.

Depending on your setup, it may take a minute for the function to
execute. In the background, Pixeltable is downloading the model from
Huggingface (if necessary), instantiating it, and caching it for later
use.

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

t.add_computed_column(
    detections=huggingface.detr_for_object_detection(
        t.input_image, model_id='facebook/detr-resnet-50'
    )
)
```

<pre>
  Added 1 column value with 0 errors in 3.26 s (0.31 rows/s)
  1 row updated.
</pre>

Let’s examine the results.

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

We see that the model returned a JSON structure containing a lot of
information. In particular, it has the following fields:

* `label_text`: Descriptions of the objects detected
* `boxes`: Bounding boxes for each detected object
* `scores`: Confidence scores for each detection
* `labels`: The DETR model’s internal IDs for the detected objects

Perhaps this is more than we need, and all we really want are the text
labels. We could add another computed column to extract `label_text`
from the JSON struct:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.add_computed_column(detections_text=t.detections.label_text)
t.head()
```

If we inspect the table schema now, we see how Pixeltable distinguishes
between ordinary and computed columns.

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

Now let’s add some more images to our table. This demonstrates another
important feature of computed columns: by default, they update
incrementally any time new data shows up on their inputs. In this case,
Pixeltable will run the ResNet-50 model against each new image that is
added, then extract the labels into the `detect_text` column. Pixeltable
will orchestrate the execution of any sequence (or DAG) of computed
columns.

Note how we can pass multiple rows to `t.insert` with a single
statement, which will insert them more efficiently.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
more_images = [
    'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000030.jpg',
    'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000034.jpg',
    'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000042.jpg',
    'https://raw.githubusercontent.com/pixeltable/pixeltable/release/docs/resources/images/000000000061.jpg',
]
t.insert({'input_image': image} for image in more_images)
```

<pre>
  Inserted 4 rows with 0 errors in 1.51 s (2.65 rows/s)
  4 rows inserted.
</pre>

Let’s see what the model came up with. We’ll use `t.select` to suppress
the display of the `detect` column, since right now we’re only
interested in the text labels.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.select(t.input_image, t.detections_text).head()
```

## Pixeltable is persistent

An important feature of Pixeltable is that *everything is persistent*.
Unlike in-memory Python libraries such as Pandas, Pixeltable is a
database: all your data, transformations, and computed columns are
stored and preserved between sessions. To see this, let’s clear all the
variables in our notebook and start fresh. You can optionally restart
your notebook kernel at this point, to demonstrate how Pixeltable data
persists across sessions.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Clear all variables in the notebook
%reset -f

# Instantiate a new client object
import pixeltable as pxt

t = pxt.get_table('demo/first')

# Display just the first two rows, to avoid cluttering the tutorial
t.select(t.input_image, t.detections_text).head(2)
```

## GPT-4o

For comparison, let’s try running our examples through a generative
model, Open AI’s `gpt-4o-mini`. For this section, you’ll need an OpenAI
account with an API key. You can use the following command to add your
API key to the environment (just enter your API key when prompted):

```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(
        'Enter your OpenAI API key:'
    )
```

Now we can connect to OpenAI through Pixeltable. This may take some
time, depending on how long OpenAI takes to process the query.

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

# Construct a message dict for OpenAI. It follows the same pattern
# as the OpenAI SDK, except that in place of an image URL, we can
# put a reference to our image column, and Pixeltable will do the
# substitution once for each row of the table.

messages = [
    {
        'role': 'user',
        'content': [
            {'type': 'text', 'text': "What's in this image?"},
            {'type': 'image_url', 'image_url': t.input_image},
        ],
    }
]

t.add_computed_column(
    vision=openai.chat_completions(messages, model='gpt-4o-mini')
)
```

<pre>
  Added 5 column values with 0 errors in 6.98 s (0.72 rows/s)
  5 rows updated.
</pre>

Let’s see how GPT-4’s responses compare to the traditional
discriminative (DETR) model.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.select(t.input_image, t.detections_text, t.vision).head()
```

It looks like OpenAI returned a whole range of context information along
with the image descriptions. Let’s pluck out just the response content
from inside those JSON structures, so that it’s easier to see in the
table. Note that we can unpack JSON columns in Pixeltable the same way
we would with ordinary Python dicts and lists.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.select(
    t.input_image,
    t.detections_text,
    t.vision['choices'][0]['message']['content'],
).head()
```

In addition to adapters for local models and inference APIs, Pixeltable
can perform a range of more basic image operations. These image
operations can be seamlessly chained with API calls, and Pixeltable will
keep track of the sequence of operations, constructing new images and
caching when necessary to keep things running smoothly. Just for fun
(and to demonstrate the power of computed columns), let’s see what
OpenAI thinks of our sample images when we rotate them by 180 degrees.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.add_computed_column(rot_image=t.input_image.rotate(180))

# This is identical to the preceding messages dict, but with
# `t.rot_image` in place of `t.input_image`.

messages = [
    {
        'role': 'user',
        'content': [
            {'type': 'text', 'text': "What's in this image?"},
            {'type': 'image_url', 'image_url': t.rot_image},
        ],
    }
]

t.add_computed_column(
    rot_vision=openai.chat_completions(messages, model='gpt-4o-mini')
)
```

<pre>
  Added 5 column values with 0 errors in 6.19 s (0.81 rows/s)
  5 rows updated.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.select(
    t.rot_image, t.rot_vision['choices'][0]['message']['content']
).head()
```

## UDFs: Enhancing Pixeltable’s capabilities

Another important principle of Pixeltable is that, although Pixeltable
has a built-in library of useful operations and adapters, it will never
prescribe a particular way of doing things. Pixeltable is built from the
ground up to be extensible.

Let’s take a specific example. Recall our use of the ResNet-50 detection
model, in which the `detect` column contains a JSON blob with bounding
boxes, scores, and labels. Suppose we want to create a column containing
the single label with the highest confidence score. There’s no built-in
Pixeltable function to do this, but it’s easy to write our own. In fact,
all we have to do is write a Python function that does the thing we
want, and mark it with the `@pxt.udf` decorator.

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
def top_detection(detect: dict) -> str:
    scores = detect['scores']
    label_text = detect['label_text']
    # Get the index of the object with the highest confidence
    i = scores.index(max(scores))
    # Return the corresponding label
    return label_text[i]
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.add_computed_column(top=top_detection(t.detections))
```

<pre>
  Added 5 column values with 0 errors in 0.11 s (45.52 rows/s)
  5 rows updated.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.select(t.detections_text, t.top).show()
```

Congratulations! You’ve reached the end of the tutorial. Hopefully, this
gives a good overview of the capabilities of Pixeltable, but there’s
much more to explore. As a next step, you might check out one of the
other tutorials, depending on your interests:

* [Object Detection in
  Videos](https://docs.pixeltable.com/howto/use-cases/object-detection-in-videos.md)
* [RAG Operations in
  Pixeltable](https://docs.pixeltable.com/howto/use-cases/rag-operations.md)
* [Working with OpenAI in
  Pixeltable](https://docs.pixeltable.com/howto/providers/working-with-openai.md)

## Ship it as an app

This notebook used `create_table` so you can run cells without a
project. A `:` field is stored (you insert it). An `=` field is
computed. After `pxt init`, create the tables with `pxt schema update`:

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

TableModel = pxt.model_base()


class First(TableModel, name='first'):
    input_image: pxt.Image
    detections = pxtf.huggingface.detr_for_object_detection(input_image)
```

```bash theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
pxt init
pxt schema update app.py demo
```

See the [Quickstart](https://docs.pixeltable.com/overview/quick-start.md).


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