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

# Generate captions for images

[![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/images/img-generate-captions.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/images/img-generate-captions.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/images/img-generate-captions.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.

Automatically create descriptive captions for images using AI vision
models.

## Problem

You have a collection of images that need captions—for accessibility,
SEO, content management, or searchability. Writing captions manually
doesn’t scale.

## Solution

**What’s in this recipe:**

* Generate captions using OpenAI’s vision models
* Customize caption style (short, detailed, SEO-focused)
* Process images in batch automatically

You add a computed column that sends each image to a vision model with a
captioning prompt. New images are captioned automatically on insert.

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

### Load images

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

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

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

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Create table for images
images = pxt.create_table('caption_demo/images', {'image': pxt.Image})
```

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

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Insert sample images
image_urls = [
    'https://raw.githubusercontent.com/pixeltable/pixeltable/main/docs/resources/images/000000000036.jpg',
    'https://raw.githubusercontent.com/pixeltable/pixeltable/main/docs/resources/images/000000000090.jpg',
    'https://raw.githubusercontent.com/pixeltable/pixeltable/main/docs/resources/images/000000000106.jpg',
]

images.insert([{'image': url} for url in image_urls])
```

<pre>
  Inserted 3 rows with 0 errors in 0.12 s (25.17 rows/s)
  3 rows inserted.
</pre>

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

### Generate captions

Add a computed column that generates captions using the vision model:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add caption using OpenAI vision

messages = [
    {
        'role': 'user',
        'content': [
            {
                'type': 'text',
                'text': 'Write a concise, descriptive caption for this image in one sentence.',
            },
            {'type': 'image_url', 'image_url': images.image},
        ],
    }
]

images.add_computed_column(
    caption=chat_completions(messages, model='gpt-4o-mini')
)
```

<pre>
  Added 3 column values with 0 errors in 4.62 s (0.65 rows/s)
  3 rows updated.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# View images with captions
images.select(
    images.image, images.caption['choices'][0]['message']['content']
).collect()
```

### Different caption styles

You can generate multiple caption styles for different uses:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add alt text for accessibility (brief)

messages = [
    {
        'role': 'user',
        'content': [
            {
                'type': 'text',
                'text': 'Write a brief alt text for this image (under 125 characters) for screen readers.',
            },
            {'type': 'image_url', 'image_url': images.image},
        ],
    }
]

images.add_computed_column(
    alt_text=chat_completions(messages, model='gpt-4o-mini')
)
```

<pre>
  Added 3 column values with 0 errors in 3.51 s (0.85 rows/s)
  3 rows updated.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add detailed description

messages = [
    {
        'role': 'user',
        'content': [
            {
                'type': 'text',
                'text': 'Describe this image in detail, including objects, colors, setting, and mood.',
            },
            {'type': 'image_url', 'image_url': images.image},
        ],
    }
]

images.add_computed_column(
    description=chat_completions(messages, model='gpt-4o-mini')
)
```

<pre>
  Added 3 column values with 0 errors in 11.28 s (0.27 rows/s)
  3 rows updated.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# View all caption types
images.select(
    images.image,
    images.caption['choices'][0]['message']['content'],
    images.alt_text['choices'][0]['message']['content'],
    images.description['choices'][0]['message']['content'],
).collect()
```

## Explanation

**Caption prompt patterns:**

**Model selection:**

* `gpt-4o-mini`: Fast and affordable, good for most captioning tasks
* `gpt-4o`: Higher quality for complex images or detailed descriptions

## See also

* [Analyze images in
  batch](https://docs.pixeltable.com/howto/cookbooks/images/vision-batch-analysis.md) -
  Run custom prompts on images
* [Extract structured data from
  images](https://docs.pixeltable.com/howto/cookbooks/images/vision-structured-output.md) -
  Get JSON from images
* [Find similar
  images](https://docs.pixeltable.com/howto/cookbooks/search/search-similar-images.md) -
  Visual similarity search


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