AI functions in the azure_ai extension in Azure HorizonDB

Important

The AI function guidance in this article uses the ai schema in the azure_ai extension version 2.5.6 or later. Pipeline builders use the ai.*_step() names. For earlier versions or existing azure_ai.* and azure_openai.create_embeddings() calls, see Migrate AI functions to the ai schema for version checks, API differences, upgrade steps, and the HorizonDB legacy reference.

The azure_ai extension introduces AI functions, a feature that integrates advanced Generative AI (GenAI) capabilities directly into PostgreSQL SQL. By using these functions with models like chat-completion, embeddings, reranking, and other Microsoft Foundry model deployments, you can build GenAI-driven applications directly within your database. This integration unlocks new capabilities for generating vector embeddings, reranking vector search results, understanding text, reasoning, and generating structured outputs.

Key features

The AI functions provide five core SQL functions that use generative AI capabilities:

  • ai.generate(): Generates text or structured output by using large language models (LLMs).
  • ai.is_true(): Evaluates the likelihood that a given statement is true.
  • ai.extract(): Extracts structured features or entities from text.
  • ai.rank(): Reranks a list of documents based on relevance to a given query.
  • ai.embed(): Creates vector embeddings for a given input text.

Each function operates through model endpoints registered in the model registry or through Managed Models provisioned by AI Model Management (Preview), ensuring seamless integration and user control.

The extension also provides ai.search(), a table-search function that combines vector retrieval, BM25 keyword matching, and optional semantic reranking. It returns row locations and scores that you join to your source table. Unlike a single model invocation, it orchestrates retrieval over your indexed data.

Enable the azure_ai extension and register models

Before you can use AI functions, you need to enable the azure_ai extension and register the AI models you want to use.

Option 1: Use AI Model Management

When you enable AI Model Management (Preview) on your Azure HorizonDB instance, you get a turnkey experience that automatically:

  1. Installs and configures the azure_ai extension.

  2. Provisions and registers three managed models:

    • gpt-5.4 for chat completion (alias: default-chat).
    • text-embedding-3-small for embeddings (alias: default-embedding).
    • Cohere-rerank-v4.0-fast for reranking (alias: default-reranker).
  3. Establishes secure connections to the model endpoints.

After you enable AI Model Management, you can immediately start using AI functions without additional configuration.

Option 2: Manual setup with model registry

If you prefer to use your own Microsoft Foundry models (Bring Your Own Model), follow these steps:

  1. Before you can enable azure_ai on your Azure HorizonDB instance, add it to your allow list as described in how to use PostgreSQL extensions. Check if it's correctly added by running SHOW azure.extensions;.

  2. Install the azure_ai extension on your database by running the following command:

    CREATE EXTENSION IF NOT EXISTS azure_ai;
    

    Tip

    These examples require azure_ai 2.5.6 or later. Check your installed version and follow Upgrade to azure_ai 2.5.6 if needed.

  3. Deploy a model through Microsoft Foundry. Select the model you want to use (for example, gpt-5.4 or text-embedding-3-small) and complete the deployment.

  4. In the Microsoft Foundry dashboard, navigate to your project and note the API key and the endpoint URL. The following endpoint formats are supported:

    • https://<your-resource-name>.services.ai.azure.com/ (Microsoft Foundry)
    • https://<your-resource-name>.openai.azure.com/ (Azure OpenAI)
    • https://<your-resource-name>.cognitiveservices.azure.com/ (Azure AI Services)
  5. Navigate to your model deployment and note the following values:

    • Deployment name: The name you assigned during deployment, such as gpt-5-deployment.
    • Model name: The underlying model name, such as gpt-5.4.
  6. Register the model in the model registry.

    Syntax:

    SELECT model_registry.model_add(
        '<model-alias>',              -- a unique, custom identifier for your model
        '<endpoint-URL>',             -- your model endpoint URL (see supported formats above)
        '<deployment-name>',          -- the deployment name of your model
        '<model-name>',               -- the model name (for example, gpt-5.4, text-embedding-3-small)
        '<API-version>',              -- the API version (NULL for latest)
        'subscription-key',          -- the only supported auth type for BYOM
        '<endpoint-key>'              -- required endpoint key
    );
    

    Example:

    SELECT model_registry.model_add(
        'my-gpt',
        'https://my-endpoint.services.ai.azure.com/',
        'gpt-5-deployment',
        'gpt-5',
        '2025-01-01-preview',
        'subscription-key',
        '<your-endpoint-key>'
    );
    
  7. You're now ready to invoke AI functions by using your registered model alias.

BYOM registration requires subscription-key authentication and an endpoint key. Use subscription-key; to update an existing key, call model_registry.model_key_update().

Tip

You can also register models with Azure API Management (APIM) endpoints to route requests through APIM for load balancing, monitoring, or policy enforcement.

View registered models

To view all models registered in the model registry, run:

SELECT * FROM model_registry.model_list_all();

Upgrade to azure_ai 2.5.6

For an end-to-end migration checklist, before-and-after SQL, and the HorizonDB legacy reference, see Migrate AI functions to the ai schema.

Version 2.5.6 includes the complete ai.* direct-inference API and *_step pipeline-builder naming used in this documentation. The examples, parameter names, argument order, defaults, and return types on this page target azure_ai 2.5.6 or later. The extension is still named azure_ai; ai is the SQL schema used by these functions.

Check the installed and available versions

Run these queries in each database that uses the extension:

SELECT extversion
FROM pg_extension
WHERE extname = 'azure_ai';

SELECT version
FROM pg_available_extension_versions
WHERE name = 'azure_ai' AND version = '2.5.6';

If the installed version is already 2.5.6 or later, don't downgrade it. If you need to upgrade but 2.5.6 isn't available, wait for the service update. The extension update command doesn't download extension files.

Upgrade each database

When 2.5.6 is available and your installed version is earlier, an authorized administrator runs the following command on the primary (read-write) endpoint in each database being upgraded:

ALTER EXTENSION azure_ai UPDATE TO '2.5.6';

Repeat the pg_extension query to confirm the installed version. Updating one database doesn't update other databases on the same cluster. Don't run individual ALTER FUNCTION statements; PostgreSQL executes the bundled migrations.

Update application SQL

Use the direct-inference functions in the ai schema:

Operation Older function Direct-inference function in 2.5.6
Generate text or structured output azure_ai.generate() ai.generate()
Extract entities azure_ai.extract() ai.extract()
Evaluate a statement azure_ai.is_true() ai.is_true()
Rerank documents azure_ai.rank() ai.rank()
Create embeddings azure_openai.create_embeddings() ai.embed()

The older inference functions remain available, but changing only the schema or function name isn't sufficient: argument names and order can differ. Use named arguments and the signatures in Use AI functions.

For pipeline-creation SQL, use ai.embed_step(), ai.extract_step(), ai.generate_step(), ai.rank_step(), ai.is_true_step(), and ai.chunk_step(). These builders return JSONB descriptors for deferred execution, not direct-inference results. Existing stored pipeline descriptors and source/sink tables remain unchanged; pipelines don't need to be recreated. For the builder migration table and examples, see Upgrade AI pipelines to azure_ai 2.5.6.

Use AI functions

AI functions in the azure_ai extension simplify complex AI-driven tasks directly within your PostgreSQL database. You can seamlessly integrate generative AI capabilities into your SQL workflows to perform advanced text generation, truth evaluation, entity extraction, document ranking, and vector embedding creation. Each function is optimized for ease of use and flexibility, so you can build intelligent applications with minimal effort.

Tip

When you omit model in the default overloads shown here, the function uses the corresponding alias (default-chat, default-embedding, or default-reranker). These aliases must already be registered, for example through AI Model Management (Preview). The ai.generate() overloads that take max_tokens require explicit model and system_prompt arguments.

Use the ai schema for direct inference. The older azure_ai.* and azure_openai.create_embeddings() functions remain available, but their argument names and order can differ. In particular, ai.embed() takes text, not input; ai.extract() takes text, model, then data; and ai.rank() takes data, optional ids, optional top_n, then model. Use named arguments rather than copying positional arguments from the older APIs.

Important

Use azure_ai 2.5.6 or later for this API guidance. Unsuffixed ai.* functions perform direct inference immediately; ai.*_step() builders describe deferred pipeline work. For older databases and existing callers, follow Migrate AI functions to the ai schema.

ai.embed()

Use this function to create vector embeddings for a given input text. Vector embeddings are numerical representations of text that capture semantic meaning, enabling similarity search, clustering, and other vector-based operations.

It supports the following input parameters:

Argument Type Description
text text or text[] Input text, or an array of texts for batch embedding.
model (optional) text Model alias registered in the model registry. When omitted, uses the default-embedding Managed Model.
batch_size (optional) integer Maximum texts per request. Defaults to 100.
dimensions (optional) integer Requested embedding dimensions, when supported by the model. Defaults to NULL, which uses the model's default dimensions.
retry_attempts (optional) integer Total attempts, including the initial request. SQL default is NULL, which uses three attempts.
retry_delay_ms (optional) integer Initial retry delay in milliseconds. Defaults to 1000.

Signatures:

ai.embed(text text, model text DEFAULT 'default-embedding',
         batch_size integer DEFAULT 100, dimensions integer DEFAULT NULL,
         retry_attempts integer DEFAULT NULL, retry_delay_ms integer DEFAULT 1000)
    RETURNS real[]

ai.embed(text text[], model text DEFAULT 'default-embedding',
         batch_size integer DEFAULT 100, dimensions integer DEFAULT NULL,
         retry_attempts integer DEFAULT NULL, retry_delay_ms integer DEFAULT 1000)
    RETURNS TABLE (embedding real[])

The scalar overload returns real[], not a vector value. Cast it to vector for pgvector storage or distance operators. The batch overload returns one embedding real[] row per input text. Use the same model and dimensions for stored embeddings and queries.

Example usage:

SELECT ai.embed(
    text  => 'Alternatives to Lego',
    model => 'my-embedding'
) AS embedding_vector;

Embed a batch of texts:

SELECT *
FROM ai.embed(
    text  => ARRAY['Alternatives to Lego', 'Building blocks for children'],
    model => 'my-embedding'
);

Generate and store embeddings for a table column:

ALTER TABLE products
ADD COLUMN description_vector vector(1536);

UPDATE products SET description_vector = ai.embed(
    text       => product_description,
    model      => 'my-embedding',
    dimensions => 1536
)::vector
WHERE description_vector IS NULL;

Perform vector search with ai.embed():

SELECT product_name, product_description
FROM products
ORDER BY description_vector <=> ai.embed(
    text       => 'Alternatives to LEGO',
    model      => 'my-embedding',
    dimensions => 1536
)::vector ASC
LIMIT 10;

ai.generate()

Use this function to generate text or structured output by using LLMs.

It supports the following input parameters:

Argument Type Description
prompt text User prompt to send to the LLM.
model (optional) text Model alias registered in the model registry. When omitted, uses the default-chat Managed Model.
json_schema jsonb Required for the structured-output overload; omit it for text generation. Must follow the OpenAI notation for structured output. It has no default value.
system_prompt (optional) text DEFAULT 'You are a helpful assistant.' System prompt to send to the LLM.
max_tokens integer Optional completion-token limit through a separate overload. When you supply it, also supply model and system_prompt; none of these three arguments has a default in that overload. Otherwise, the function uses azure_ai.max_tokens (default 2000).

Signatures:

ai.generate(prompt text, model text DEFAULT 'default-chat',
            system_prompt text DEFAULT 'You are a helpful assistant.')
    RETURNS text

ai.generate(prompt text, model text, system_prompt text, max_tokens integer)
    RETURNS text

ai.generate(prompt text, json_schema jsonb, model text DEFAULT 'default-chat',
            system_prompt text DEFAULT 'You are a helpful assistant.')
    RETURNS jsonb

ai.generate(prompt text, json_schema jsonb, model text, system_prompt text,
            max_tokens integer)
    RETURNS jsonb

Without json_schema, the function returns text. Supplying json_schema selects a different overload that returns jsonb.

Example usage:

SELECT ai.generate(
    prompt => 'Rewrite the following comment to be more polite: ' || comment_text,
    model  => 'my-gpt'
) AS polite_comment
FROM user_comments;

Generate structured output with JSON schema:

SELECT review, ai.generate(
    prompt      => 'Rewrite the following comment to be more polite and return the number of products mentioned:' || review,
    json_schema => '{
                      "name": "generate_response",
                      "description": "Generate a response to the user",
                      "strict": true,
                      "schema": {
                        "type": "object",
                        "properties": {
                          "comment": { "type": "string" },
                          "num_products": { "type": "integer" }
                        },
                        "required": ["comment", "num_products"],
                        "additionalProperties": false
                      }
                    }',
    model       => 'my-gpt'             -- model alias
) AS polite_comment_with_count
FROM Reviews;

Set an explicit completion-token limit:

SELECT ai.generate(
    prompt        => 'Explain vector search in one sentence.',
    model         => 'my-gpt',
    system_prompt => 'You are a helpful assistant.',
    max_tokens    => 200
);

ai.extract()

Use this function to extract structured features or entities from text based on user-defined labels.

It supports the following input parameters:

Argument Type Description
text text A document containing the entities and features.
model (optional) text Model alias registered in the model registry. When omitted, uses the default-chat Managed Model.
data text[] Required non-NULL array of labels or feature names. The SQL signature defaults this argument to NULL, but the function rejects an omitted or NULL value.

Signature:

ai.extract(text text, model text DEFAULT 'default-chat', data text[] DEFAULT NULL)
    RETURNS jsonb

The function returns a jsonb object containing the extracted entities mapped to their corresponding labels. Always pass data by name when omitting model.

Example usage:

SELECT ai.extract(
    text  => 'The headphones are not great. They have a good design, but the sound quality is poor and the battery life is short.',
    data  => ARRAY['product', 'sentiment'],
    model => 'my-gpt'
);

-- Output: {"product": "headphones", "sentiment": "negative"}

Extract with detailed labels:

SELECT ai.extract(
    text => 'The music quality is good, though the call quality could have been better. The design is sleek, but still slightly heavy for convenient travel.',
    data => ARRAY[
        'design: string - comma separated list of design features of the product',
        'sound: string - sound quality (e.g., music, call, noise cancellation) of the product',
        'sentiment: number - sentiment score of the review; 1 (lowest) to 5 (highest)'
    ],
    model => 'my-gpt'
);

-- Output: {"sound": "music quality is good, call quality could have been better", "design": "sleek, slightly heavy", "sentiment": 3}

ai.is_true()

This function evaluates the likelihood that a given statement is true. It returns a boolean value or NULL if the result is inconclusive.

It supports the following input parameters:

Argument Type Description
statement text Statement to evaluate as true or false.
model (optional) text Model alias registered in the model registry. When omitted, uses the default-chat Managed Model.

Signature:

ai.is_true(statement text, model text DEFAULT 'default-chat')
    RETURNS boolean

Example usage:

SELECT ai.is_true(
    statement => 'The review talks about the product: ' || product_name || ' Review: ' || review_text,
    model     => 'my-gpt'
) AS is_relevant_review
FROM product_reviews;

ai.rank()

Use this function to rerank documents based on their relevance to a given query. It supports cross-encoder and GPT models.

It supports the following input parameters:

Argument Type Description
query text The search string used to evaluate and rank the relevance of each document.
data text[] An array of documents to rerank.
ids anyarray Optional through the overload with IDs. Supply one non-NULL identifier per document, in the same order as data.
top_n (optional) integer Maximum results to return. Defaults to NULL (all results); an explicit value must be greater than zero.
model (optional) text Model alias registered in the model registry. When omitted, uses the default-reranker Managed Model.

Signatures:

ai.rank(query text, data text[], top_n integer DEFAULT NULL,
        model text DEFAULT 'default-reranker')
    RETURNS TABLE (id bigint, rank bigint, score double precision)

ai.rank(query text, data text[], ids anyarray, top_n integer DEFAULT NULL,
        model text DEFAULT 'default-reranker')
    RETURNS TABLE (id anyelement, rank bigint, score double precision)

The function returns a table with id, rank, and score. Without ids, id is the zero-based input-document index. With ids, id has the element type of the supplied array. Use SELECT * FROM ai.rank(...) to expose these columns.

Example usage:

SELECT *
FROM ai.rank(
    query => 'Best headphones for travel',
    data  => ARRAY[
        'The headphones are lightweight and foldable, making them easy to carry.',
        'Bad battery life, not so great for long trips.',
        'The sound quality is excellent, with good noise isolation.'
    ],
    model => 'my-reranker'
);

Combine vector search with semantic reranking:

WITH potential_toys AS (
    SELECT id AS product_id, title AS product_name, text_content AS product_description
    FROM products
    ORDER BY embedding <=> ai.embed(
        text => 'Alternatives to LEGO'
    )::vector ASC
    LIMIT 10
),
reranked_results AS (
    SELECT
        id AS row_id, rank
    FROM ai.rank(
        query => 'Alternatives to LEGO',
        data  => ARRAY(SELECT 'Product Description: ' || product_description FROM potential_toys ORDER BY product_id),
        ids   => ARRAY(SELECT product_id FROM potential_toys ORDER BY product_id),
        model => 'my-reranker'
    )
)
SELECT
    pt.product_id,
    pt.product_name
FROM potential_toys pt
LEFT JOIN reranked_results rr ON (rr.row_id = pt.product_id)
ORDER BY rr.rank ASC;

Search indexed tables with ai.search()

Use ai.search() to run vector, full-text, or hybrid search through one SQL interface. Hybrid mode combines rankings with Reciprocal Rank Fusion; rerank => true adds semantic reranking. For a complete, runnable example, the function signature, and index requirements, see AI search with ai.search.

The walkthrough uses the synchronous ai.embed(text => ..., model => ..., dimensions => ...) function to populate stored embeddings. In version 2.5.6 or later, use ai.embed_step(input => ...) to build an AI pipeline step instead.

Manage models in the model registry

The model registry provides a centralized interface for managing all AI model endpoints. You can register, update, and remove models by using SQL functions.

Register a model

SELECT model_registry.model_add(
    '<model-alias>',                -- a unique, custom identifier for your model
    '<model-endpoint-URL>',         -- your model endpoint URL (see Enable the azure_ai extension and register models)
    '<model-deployment-name>',      -- the deployment name of your model
    '<model-name>',                 -- the model name (for example, gpt-5.4, text-embedding-3-small)
    '<API-version>',                -- the API version (NULL for latest)
    'subscription-key',            -- the only supported auth type for BYOM
    '<model-endpoint-key>'          -- required endpoint key
);

Remove a model

SELECT model_registry.model_remove('<your-model-alias>');

Update a model alias

SELECT model_registry.model_alias_update('<your-model-alias>', '<new-model-alias>');

Update model metadata

Update individual or multiple metadata fields for a registered model:

SELECT model_registry.model_update(
    '<your-model-alias>',
    '{
        "endpoint": "<your-new-endpoint-URL>",
        "auth_type": "subscription-key",
        "model_name": "<your-new-model-name>",
        "deployment_name": "<your-new-deployment-name>",
        "api_version": "<your-new-api-version>"
    }'
);

Update an API key

SELECT model_registry.model_key_update(
    '<your-model-alias>',
    '<your-new-endpoint-key>'
);

User access management

When you register a model, either by using Managed Models (when AI Model Management is enabled) or as a user, all database users can use the model by default. Use the model_user_add, model_user_set, and model_user_remove functions to explicitly manage and restrict access to models in the registry. This capability is useful for Bring Your Own Model (BYOM) entries, which might have associated costs or data privacy considerations.

Roles

In addition to the built-in azure_pg_admin role, the model_registry_manager role has permissions to use, add, remove, and update models in the model registry, and manage user access to those models. A regular user can also register a model, and unless you define a specific user set, the model remains accessible to all other users. You can update models either by the user who created them or by users with the appropriate privileges (azure_pg_admin or model_registry_manager).

Assign the model_registry_manager role to a user:

CREATE USER registry_manager;
GRANT model_registry_manager TO registry_manager;

Grant access to specific users

Use model_user_add to grant a specific user access to a model:

SELECT model_registry.model_user_add('<your-model-alias>', 'target_user');

After you add at least one user, only the specified users can invoke AI functions with that model. Other users receive an error.

Set a complete user access list

Use model_user_set to replace the entire access list for a model with a new set of users:

SELECT model_registry.model_user_set('<your-model-alias>', ARRAY['user1', 'user2']);

Important

The model_user_set function replaces the previous access list. With a nonempty list, users not included lose access to the model. An empty list means all database users can use the model; it isn't a deny-all setting.

Verify user access

To verify a user's access, set the role and attempt to invoke an AI function:

SET ROLE target_user;
SELECT ai.generate(
    prompt => 'Rewrite the following comment to be more polite: This product is the worst.',
    model  => 'my-gpt'
);
RESET ROLE;

Remove user access

Use model_user_remove to revoke a specific user's access to a model:

SELECT model_registry.model_user_remove('<your-model-alias>', 'target_user');

Removing the last listed user leaves an empty access list and makes the model available to all database users again. Keep a nonempty list when you intend to restrict access.

Supported models

The following table lists the models supported by each AI function.

Function Supported models
ai.generate() All GPT and o-series models, except gpt-5.4-pro.
ai.extract() All GPT and o-series models, except gpt-5.4-pro.
ai.is_true() All GPT and o-series models, except gpt-5.4-pro.
ai.embed() text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002.
ai.rank() All GPT models listed previously, Cohere-rerank-v4.0-pro, Cohere-rerank-v4.0-fast.

Model-kind validation

The extension infers the model kind from the registered model name, not the alias. A clearly incompatible kind, such as an embedding model used for generation or a chat model used for embeddings, fails before a request is sent to Azure. Ranking accepts chat models for LLM-based ranking as well as supported dedicated rerankers.

Names that don't identify a known kind aren't rejected by the kind check. If a generation model isn't on the built-in structured-output support list, the extension emits a warning and attempts the call. A warning doesn't guarantee that the endpoint supports the requested operation. Models whose names contain audio-preview or realtime are rejected.

Reranker routing is separate from kind validation. Model names containing cohere use the Cohere serverless rerank API. Other names identified as dedicated rerankers, such as bge-reranker, fail before a network call; they aren't routed to the Cohere API. Chat-capable models use LLM-based ranking.

Use AI functions on reader nodes

You can run read-only AI calls and model_registry.model_list_all() on a reader node. This capability includes a SELECT statement that invokes an AI model, but it doesn't include an UPDATE statement that stores the result on a reader node.

Operations that change model registrations, keys, access lists, or extension settings require the primary endpoint. Pipeline creation, manual execution, backfill, pause, resume, and deletion also require the primary endpoint. On a reader node, these operations fail and provide a hint to connect to the primary (read-write) endpoint. These operations also fail inside an explicitly read-only transaction on the primary endpoint. Use a read-write transaction on the primary endpoint.

Troubleshoot AI calls

Model alias isn't registered

An unregistered alias fails with SQLSTATE 42704 (undefined_object). The error message names the alias and suggests listing the registered models:

SELECT * FROM model_registry.model_list_all();

Use an alias from this list that you're authorized to access, or register a BYOM model on the primary endpoint. Omitting model also fails with 42704 if the corresponding default alias isn't registered. An empty or whitespace-only alias fails with SQLSTATE 22023 (invalid_parameter_value).

Embedding calls are rate-limited

Embedding calls retry transient failures, including HTTP 429 responses with RateLimitReached, within their configured attempt limit. The wait uses the longer of exponential backoff and the service's retry hint, capped at 60 seconds per retry. The extension reads retry-after-ms first, then an integer-seconds Retry-After header. HTTP-date retry hints aren't supported.

Rate-limited calls can therefore take longer instead of failing immediately. The 60-second cap applies to each wait, not to the total call duration. Calls still fail after their attempts are exhausted. For direct ai.embed() calls, use retry_attempts and retry_delay_ms; for azure_openai.create_embeddings(), use max_attempts and retry_delay_ms. Both default to three total attempts, including the initial request, and a 1,000-millisecond initial delay. Don't assume the same retry parameters exist on generation functions.