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

# openai

> <a href="https://github.com/pixeltable/pixeltable/blob/main/pixeltable/functions/openai.py#L0" id="viewSource" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/View%20Source%20on%20Github-blue?logo=github&labelColor=gray" alt="View Source on GitHub" style={{ display: 'inline', margin: '0px' }} noZoom /></a>

# <span style={{ 'color': 'gray' }}>module</span>  pixeltable.functions.openai

Pixeltable UDFs
that wrap various endpoints from the OpenAI API. In order to use them, you must
first `pip install openai` and configure your OpenAI credentials, as described in
the [Working with OpenAI](https://docs.pixeltable.com/notebooks/integrations/working-with-openai) tutorial.

## <span style={{ 'color': 'gray' }}>func</span>  invoke\_tools()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
invoke_tools(
    tools: pixeltable.func.tools.Tools,
    response: pixeltable.exprs.expr.Expr
) -> pixeltable.exprs.inline_expr.InlineDict
```

Converts an OpenAI response dict to Pixeltable tool invocation format and calls `tools._invoke()`.

## <span style={{ 'color': 'gray' }}>udf</span>  chat\_completions()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
chat_completions(
    messages: pxt.Json[(Json, ...)],
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None,
    tools: pxt.Json[(Json, ...)] | None = None,
    tool_choice: pxt.Json | None = None
) -> pxt.Json
```

Creates a model response for the given chat conversation.

Equivalent to the OpenAI `chat/completions` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/chat-completions](https://platform.openai.com/docs/guides/chat-completions)

Request throttling:
Uses the rate limit-related headers returned by the API to throttle requests adaptively, based on available
request and token capacity. No configuration is necessary.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`messages`** (`pxt.Json[(Json`): A list of messages to use for chat completion, as described in the OpenAI API documentation.
* **`model`** (`Any`): The model to use for chat completion.
* **`model_kwargs`** (`Any`): Additional keyword args for the OpenAI `chat/completions` API. For details on the available
  parameters, see: [https://platform.openai.com/docs/api-reference/chat/create](https://platform.openai.com/docs/api-reference/chat/create)

**Returns:**

* `pxt.Json`: A dictionary containing the response and other metadata.

**Examples:**

Add a computed column that applies the model `gpt-4o-mini` to an existing Pixeltable column `tbl.prompt`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': tbl.prompt},
]
tbl.add_computed_column(
    response=chat_completions(messages, model='gpt-4o-mini')
)
```

You can also include images in the messages list by passing image data directly in the input dictionary, in
the `'image_url'` field of the message content, as in this example:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
messages = [
    {
        'role': 'user',
        'content': [
            {'type': 'text', 'text': "What's in this image?"},
            {'type': 'image_url', 'image_url': tbl.image},
        ],
    }
]
tbl.add_computed_column(
    response=chat_completions(messages, model='gpt-4o-mini')
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  embeddings()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
embeddings(
    input: pxt.String,
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Array[(None,), float32]
```

Creates an embedding vector representing the input text.

Equivalent to the OpenAI `embeddings` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/embeddings](https://platform.openai.com/docs/guides/embeddings)

Request throttling:
Uses the rate limit-related headers returned by the API to throttle requests adaptively, based on available
request and token capacity. No configuration is necessary.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`input`** (`pxt.String`): The text to embed.
* **`model`** (`pxt.String`): The model to use for the embedding.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `embeddings` API. For details on the available
  parameters, see: [https://platform.openai.com/docs/api-reference/embeddings](https://platform.openai.com/docs/api-reference/embeddings)

**Returns:**

* `pxt.Array[(None,), float32]`: An array representing the application of the given embedding to `input`.

**Examples:**

Add a computed column that applies the model `text-embedding-3-small` to an existing
Pixeltable column `tbl.text` of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    embed=embeddings(tbl.text, model='text-embedding-3-small')
)
```

Add an embedding index to an existing column `text`, using the model `text-embedding-3-small`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_embedding_index(
    embedding=embeddings.using(model='text-embedding-3-small')
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  image\_edits()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
image_edits(
    image: pxt.Image,
    *,
    prompt: pxt.String,
    model: pxt.String,
    mask: pxt.Image | None = None,
    model_kwargs: pxt.Json | None = None
) -> pxt.Json
```

Creates an edited or extended image given a source image and a prompt.

Equivalent to the OpenAI `images/edits` API endpoint.
For additional details, see: [https://developers.openai.com/api/docs/guides/image-generation#edit-images](https://developers.openai.com/api/docs/guides/image-generation#edit-images)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`image`** (`pxt.Image`): The source image to edit.
* **`prompt`** (`pxt.String`): A text description of the desired edit.
* **`model`** (`pxt.String`): The model to use for image editing.
* **`mask`** (`pxt.Image | None`): An optional mask image. See: [https://developers.openai.com/api/reference/resources/images/methods/edit](https://developers.openai.com/api/reference/resources/images/methods/edit)
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `images/edits` API. For details on the available
  parameters, see: [https://developers.openai.com/api/reference/resources/images/methods/edit](https://developers.openai.com/api/reference/resources/images/methods/edit)

**Returns:**

* `pxt.Json`: A dictionary containing the edited image data. Images will be deserialized into `PIL.Image.Image` objects,
  and the result dictionary will have the following form:
  ```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
  {
      "created": 1234567890,
      "data": [
          PIL.Image.Image(...),
          ...
      ],
      "usage": <optional usage data, depending on model>
  }
  ```

**Examples:**

Edit an image with a text prompt:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    edited=image_edits(
        tbl.source_image,
        prompt='Add a sunset background',
        model='gpt-image-2',
    )
)
```

Edit an image with a mask to specify the edit area:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    edited=image_edits(
        tbl.source_image,
        mask=tbl.mask_image,
        prompt='Replace with a beach scene',
        model='gpt-image-2',
    )
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  image\_generations()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
image_generations(
    prompt: pxt.String,
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Json
```

Creates an image given a prompt.

Equivalent to the OpenAI `images/generations` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/images](https://platform.openai.com/docs/guides/images)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`prompt`** (`pxt.String`): Prompt for the image.
* **`model`** (`pxt.String`): The model to use for the generations. See the OpenAI docs for supported models.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `images/generations` API. For details on the available
  parameters, see: [https://developers.openai.com/api/reference/resources/images/methods/generate](https://developers.openai.com/api/reference/resources/images/methods/generate)

**Returns:**

* `pxt.Json`: A dictionary containing the generated image data. Images will be deserialized into `PIL.Image.Image` objects,
  and the result dictionary will have the following form:
  ```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
  {
      "created": 1234567890,
      "data": [
          PIL.Image.Image(...),
          PIL.Image.Image(...),
          ...
      ],
      "usage": <optional usage data, depending on model>
  }
  ```

**Examples:**

Add a computed column that applies the model `dall-e-2` to an existing
Pixeltable column `tbl.text` of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    gen_image=image_generations(tbl.text, model='dall-e-2')
)
```

Generate an image using the `gpt-image-2` model:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    gen_image=image_generations(tbl.text, model='gpt-image-2')
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  image\_variations()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
image_variations(
    image: pxt.Image,
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Json
```

Creates a variation of a given image.

Equivalent to the OpenAI `images/variations` API endpoint.
For additional details, see: [https://developers.openai.com/api/docs/guides/image-generation#image-variations](https://developers.openai.com/api/docs/guides/image-generation#image-variations)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`image`** (`pxt.Image`): The source image to create a variation of.
* **`model`** (`pxt.String`): The model to use for creating variations.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `images/variations` API. For details on the available
  parameters, see: [https://developers.openai.com/api/reference/resources/images/methods/create\_variation](https://developers.openai.com/api/reference/resources/images/methods/create_variation)

**Returns:**

* `pxt.Json`: A dictionary containing the variation image data. Images will be deserialized into `PIL.Image.Image` objects,
  and the result dictionary will have the following form:
  ```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
  {
      "created": 1234567890,
      "data": [
          PIL.Image.Image(...),
          ...
      ]
  }
  ```

**Examples:**

Generate a variation of an existing image:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    variation=image_variations(tbl.source_image, model='dall-e-2')
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  moderations()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
moderations(
    input: pxt.String,
    *,
    model: pxt.String = 'omni-moderation-latest'
) -> pxt.Json
```

Classifies if text is potentially harmful.

Equivalent to the OpenAI `moderations` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/moderation](https://platform.openai.com/docs/guides/moderation)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`input`** (`pxt.String`): Text to analyze with the moderations model.
* **`model`** (`pxt.String`): The model to use for moderations.

**Returns:**

* `pxt.Json`: Details of the moderations results.

**Examples:**

Add a computed column that applies the default moderation model to an existing Pixeltable column `tbl.input`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(moderations=moderations(tbl.input))
```

## <span style={{ 'color': 'gray' }}>udf</span>  responses()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
responses(
    input: pxt.Json[(Json, ...)],
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None,
    tools: pxt.Json[(Json, ...)] | None = None,
    tool_choice: pxt.Json | None = None
) -> pxt.Json
```

Creates a model response for the given input.

Equivalent to the OpenAI `responses` API endpoint.
For additional details, see: [https://developers.openai.com/api/docs/guides/migrate-to-responses](https://developers.openai.com/api/docs/guides/migrate-to-responses)

Request throttling:
Uses the rate limit-related headers returned by the API to throttle requests adaptively, based on available
request and token capacity. No configuration is necessary.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`input`** (`pxt.Json[(Json`): A list of input items for the model, as described in the OpenAI API documentation.
* **`model`** (`Any`): The model to use for generating a response.
* **`model_kwargs`** (`Any`): Additional keyword args for the OpenAI `responses` API. For details on the available
  parameters, see: [https://developers.openai.com/api/docs/api-reference/responses/create](https://developers.openai.com/api/docs/api-reference/responses/create)
  Common options include `instructions`, `temperature`, `max_output_tokens`, `reasoning`, `text`
  (for structured outputs), `previous_response_id` (for multi-turn), and `store`.

**Returns:**

* `pxt.Json`: A dictionary containing the response and other metadata. The response text is accessible via
  the `output_text` field for simple cases, or through the `output` list for structured access.

**Examples:**

Add a computed column that applies the model `gpt-4o-mini` to an existing Pixeltable column `tbl.prompt`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
messages = [{'role': 'user', 'content': tbl.prompt}]
tbl.add_computed_column(
    response=responses(
        messages,
        model='gpt-4o-mini',
        model_kwargs={'instructions': 'You are a helpful assistant.'},
    )
)
```

You can also include images in the input list by passing image data directly, using the Responses API
`input_image` content type:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
messages = [
    {
        'role': 'user',
        'content': [
            {'type': 'input_text', 'text': "What's in this image?"},
            {'type': 'input_image', 'image_url': tbl.image},
        ],
    }
]
tbl.add_computed_column(response=responses(messages, model='gpt-4o-mini'))
```

## <span style={{ 'color': 'gray' }}>udf</span>  speech()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
speech(
    input: pxt.String,
    *,
    model: pxt.String,
    voice: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Audio
```

Generates audio from the input text.

Equivalent to the OpenAI `audio/speech` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/text-to-speech](https://platform.openai.com/docs/guides/text-to-speech)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`input`** (`pxt.String`): The text to synthesize into speech.
* **`model`** (`pxt.String`): The model to use for speech synthesis.
* **`voice`** (`pxt.String`): The voice profile to use for speech synthesis. Supported options include:
  `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `audio/speech` API. For details on the available
  parameters, see: [https://platform.openai.com/docs/api-reference/audio/createSpeech](https://platform.openai.com/docs/api-reference/audio/createSpeech)

**Returns:**

* `pxt.Audio`: An audio file containing the synthesized speech.

**Examples:**

Add a computed column that applies the model `tts-1` to an existing Pixeltable column `tbl.text`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    audio=speech(tbl.text, model='tts-1', voice='nova')
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  transcriptions()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
transcriptions(
    audio: pxt.Audio,
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Json
```

Transcribes audio into the input language.

Equivalent to the OpenAI `audio/transcriptions` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/speech-to-text](https://platform.openai.com/docs/guides/speech-to-text)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`audio`** (`pxt.Audio`): The audio to transcribe.
* **`model`** (`pxt.String`): The model to use for speech transcription.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `audio/transcriptions` API. For details on the available
  parameters, see: [https://platform.openai.com/docs/api-reference/audio/createTranscription](https://platform.openai.com/docs/api-reference/audio/createTranscription)

**Returns:**

* `pxt.Json`: A dictionary containing the transcription and other metadata.

**Examples:**

Add a computed column that applies the model `whisper-1` to an existing Pixeltable column `tbl.audio`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    transcription=transcriptions(
        tbl.audio, model='whisper-1', language='en'
    )
)
```

## <span style={{ 'color': 'gray' }}>udf</span>  translations()

```python Signature theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
@pxt.udf
translations(
    audio: pxt.Audio,
    *,
    model: pxt.String,
    model_kwargs: pxt.Json | None = None
) -> pxt.Json
```

Translates audio into English.

Equivalent to the OpenAI `audio/translations` API endpoint.
For additional details, see: [https://platform.openai.com/docs/guides/speech-to-text](https://platform.openai.com/docs/guides/speech-to-text)

Request throttling:
Applies the rate limit set in the config (section `openai.rate_limits`; use the model id as the key). If no rate
limit is configured, uses a default of 600 RPM.

**Requirements:**

* `pip install openai`

**Parameters:**

* **`audio`** (`pxt.Audio`): The audio to translate.
* **`model`** (`pxt.String`): The model to use for speech transcription and translation.
* **`model_kwargs`** (`pxt.Json | None`): Additional keyword args for the OpenAI `audio/translations` API. For details on the available
  parameters, see: [https://platform.openai.com/docs/api-reference/audio/createTranslation](https://platform.openai.com/docs/api-reference/audio/createTranslation)

**Returns:**

* `pxt.Json`: A dictionary containing the translation and other metadata.

**Examples:**

Add a computed column that applies the model `whisper-1` to an existing Pixeltable column `tbl.audio`
of the table `tbl`:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
tbl.add_computed_column(
    translation=translations(tbl.audio, model='whisper-1', language='en')
)
```
