Skip to main content
Use OpenAI’s powerful language models directly from with . These functions enable you to generate embeddings, complete chat conversations, moderate content, and work with tokens without leaving your database.

Prerequisites

To use OpenAI functions, you need an OpenAI API key. Set your API key as an environment variable and configure it when connecting:
export OPENAI_API_KEY="your-api-key"
PGOPTIONS="-c ai.openai_api_key=$OPENAI_API_KEY" psql -d "postgres://..."
For more configuration options, see handling API keys.

Samples

Create embeddings from text for vector similarity search:
SELECT ai.openai_embed(
    'text-embedding-ada-002',
    'PostgreSQL is a powerful database'
);

Complete a chat conversation

Use GPT models for natural language responses:
SELECT ai.openai_chat_complete(
    'gpt-4o-mini',
    jsonb_build_array(
        jsonb_build_object('role', 'user', 'content', 'What is PostgreSQL?')
    )
)->'choices'->0->'message'->>'content';

Moderate content

Check if content violates OpenAI’s usage policies:
SELECT ai.openai_moderate(
    'text-moderation-latest',
    'some text to check'
);

Tokenize text

Count tokens to manage API costs and limits:
SELECT array_length(
    ai.openai_tokenize('text-embedding-ada-002', 'Hello world'),
    1
) as token_count;

Available functions

Model management

Embeddings

  • openai_embed(): generate vector embeddings from text, text arrays, or tokens

Chat completion

Content moderation

Token management

Advanced usage