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

# Create text embeddings with OpenAI

[![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/cookbooks/search/embed-text-openai.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/cookbooks/search/embed-text-openai.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/cookbooks/search/embed-text-openai.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.

Generate vector embeddings for text data to enable semantic search and
similarity matching.

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

## Problem

You need to convert text into vector embeddings for:

* Semantic search (find similar documents)
* RAG pipelines (retrieve relevant context)
* Clustering and classification

## Solution

**What’s in this recipe:**

* Generate embeddings with OpenAI’s models
* Store embeddings as computed columns
* Use embeddings for similarity queries

You add an embedding column that automatically generates vectors for new
rows. The embeddings are cached and only recomputed when the source text
changes.

### Setup

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

```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: ')
```

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

# Create a fresh directory
pxt.drop_dir('embed_demo', force=True)
pxt.create_dir('embed_demo')
```

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

### Create table with embedding column

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Create table for documents
docs = pxt.create_table(
    'embed_demo/documents', {'title': pxt.String, 'content': pxt.String}
)
```

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

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add embedding column using OpenAI's text-embedding-3-small
docs.add_computed_column(
    embedding=embeddings(docs.content, model='text-embedding-3-small')
)
```

<pre>
  Added 0 column values with 0 errors.
  No rows affected.
</pre>

### Insert documents

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Insert sample documents
sample_docs = [
    {
        'title': 'Python Basics',
        'content': 'Python is a high-level programming language known for its clear syntax and readability.',
    },
    {
        'title': 'Machine Learning',
        'content': 'Machine learning is a subset of AI that enables systems to learn from data.',
    },
    {
        'title': 'Web Development',
        'content': 'Web development involves building websites and web applications using HTML, CSS, and JavaScript.',
    },
    {
        'title': 'Data Science',
        'content': 'Data science combines statistics, programming, and domain expertise to extract insights from data.',
    },
    {
        'title': 'Cloud Computing',
        'content': 'Cloud computing provides on-demand computing resources over the internet.',
    },
]

docs.insert(sample_docs)
```

<pre>
  Inserting rows into \`documents\`: 5 rows \[00:00, 553.22 rows/s]
  Inserted 5 rows with 0 errors.
  5 rows inserted, 15 values computed.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# View documents with embeddings (showing first 5 dimensions)
result = docs.select(docs.title, docs.embedding).collect()
```

### Query by similarity

Find documents similar to a query by creating an embedding index:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add embedding index for semantic search
docs.add_embedding_index(
    column='content',
    string_embed=embeddings.using(model='text-embedding-3-small'),
)
```

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Search for similar documents
sim = docs.content.similarity(
    string='artificial intelligence applications'
)
results = (
    docs.where(sim > 0.2)
    .order_by(sim, asc=False)
    .limit(3)
    .select(docs.title, docs.content, sim=sim)
)
results.collect()
```

## Explanation

**OpenAI embedding models:**

**Similarity metrics:**

**Key benefits of computed embedding columns:**

* Embeddings are generated automatically on insert
* Results are cached—no re-computation on subsequent queries
* Index enables fast similarity search at scale

## See also

* [Semantic text
  search](https://docs.pixeltable.com/howto/cookbooks/search/search-semantic-text.md) -
  Full semantic search patterns
* [Chunk documents for
  RAG](https://docs.pixeltable.com/howto/cookbooks/text/doc-chunk-for-rag.md) -
  Prepare documents for retrieval


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