Step-by
local graph
Chapter 18 — Step-by
Section titled “Chapter 18 — Step-by”Step-by-Step Approach to Integrating LLMs with PostgreSQL to Create Complete AI Applications
Section titled “Step-by-Step Approach to Integrating LLMs with PostgreSQL to Create Complete AI Applications”So far, we have been on a bit of an adventure. We’ve learned that vectors are like containers of meaning—mathematical fingerprints that help us understand the “vibe” of the data. We’ve seen how vectors can add a layer of semantic magic to otherwise ordinary database records, and we have become comfortable with storing those embeddings as vector data in PostgreSQL.
Not every vector in PostgreSQL is an AI embedding used to represent meaning and support AI operations. In Chapter 14*,* Analyzing Text Documents in PostgreSQL, we saw that PostgreSQL also supports text search for powerful full-text searching. In this chapter, we will show you how to connect PostgreSQL to an LLM to generate AI vectors for data that is stored in PostgreSQL and for queries.
This chapter covers the following topics:
- How to use cURL to send text to an LLM and return the vector that represents the embedding, or meaning, of the text
- How to use Python to do the same thing
- How to move that operation inside the database, using PL/Python
- Ways to generate embeddings for larger collections of data
- How to generate the embedding for a query term
- How to combine AI vectors and SQL data to create a Spotify-style recommendation engine
Your purchase includes a free PDF copy + code bundle
Technical requirements
Section titled “Technical requirements”We will illustrate these concepts using the OpenAI API, which has been adopted by other LLM providers, including DeepSeek, Meta AI, and Mistral. To follow the examples in this chapter, you will need an API key from OpenAI.
The sample code for this chapter can be found in psql_scripts/sample_scripts/chapter_18.sql. We encourage you to follow the examples!
Creating an embedding with cURL
Section titled “Creating an embedding with cURL”We will start with the most basic tool in the toolbox: cURL, pronounced curl. cURL is a free and open source command-line tool for uploading and downloading individual files from a web server over HTTP. It is included in macOS, Linux, and Windows distributions.
If you haven’t worked with cURL yet, think of it as the friendly little command-line critter that lets you talk to web services. The following example is like knocking politely on OpenAI’s digital door and saying, “Hey, could you turn this sentence into an embedding for me?”
Here’s how we do it in the simplest way:
- First, get your API key from OpenAI’s website. This key is like your secret handshake, allowing OpenAI to recognize you.
- Now, let’s use the
curlcommand: Open your terminal, replaceYOUR_API_KEYwith the API key that you received from OpenAI, and run the following command:curl https://api.openai.com/v1/embeddings \-H "Authorization: Bearer YOUR_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "text-embedding-3-small","input": "Here is the text I want to turn into an embedding."}'
This command tells OpenAI, “Here’s my key, here’s the text, and I’d like an embedding generated by the model called text-embedding-3-small, please.” And voilà! OpenAI will respond with a vector that you can store and use as follows:
"object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [ -0.008902248, 0.021756759,……… ] } ], "model": "text-embedding-3-small", "usage": { "prompt_tokens": 12, "total_tokens": 12 }}Besides returning the vector of embeddings in JSON format, it also tells us how many tokens we consumed.
Moving from cURL to Python: A simple embedding script
Section titled “Moving from cURL to Python: A simple embedding script”Now we will move that same OpenAI API call to Python. These will be our first steps into a more automated world, so we’ll keep it friendly and practical.
- Set up the Python environment.
- Create a simple Python script to request the embedding.
- Run the script and inspect the results.
Setting up the Python environment
Section titled “Setting up the Python environment”Install Python (version 3.12 or later) and ensure that pip is available with the basic web request libraries installed. We recommend using a virtual environment (venv) to keep dependencies isolated. They are like the Swiss Army knife for web requests in Python.
Just run
python3 -m venv .venv && source .venv/bin/activate.Creating the Python script
Section titled “Creating the Python script”Now, we’ll write a simple Python script that sends a piece of text to OpenAI and gets back an embedding. We’ll keep it light and breezy. Replace YOUR_API_KEY with the same OpenAI API key that you used for the curl example:
import jsonimport sslimport timeimport randomimport urllib.requestimport urllib.error
# Your OpenAI API keyapi_key = 'YOUR_API_KEY'
# The text you want to embedinput_text = "Here is the text I want to turn into an embedding."
# The endpoint and headersurl = "https://api.openai.com/v1/embeddings"headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
# The data payloaddata = { "model": "text-embedding-3-small", "input": input_text}
# Make the requestrequest = urllib.request.Request( url, data=json.dumps(data).encode('utf-8'), headers=headers, method='POST')try: with urllib.request.urlopen(request) as resp: resp_data = json.load(resp) embedding = resp_data['data'][0]['embedding'] print("Embedding:", embedding)except urllib.error.HTTPError as e: print("Error:", e.code, e.read().decode())The Python program transforms plain text into an embedding. Think of it as a one-question conversation with an AI service using Python instead of cURL: we hand it a sentence, and it hands us back a vector (an ordered list of numbers that captures the meaning of that sentence in a form computers can compare and search).
The script begins by importing a few standard Python modules. json is there because the OpenAI API uses JavaScript Object Notation (JSON): we send JSON in the request body and receive JSON back in the response.
The urllib.request module is the workhorse that makes the HTTP call, and urllib.error helps us handle failures cleanly if the server returns an error. You’ll also notice ssl, time, and random imported as well. In this minimal version, they are not strictly required, but they are commonly used when you later evolve this script into something more resilient—for example, when you add secure TLS handling or implement retry-and-backoff logic for temporary network or rate-limit issues. In other words, they’re the “future-proofing tools” sitting on the bench, ready for the next chapter of the story.
Next, the program defines two essential inputs: the API key and the text we want to embed. The API key serves as your credentials and identifies you to OpenAI. The text is the raw material we want to transform into an embedding. In this example, the text is a simple sentence, but it could just as easily be a product description, a customer complaint, a support ticket, or a paragraph from a policy document.
With those pieces in place, the program prepares the API request. It points to the embeddings endpoint (/v1/embeddings) and constructs HTTP headers that describe who we are and what we are sending. The Authorization header carries the API key as a bearer token, which is the standard way modern APIs authenticate requests. The Content-Type header is set to application/json, indicating that the request body contains JSON rather than plain text or another format.
The heart of the request is the payload itself. The program builds a small JSON object that specifies two things: the embedding model to use (text-embedding-3-small) and the input text that we want to transform into an AI embedding. You can think of this payload as a neatly addressed envelope: it tells OpenAI which “engine” we want to use and provides the “message” that we want processed.
The script then turns that payload into bytes (because HTTP requests ultimately send bytes over the wire), creates a POST request, and sends it to OpenAI using urllib.request.urlopen. If the call succeeds, OpenAI responds with a JSON document. Inside that response is the embedding vector, accessible at data[0].embedding. The program extracts that list of numbers and prints it. That printed list is the embedding, or the “meaning fingerprint” of your text.
Finally, the program includes basic error handling. If OpenAI rejects the request (for example, because the API key is missing, invalid, or the request is malformed), urllib raises an HTTPError. The script catches that error and prints both the HTTP status code and the response body. This is a small but important discipline: when you start building embedding pipelines at scale, clean error reporting is what saves you from debugging in the dark.
In short, this script does one job beautifully: it proves the end-to-end concept. A sentence goes in. A vector comes out.
Running the script
Section titled “Running the script”Just save this as a .py file and run it. Your Python program will call the OpenAI API just like cURL did, but now you’ve got a neat little reusable tool. You can pass in any text, and it’ll happily fetch the embedding for you:
python3 ./my_embedding.pyThis returns the same results as the curl call:
Embedding: [-0.008902248, 0.021756759, 0.01281589, ……, -0.009088919, -0.015487208, -0.0034501844, -0.010414923]And there we go! We’ve taken that first leap from a simple curl command to a humble Python script. It’s like going from a single brushstroke to the start of a beautiful painting.
Now that we have created our Python program to generate an embedding, we will move that code inside the database.
Creating embeddings in PostgreSQL with PL/PythonU
Section titled “Creating embeddings in PostgreSQL with PL/PythonU”Once you’ve seen embeddings created from a simple Python script, the next natural question is: can the database create embeddings directly? Next, we’ll do exactly that, by teaching PostgreSQL how to call the OpenAI embeddings API from inside the database using PL/PythonU.
A quick recap of what we discussed in Chapter 6, Functions and Stored Procedures: The U in PL/PythonU stands for untrusted. It is considered untrusted because it grants full access to the underlying OS, network, and files. That’s why it typically requires elevated privileges and is best used in a controlled demo or a carefully governed capability. For learning and clarity, it’s perfect. For production, you’ll often move this call into a service layer. But for now, we want something simple, direct, and runnable.
The embedding API expects three things:
- A model name (we’ll use
text-embedding-3-small) - The input text
- An API key for authorization
The response comes back as JSON, and inside it is a single field we care about most: data[0].embedding, the AI vector represented as a list of numbers.
That’s the entire story arc: text in, JSON out to the LLM, embedding extracted from JSON, and returned to SQL.
Let’s convert our basic Python script to PL/PythonU. The following is a PL/PythonU function that mirrors our basic Python example but runs inside PostgreSQL. It uses urllib, constructs a POST request to the OpenAI embeddings endpoint, parses the JSON response, and returns the embedding as a float4[] array.
The API key should be stored in a session parameter (use the set_config command) or as a server setting (ALTER SYSTEM).
In option 1, we have a session-level parameter:
SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);In option 2, we have a server-level parameter:
ALTER SYSTEM SET api.openai_api_key = 'your_openai_api_key_here';-- Reload the configuration to apply the changeSELECT pg_reload_conf();ALTER SYSTEM writes the value in plain text to postgresql.auto.conf, so treat this as sensitive and restrict file access (or prefer environment variables/secret managers where possible).
This PL/Python function is intentionally minimal and readable. It does not try to be clever. It tries to be understandable:
CREATE OR REPLACE FUNCTION api.openai_embed(input_text text)RETURNS float4[]LANGUAGE plpython3uAS $$import jsonimport sslimport urllib.requestimport urllib.error
# Read API key from a session-scoped setting (GUC)rv = plpy.execute( "SELECT current_setting('api.openai_api_key', true) AS k")api_key = rv[0]["k"] if rv and rv[0]["k"] is not None else Noneif not api_key: raise Exception("OpenAI API key not set. Use: SELECT set_config('api.openai_api_key','sk-...','f');")
# Input text we want to embedtext = input_text or ""
# OpenAI endpoint for embeddingsurl = "https://api.openai.com/v1/embeddings"
# HTTP headers (auth + JSON)headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
# JSON payload (model + input text)payload = { "model": "text-embedding-3-small", "input": text}
# Create and send POST requestreq = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
ctx = ssl.create_default_context()
try: with urllib.request.urlopen(req, context=ctx, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) emb = data["data"][0]["embedding"] return [float(x) for x in emb]except urllib.error.HTTPError as e: body = e.read().decode("utf-8", errors="ignore") raise Exception(f"OpenAI HTTP {e.code}. Body: {body[:400]} ...")$$;The first version of the Python script was designed to run outside the database, like a courier at the edge of the system. Python made an HTTP request to OpenAI and printed the embedding on the screen. It was perfect for learning the API call, but it was not connected to the database.
The PL/PythonU function differs because it embeds that same capability within PostgreSQL. The database stops being just the storage layer and becomes an active participant in the embedding workflow. Instead of “Python calls OpenAI,” the story becomes “SQL calls a database function, and that function calls OpenAI.” The result can immediately be stored, indexed, joined, filtered, and governed using the same database engine that already manages your products and pricing.
Another key difference is how authentication is handled. In the Python script, the API key is usually hardcoded in the file or read from an environment variable. In the PL/PythonU version, the key is pulled from a database setting (a GUC) using current_setting('api.openai_api_key', true). That’s why your workflow begins with a SQL line such as set_config(...). It’s a clean, demo-friendly way to keep secrets out of tables and the function body, while still allowing the database to authenticate API calls.
The mechanics of the HTTP request are also shaped by the database environment. In a normal Python script, you can use any library you want (requests, httpx, etc.). In PL/PythonU, you typically prefer standard libraries such as urllib.request because they are always available and behave consistently across environments, especially when they are called inside a database server process. The function also explicitly creates an SSL context (ssl.create_default_context()), because database servers often run in locked-down environments where being explicit about SSL and TLS is a best practice.
Error handling changes, too, because errors now occur “inside SQL.” In the Python script, we printed error messages to the console. In PL/PythonU, if something goes wrong, the function raises an exception, and that exception bubbles up as a SQL error, which can be handled at the PostgreSQL level. That’s important as it allows embedding failures to participate in ACID-compliant transactions. If we generate embeddings as part of an insert/update pipeline, PostgreSQL can treat failures as transaction failures—roll them back, log them, and surface them to the calling application in a predictable way.
Finally, the biggest conceptual shift is what happens after we get the embedding vector back from the LLM. In the Python script, the embedding was just output. In PostgreSQL, the embeddings are treated as data and stored in the embeddings.product_embedding table and indexed for pgvector using HNSW or IVFFlat, as described in Chapter 16*,* Vectors and Indexing for AI with pgvector. Once stored and indexed, the embeddings can be queried with < = > (cosine distance) or < - > (Euclidean distance). The embeddings stopped being a printed list and became part of the database’s searchable semantic memory, ready to be joined with price tables, filtered by current=true, constrained by region, and audited like any other business-critical query.
The difference is not the API call itself—the call is essentially the same. The difference is where the call lives and what that enables: one database, one transaction boundary, and one place where “meaning” and “business reality” can meet without friction.
Here’s the simplest way to use api.openai_embed() with plain text—no tables yet, just text in → embedding out.
First, set your OpenAI API key for the current session (this is how your function reads it):
SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);Now, call the function with any text:
-- Tip: If the output is wide, enable expanded display in psql:-- \x-- (or disable the pager: \pset pager off)SELECT api.openai_embed('waterproof trail running shoes');If you see an HTTP 401 error, verify that your API key is valid and has the required permissions/scopes for embedding requests (and that it is associated with the correct OpenAI project/role). If you are using a restricted API key, ensure that it includes the necessary model/request scope.
That will return a float4[] array—the embedding (a long list of numbers).
If you want to immediately work with it as a pgvector type (so you can use pgvector distance operators and indexes), cast it to vector(1536):
SELECT api.openai_embed('waterproof trail running shoes')::vector(1536) AS embedding_vec;And if you want a quick “sanity check” without printing the entire vector, you can just check the dimension by converting to vector and calling the vector_dims() function:
SELECT vector_dims(api.openai_embed('waterproof trail running shoes')::vector(1536)) AS dims;This should return 1536, confirming that the embedding size matches the model output.
In the next step, we will make our OpenAI function more robust by ensuring that it can retry the embedding generation and handle errors that the API might return.
Making api.openai_embed more robust: Adding retries and backoff
Section titled “Making api.openai_embed more robust: Adding retries and backoff”In the earliest examples, our embedding call was intentionally simple: send text to OpenAI, receive a vector, and move on. That’s perfect for learning. But once we start embedding real-size tables (hundreds or thousands of categories, brands, products, and variants), simplicity alone becomes fragile, and we have to anticipate real-life slowdowns and errors.
At that scale, we must handle conditions that are normal in complex and distributed systems:
- Temporary network glitches
- Short-lived service hiccups
- Brief rate limits during request bursts
- Transient
5xxerrors from upstream infrastructure
The goal of the updated design is not to add more complexity; it is to have fewer failed embedding runs, fewer reruns, and fewer half-populated embedding tables. In a database pipeline, robustness isn’t optional; it’s operational hygiene.
The following is the modified, more robust version of the function of api.openai_embed:
CREATE OR REPLACE FUNCTION api.openai_embed(input_text text)RETURNS float4[]LANGUAGE plpython3uAS $$import json, ssl, time, random, urllib.request, urllib.error
def call_openai(payload, api_key, org): req = urllib.request.Request( "https://api.openai.com/v1/embeddings", data=json.dumps(payload).encode("utf-8"), headers={ "Content-Type": "application/json", "Authorization": f"Bearer {api_key}", "User-Agent": "aidb-postgres-plpython/1.0", **({"OpenAI-Organization": org} if org else {}) } ) ctx = ssl.create_default_context() with urllib.request.urlopen(req, context=ctx, timeout=30) as resp: raw = resp.read().decode("utf-8") return json.loads(raw)
rv = plpy.execute(""" SELECT current_setting('api.openai_api_key', true) AS k, current_setting('api.openai_organization', true) AS o""")api_key = rv[0]["k"] if rv and rv[0]["k"] is not None else Noneorg = rv[0]["o"] if rv and rv[0]["o"] is not None else Noneif not api_key: raise Exception("OpenAI API key not set. Use: SELECT set_config('api.openai_api_key','sk-...','f');")
payload = {"model":"text-embedding-3-small","input": input_text or ""}
attempts = 6for i in range(attempts): try: data = call_openai(payload, api_key, org)
# Validate response structure for clearer errors if "data" not in data or not data["data"] or "embedding" not in data["data"][0]: raise Exception(f"Unexpected OpenAI response shape: keys={list(data.keys())}")
emb = data["data"][0]["embedding"] if not isinstance(emb, list): raise Exception("Embedding is not a list in OpenAI response")
return [float(x) for x in emb]
except urllib.error.HTTPError as e: body = e.read().decode("utf-8", errors="ignore") # Retry only on transient HTTP errors if e.code not in (429, 500, 502, 503, 504) or i == attempts - 1: raise Exception(f"OpenAI HTTP {e.code} (attempt {i+1}/{attempts}). Body: {body[:400]} ...")
# If rate-limited, honor Retry-After when present retry_after = None try: retry_after = e.headers.get("Retry-After") except Exception: retry_after = None
if retry_after: try: sleep_s = float(retry_after) except Exception: sleep_s = (2 ** i) * 0.5 + random.uniform(0, 0.3) else: sleep_s = (2 ** i) * 0.5 + random.uniform(0, 0.3)
time.sleep(sleep_s)
except urllib.error.URLError as e: # Common transient network error if i == attempts - 1: raise time.sleep((2 ** i) * 0.5 + random.uniform(0, 0.2))
except Exception as e: # Fail fast on unexpected errors on last attempt; otherwise short backoff if i == attempts - 1: raise time.sleep((2 ** i) * 0.5 + random.uniform(0, 0.2))$$;In the updated design, we add a dedicated call_openai helper function, handle the secret keys within the function, add bounded retries, selective retry conditions, exponential backoff, and clear errors. Let’s review the changes and discuss why they are important.
A dedicated call_openai(…) helper
Section titled “A dedicated call_openai(…) helper”Defining a separate helper function for the HTTP request separates concerns:
def call_openai(payload, api_key, org): ...This makes the code easier to read and maintain, and it provides a clean retry loop: the retry loop doesn’t need to know the details of building requests; it only needs to know whether the call succeeded or failed.
Session-scoped secrets (API key and optional org)
Section titled “Session-scoped secrets (API key and optional org)”Instead of hardcoding credentials, the function reads them from session settings:
current_setting('api.openai_api_key', true)current_setting('api.openai_organization', true)Let’s see why this matters:
- No secrets in tables
- No secrets inside the function body
- Each session can use its own key (useful in demos, labs, or multi-tenant setups)
- You can revoke access simply by not setting the key
If the key isn’t set, the function fails fast with a clear message. That’s intentional: it avoids mysterious failures later.
A bounded retry loop
Section titled “A bounded retry loop”Retrying is at the heart of robustness. Instead of failing when there is an issue anywhere, retry the operation, but don’t retry forever:
attempts = 6for i in range(attempts): ...The key design choice here is bounded retries. We don’t retry forever. We retry a small number of times and then fail loudly. That keeps database sessions from hanging indefinitely and makes failure modes predictable.
Smart retries only for transient errors
Section titled “Smart retries only for transient errors”The HTTP request provides detailed error messages, which we use to determine which failures should be retried. We retry only for the errors that are commonly temporary:
429(rate limited)500,502,503,504(server-side/gateway errors)
Here’s how to do it:
if e.code not in (429, 500, 502, 503, 504) or i == attempts - 1: raise ...This is an important discipline. If the error is permanent (bad key, invalid payload, or permissions), retrying wastes time and increases load.
Exponential backoff with jitter (the polite retry)
Section titled “Exponential backoff with jitter (the polite retry)”If OpenAI (or the network) is under stress, hammering it will only make the problem worse, as more requests pile up. Blind retry is the worst thing you can do under those circumstances.
That’s why the function uses exponential backoff:
time.sleep((2 ** i) * 0.5 + random.uniform(0, 0.3))This means the following:
- First retry waits ~0.5s
- Then ~1.0s
- Then ~2.0s
- Then ~4.0s
- And so on
The random jitter prevents a thundering herd effect where multiple workers retry at the exact same time. This is exactly the kind of behavior we want when embedding in bulk: patient, polite, and resilient.
Better error messages with response body snippet
Section titled “Better error messages with response body snippet”When an HTTP error happens, the function captures part of the body:
body = e.read().decode("utf-8", errors="ignore")raise Exception(f"OpenAI HTTP {e.code}. Body: {body[:400]} ...")This makes debugging significantly easier. Instead of HTTP 401 with no context, we get the explanation (invalid key, model not found, etc.). We truncate the body to avoid flooding logs with huge payloads.
Why robustness matters specifically inside PostgreSQL
Section titled “Why robustness matters specifically inside PostgreSQL”When we run embeddings from the application layer, failures are annoying. When we run embeddings inside the database, failures can be more costly because they can interrupt the following:
- Data loading scripts
- Batch embedding jobs
- Stored procedures that embed missing vectors
- Demo pipelines that must “just work” live
A single transient error shouldn’t trigger the restart of a 10,000-row embedding run. A robust function with built-in smart retries dramatically reduces those interruptions.
That is the difference between “Our pipeline fails randomly sometimes.”
and “Our pipeline finishes reliably, even when the world is noisy.”
This modified api.openai_embed function is built around one philosophy: Treat API calls like the weather, not like math. Sometimes it rains. Your system should bring an umbrella.
With bounded retries, selective retry conditions, exponential backoff, and clear errors, we’ve made embedding generation inside PostgreSQL far more dependable, especially when we move from “one text” to “entire product catalogs.”
Creating embeddings for real tables and storing them in embedding tables
Section titled “Creating embeddings for real tables and storing them in embedding tables”Now that we have a function that runs within the database and can create an embedding from a single piece of text, we can do something far more useful: generate embeddings from actual rows in our product catalog and store them in the embedding tables under the embeddings schema (see Figure 18.1).

Figure 18.1: Product catalog and corresponding embedding tables
The pattern is simple and repeatable:
- Select the row to embed (
category,brand,product, orvariant). - Compose the text that best captures its meaning (usually a combination of
labelanddescription, or JSON attributes). - Call
api.openai_embed(...)to retrieve an embedding. - Cast it to
vector(1536), so pgvector can index and search it efficiently. - Insert it into the matching embedding table, keyed by the same primary key as the original row.
This is how we create a semantic layer for structured data: we keep the relational model intact and add meaning as a parallel representation.
Before running the examples, don’t forget to set the API key for your session:
SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);Or set the key at the server level:
ALTER SYSTEM SET api.openai_api_key = 'your_openai_api_key_here';-- Reload the configuration to apply the changeSELECT pg_reload_conf();Embedding a single row of the category table
Section titled “Embedding a single row of the category table”Categories are small but important: they represent the “aisles” of the product catalog. The schema suggests the category embedding should be generated from the columns called label and description.
The following query selects one category (id = 1), connects to OpenAI, and creates the embedding:
SELECT c.id, c.label, api.openai_embed(coalesce(c.label,'') || ' ' || coalesce(c.description,''))::vector(1536) AS embeddingFROM product.category cWHERE c.id = 1;This is the abbreviated output of the query:
-[ RECORD 1 ]-------------------------------------------------------------------------id | 1label | Pantsembedding | [0.010736421,0.045328368,-0.0058921133,-0.03895541,-0.010234049,-0.021515902,-0.0010217901,0.004686419,-0.0053179734,0.0049124868,-0.034190048,-0.023740696,0.031060982,0.009250834,-0.0042127534,0.039070237,0.03820903,0.026841052,-0.049634416,0.08256136,-0.012143064,0.021472842,0.012552139,-0.020310208,0.003234921,0.03312789,0.028735716,0.028218988,0.041883525,-0.00029222836,0.031060982,-0.02658269,0.0001299665,0.0048335427,0.014841523,0.03014236,0.007148045,0.007363348,0.018946625,-0.01396596,-0.019032747,-0.053021844,-0.015903683,-0.03232409,0.041682575,0.0024024178,0.004313228,0.05382564,0.028218988,0.032065727,0.043634653,-0.026266912,0.0074135847,0.09846504,0.0…]Now, we will insert that embedding into embeddings.product_category_embedding:
INSERT INTO embeddings.product_category_embedding (product_category_id, embedding)SELECT c.id, api.openai_embed(coalesce(c.label,'') || ' ' || coalesce(c.description,''))::vector(1536)FROM product.category cWHERE c.id = 1ON CONFLICT (product_category_id)DO UPDATE SET embedding = EXCLUDED.embedding;The ON CONFLICT clause makes it safe to rerun the process when the category changes. If there is data, and the vector is regenerated, then it’s simply replaced.
Embedding a single row of the brand table
Section titled “Embedding a single row of the brand table”Brands behave the same way as categories—their meaning comes from label and description:
INSERT INTO embeddings.product_brand_embedding (product_brand_id, embedding)SELECT b.id, api.openai_embed(coalesce(b.label,'') || ' ' || coalesce(b.description,''))::vector(1536)FROM product.brand bWHERE b.id = 1ON CONFLICT (product_brand_id)DO UPDATE SET embedding = EXCLUDED.embedding;Embedding a single row of the product table
Section titled “Embedding a single row of the product table”Products carry richer meaning because they have multiple descriptive fields. To calculate the embedding, we combine the label, short description, and long description. In practice, it’s often even better to fold in the brand label and category label (because those influence meaning and search relevance), but we’ll start with the textbook definition first, then show the upgraded version.
Here is the textbook product embedding (label and descriptions only):
INSERT INTO embeddings.product_embedding (product_id, embedding)SELECT p.id, api.openai_embed( coalesce(p.label,'') || ' ' || coalesce(p.shortdescription,'') || ' ' || coalesce(p.longdescription,'') )::vector(1536)FROM product.product pWHERE p.id = 1ON CONFLICT (product_id)DO UPDATE SET embedding = EXCLUDED.embedding;Here is the upgraded product embedding (also includes category and brand labels):
INSERT INTO embeddings.product_embedding (product_id, embedding)SELECT p.id, api.openai_embed( coalesce(p.label,'') || ' ' || coalesce(pb.label,'') || ' ' || coalesce(pc.label,'') || ' ' || coalesce(p.shortdescription,'') || ' ' || coalesce(p.longdescription,'') )::vector(1536)FROM product.product pJOIN product.brand pb ON pb.id = p.brand_idJOIN product.category pc ON pc.id = p.category_idWHERE p.id = 1ON CONFLICT (product_id)DO UPDATE SET embedding = EXCLUDED.embedding;This version tends to produce better retrieval because the embedding sees the “full semantic identity” of the product, not just the raw description.
Embedding a single product variant row
Section titled “Embedding a single product variant row”Product variants are where real-world commerce gets spicy, with sizes, colors, materials, and fits—often stored in JSONB, just like in our data model:
SELECT p.label, pv.attributes FROM product pJOIN product_variant pv ON pv.product_id = p.idWHERE p.id = 1;For example, the dress shirt by The Gap comes in six variants:
label| attributes--------------+-------------------------------------------- -----------Dress shirt ..| {"fit": "slim", "size": "S", "color": "white", "collar": "spread"}Dress shirt ..| {"fit": "slim", "size": "M", "color": "white", "collar": "spread"}Dress shirt ..| {"fit": "slim", "size": "L", "color": "white", "collar": "spread"}Dress shirt...| {"fit": "classic", "size": "S", "color": "blue", "collar": "spread"}Dress shirt...| {"fit": "classic", "size": "M", "color": "blue", "collar": "spread"}Dress shirt ..| {"fit": "classic", "size": "L", "color": "blue", "collar": "spread"}Since the embedding API requires text, we convert the JSON to text. PostgreSQL gives us an easy, stable choice: pv.attributes::text (where :: is PostgreSQL’s explicit type cast operator). The following code inserts a variant embedding:
INSERT INTO embeddings.product_variant_embedding (product_variant_id, embedding)SELECT pv.id, api.openai_embed(pv.attributes::text)::vector(1536)FROM product.product_variant pvWHERE pv.id = 1ON CONFLICT (product_variant_id)DO UPDATE SET embedding = EXCLUDED.embedding;For even higher-quality embedding, one can format JSON into a more human-readable format (e.g., Color: Navy, Size: L, Material: Cotton), but the minimal approach is perfectly valid for our first working system.
Embedding multiple rows: Same pattern, now in bulk
Section titled “Embedding multiple rows: Same pattern, now in bulk”Once single-row inserts work, scaling comes down to repeating the same pattern without the WHERE id = ... filter.
Categories (bulk)
Section titled “Categories (bulk)”INSERT INTO embeddings.product_category_embedding (product_category_id, embedding)SELECT c.id, api.openai_embed(coalesce(c.label,'') || ' ' || coalesce(c.description,''))::vector(1536)FROM product.category cON CONFLICT (product_category_id)DO UPDATE SET embedding = EXCLUDED.embedding;Brands (bulk)
Section titled “Brands (bulk)”INSERT INTO embeddings.product_brand_embedding (product_brand_id, embedding)SELECT b.id, api.openai_embed(coalesce(b.label,'') || ' ' || coalesce(b.description,''))::vector(1536)FROM product.brand bON CONFLICT (product_brand_id)DO UPDATE SET embedding = EXCLUDED.embedding;Products (bulk)
Section titled “Products (bulk)”INSERT INTO embeddings.product_embedding (product_id, embedding)SELECT p.id, api.openai_embed( coalesce(p.label,'') || ' ' || coalesce(pb.label,'') || ' ' || coalesce(pc.label,'') || ' ' || coalesce(p.shortdescription,'') || ' ' || coalesce(p.longdescription,'') )::vector(1536)FROM product.product pJOIN product.brand pb ON pb.id = p.brand_idJOIN product.category pc ON pc.id = p.category_idON CONFLICT (product_id)DO UPDATE SET embedding = EXCLUDED.embedding;Variants (bulk)
Section titled “Variants (bulk)”INSERT INTO embeddings.product_variant_embedding (product_variant_id, embedding)SELECT pv.id, api.openai_embed(pv.attributes::text)::vector(1536)FROM product.product_variant pvON CONFLICT (product_variant_id)DO UPDATE SET embedding = EXCLUDED.embedding;You’ll notice we did not create embeddings for product.product_variant_price, or product.country_of_origin. That’s intentional. These tables are mostly structured, factual metadata. Prices change over time and are best filtered with SQL. The country of origin is a strict attribute, not fuzzy meaning.
In other words, embeddings are best for meaning-rich fields (descriptions, attributes, and names). SQL is best for truth constraints (price, validity, current, region, and compliance).
Single-row embedding shows us the mechanics. Bulk embedding is how we build a system that actually runs. The moment we have hundreds or thousands of rows, we need a robust and repeatable way to do the following:
- Find rows that don’t yet have embeddings
- Generate embeddings for them
- Store them safely
- Do it in small, controlled batches, so you don’t overwhelm the API or your database
To illustrate this, we will wrap api.openai_embed in a function that calculates batch embeddings for products. You can implement similar concepts can be implemented for other tables.
At a high level, this batch embedding function behaves like a production line in a factory:
- Pick the next N products without an embedding.
- For each product, build the “meaning string” (label + brand + category + descriptions).
- Call
api.openai_embed(...)to generate the embedding. - Insert the embedding into
embeddings.product_embedding. - Keep going until the batch is done.
- Return how many products were embedded.
This gives us a very practical tool that we can run repeatedly until the embedding table is fully populated.
Here is the api.embed_product(batch_size) function:
CREATE OR REPLACE FUNCTION api.embed_product(batch_size int DEFAULT 200)RETURNS integerLANGUAGE plpgsqlAS $$DECLARE r RECORD; done_count int := 0;BEGIN FOR r IN SELECT p.id, p.label, p.shortdescription, p.longdescription, pc.label AS category_label, pb.label AS brand_label FROM product.product p JOIN product.category pc ON pc.id = p.category_id JOIN product.brand pb ON pb.id = p.brand_id LEFT JOIN embeddings.product_embedding pe ON pe.product_id = p.id WHERE pe.product_id IS NULL ORDER BY p.id LIMIT batch_size LOOP BEGIN MERGE INTO embeddings.product_embedding AS target USING (SELECT r.id AS product_id) AS source ON (target.product_id = source.product_id) WHEN NOT MATCHED THEN INSERT (product_id, embedding) VALUES (r.id, api.openai_embed( coalesce(r.label, '') || ' ' || coalesce(r.brand_label, '') || ' ' || coalesce(r.category_label, '') || ' ' || coalesce(r.shortdescription, '') || ' ' || coalesce(r.longdescription, ''))::vector(1536)); done_count := done_count + 1; EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Failed to embed product id %: %', r.id, SQLERRM; END; END LOOP;
RETURN done_count;END;$$;Let’s look at how the api.embed_product(batch_size) function works.
It only picks rows that still need embeddings
Section titled “It only picks rows that still need embeddings”This left join is crucial:
LEFT JOIN embeddings.product_embedding pe ON pe.product_id = p.idWHERE pe.product_id IS NULLIt means, “Only bring me products that do not already have a row in the embeddings table.” That makes the function idempotent in practice. You can run it repeatedly, and it will keep picking up only the missing work.
It processes in small batches to stay stable
Section titled “It processes in small batches to stay stable”The batch_size variable provides a safety valve. Instead of embedding everything at once (which could trigger rate limits or long transactions), the code calculates embeddings for a manageable chunk: 200 products at a time by default.
This is how you keep pipelines calm:
- Smaller bursts
- Fewer failures
- Easier recovery
- Predictable load
Because this logic runs inside a function, the work still executes within a single transaction. For long-running or production embedding jobs (where you want partial progress to persist and avoid repaying for embeddings), prefer a procedure or job runner that commits progress per batch.
It embeds a meaning string, not just one column
Section titled “It embeds a meaning string, not just one column”Inside the loop, it builds a single text input by concatenating the following:
- Product label
- Brand label
- Category label
- Short description
- Long description
This is a good practice because the embedding model sees a richer semantic identity. It is harder to misunderstand a product when you provide more context.
It uses the MERGE command to prevent race conditions
Section titled “It uses the MERGE command to prevent race conditions”This is a key design element in the function and deserves special attention:
MERGE INTO embeddings.product_embedding ...WHEN NOT MATCHED THEN INSERT ...This is important when two embedding jobs run at the same time (or you accidentally trigger the function twice). Without MERGE, both sessions might attempt to insert records with the same product_id value, and one would fail due to a unique constraint violation.
Using MERGE makes the operation safe:
- If the row is already there, it does nothing
- If it’s missing, the operation inserts it
This makes the function concurrency-tolerant, which is a key concept in high-volume distributed production applications. For simple insert-if-missing patterns under heavy concurrency, INSERT ... ON CONFLICT DO NOTHING is often an equally valid, and sometimes preferable alternative.
It continues even if one row fails
Section titled “It continues even if one row fails”This is the error handling block:
EXCEPTION WHEN OTHERS THEN RAISE NOTICE ...It means, “If embedding generation fails for one product, log it and move on.”
That is exactly what we want in bulk jobs. One bad record shouldn’t block embedding for thousands of good ones.
It returns a count so you can drive progress
Section titled “It returns a count so you can drive progress”The function returns the count of embeddings that were generated:
RETURN done_count;This makes the function easy to automate. We can run it in a loop until it returns 0.
How to run bulk embedding
Section titled “How to run bulk embedding”Follow these steps:
- Set the API key for the session:
SELECT set_config('api.openai_api_key','sk-...YOUR_KEY...', false);
- Run one batch:
SELECT api.embed_product(200);
- Call the query repeatedly until it returns
0, indicating that no products remain with no associated embedding:SELECT api.embed_product(200);SELECT api.embed_product(200);SELECT api.embed_product(200);
Why this approach is simple and reliable (and why that’s good)
Section titled “Why this approach is simple and reliable (and why that’s good)”You may notice the comment says “batch API” but the code calls api.openai_embed per row. That’s not a mistake; it’s a deliberate trade-off for stability.
Bulk embedding can be done in two ways:
- True API batching (send an array of inputs to OpenAI in one request):
- Fewer HTTP calls 2. More complex error handling (one bad input can poison the batch) 3. More complicated mapping between inputs and rows
- Per-row embedding inside a batch loop (this function):
- Extremely simple 2. Failures are isolated to one row 3. Easy to resume 4. Easiest to explain in a textbook 5. More HTTP calls overall
Extending the same pattern to other tables
Section titled “Extending the same pattern to other tables”Once you understand api.embed_product, it is easy to create similar bulk functions:
api.embed_categories(batch_size)api.embed_brands(batch_size)api.embed_variants(batch_size)
Same recipe, different tables.
And with that, we’ve passed a major milestone: the database is no longer just storing product data, it’s building a semantic layer over it, one careful batch at a time.
Closing the loop: using generated embeddings to drive recommendations
Section titled “Closing the loop: using generated embeddings to drive recommendations”In Chapter 16*,* Vectors and Indexing for AI with pgvector, we introduced a powerful idea: once your data has embeddings, you can stop treating recommendations as a separate “AI system” and start treating them as part of an integrated database solution. pgvector gives PostgreSQL the ability to compare meaning using vector distance operators, and SQL gives you the ability to turn “similarity” into something operational: in-stock, current price, right region, safe, and allowed.
In this chapter, we’ve focused on integrating LLMs (OpenAI) with PostgreSQL and how to create embeddings, from single text blocks to bulk population. Now, we close the loop: once embeddings exist, what do we do with them?
The answer is simple: we query them.
Chapter 16*,* Vectors and Indexing for AI with pgvector already demonstrated the core recommendation patterns, and we’ll reuse those patterns here as the “payoff” for the embedding we just built.
Query-to-product recommendations using api.openai_embed
Section titled “Query-to-product recommendations using api.openai_embed”Instead of starting from product_id (product-to-product), we start from a user request, such as “Show me premium men’s clothes for a formal occasion.”
The first step is to convert that question into an embedding (a meaning vector). We do that once, inside a CTE (see Chapter 13), and reuse it.
Here is the basic version—semantic search over products:
WITH q AS ( SELECT api.openai_embed('Show me premium men''s clothes for a formal occasion')::vector(1536) AS qvec)SELECT p.id, p.label, 1 - (pe.embedding <=> q.qvec) AS similarityFROM qJOIN embeddings.product_embedding pe ON TRUEJOIN product.product p ON p.id = pe.product_idORDER BY pe.embedding <=> q.qvecLIMIT 10;This is the output:
id | label | similarity----+-----------------------------------------+--------------------- 2 | Dress shirt by Boss | 0.5490152672226669 1 | Dress shirt by The Gap | 0.5363510207711434 14 | Suit coat - business perfect, by Brioni | 0.5311552845054526 3 | Dress shirt by Eaton | 0.5152048315046799 13 | Sports coat - business casual, by Boss | 0.4872733071716657 12 | Chinos - casual, by Boss | 0.4739027932940256 18 | Calvin Klein Cotton Shirt | 0.4679474551709031 17 | Polo shirt, Boss | 0.46449703189748415 11 | Chinos - casual, by The Gap | 0.456206622349822 21 | Ralph Lauren Chinos | 0.45597515034971825(10 rows)This does the following:
api.openai_embed(...)converts the user’s sentence into a 1,536-dimensional vector<=>computes cosine distance between the query vector and each product embeddingORDER BY ... LIMITreturns the closest matches
This is the simplest pattern for semantic search in SQL.
Now, let’s look at an advanced version: adding real-world SQL constraints.
In Chapter 16*,* Vectors and Indexing for AI with pgvector, we showed that similarity alone is not enough in real-world applications. In production, we typically also want the following:
- Only items with a current price
- Optionally, only items within a budget
- Optionally, only items that are in stock
- Optionally, filtering by category/brand/region
Here’s a simple example combining semantic matching with hard SQL constraints:
WITH q AS ( SELECT api.openai_embed('Show me premium men''s clothes for a formal occasion')::vector(1536) AS qvec)SELECT DISTINCT p.id, p.label, pvp.price, 1 - (pe.embedding <=> q.qvec) AS similarityFROM qJOIN embeddings.product_embedding pe ON TRUEJOIN product.product p ON p.id = pe.product_idJOIN product.product_variant pv ON pv.product_id = p.idJOIN product.product_variant_price pvp ON pvp.product_variant_id = pv.id AND pvp.current = trueWHERE pvp.price <= 500 -- example hard constraintORDER BY pe.embedding <=> q.qvecLIMIT 10;The output is a list matching the semantics of the request, and constrained by price:
id | label | price | similarity----+--------------------------------------+-------+--------------------- 1 | Dress shirt by The Gap | 31.72 | 0.5363591589713608 2 | Dress shirt by Boss | 31.93 | 0.5489709540894915 3 | Dress shirt by Eaton | 31.86 | 0.5152130280498575 4 | Mens Classic Oxford Shirt by The Gap | 31.79 | 0.409137946639596 5 | Mens Classic Oxford Shirt from Boss | 31.69 | 0.4330028633473605 6 | T-Shirt by The Gap | 31.69 | 0.37526652216911316 7 | T-Shirt by Diesel | 31.74 | 0.3588232398033142 8 | 501 Original Fit Jeans | 98.58 | 0.2530273199081421 9 | Casual Leather Jacket by Boss | 82.16 | 0.45369914174079895 10 | Casual Leather Jacket by Aeropostale | 81.96 | 0.43804830681989826(10 rows)Now we get “things that match the meaning” and “things that are within our budget.” That is the real payoff of processing and managing vectors and SQL together in a multi-modal database.

Figure 18.2: Step-by-step approach for processing a hybrid query
Figure 18.2 shows us a step-by-step analysis of the execution of this hybrid query, including the AI-based vector matching and the SQL-based filtering:
- In step 1, we call
api.embed_productto create the embeddings for the product records. - In steps 2 and 3,
api.embed_productuses thecall_openaihelper function to send the merged label and description information to the LLM and retrieve the embeddings. - In step 4, the
api.embed_productfunction merges the embeddings into theembeddings.product_embeddingtable. - In steps 5 and 6, the first clause of the CTE uses
api.openai_embedto send the query text “Show me premium men’s clothes for a formal occasion” to the LLM and stores the embedding inq.qvec. - In step 7, PostgreSQL creates a query plan that considers the statistics and indexes for the AI cosine distance operator (
<=>) and equality operators on theproduct,product_variant, andproduct_variant_pricetables. - Finally, in step 8, PostgreSQL returns the result of the hybrid query.
A small but important performance habit
Section titled “A small but important performance habit”Notice we always compute the embedding once in a CTE:
WITH q AS (SELECT api.openai_embed(...)::vector(1536) AS qvec)That prevents repeated API calls and ensures the query consistently uses the same vector.
Summary
Section titled “Summary”This chapter showed how to turn embeddings from an abstract AI concept into a working, production-minded capability inside PostgreSQL.
We started by reinforcing a key distinction: embeddings are specialized vectors, purpose-built to capture semantic meaning. Not every vector is an embedding, and not every embedding is useful unless it can be generated reliably and used repeatedly. To make the idea concrete, we began with the simplest possible workflow: creating an embedding with a curl call and then reproducing the same request in a minimal Python script. That early step matters because it demystifies the process: creating an embedding is not magic. It is a standard API call to a web service that returns a structured list of numbers representing meaning.
Next, we moved the embedding workflow into the database itself. By implementing api.openai_embed in PL/PythonU, PostgreSQL stopped being a passive storage engine and became an active participant in the AI lifecycle. This shift is more important than it looks: it brings embedding creation closer to the data, keeps governance and auditability in the same place, and allows embedding creation to be orchestrated alongside SQL operations rather than bolted on as an afterthought.
Production reality then entered the room, loudly: API rate limits, networks wobble, and transient service occurring at the worst possible times. We improved api.openai_embed with a disciplined reliability pattern: bounded retries, exponential backoff, and jitter. This is the difference between a tutorial function and an operational one. It doesn’t just make the function more robust; it makes the overall system calmer under pressure and far more likely to complete large runs successfully.
With a reliable single-embedding primitive in hand, we scaled up to real data. The api.embed_product(batch_size) function introduced a practical pattern for bulk embedding: process work in small, controlled batches, build a richer “meaning string” from multiple attributes (label, brand, category, and descriptions), and safely store embeddings using idempotent logic. The use of MERGE makes the workflow tolerant of concurrency, preventing race conditions when multiple embedding jobs run at the same time. By embedding only rows that are missing vectors, the process becomes repeatable: you can run it again and again until the dataset is complete.
Using the patterns introduced in Chapter 16*,* Vectors and Indexing for AI with pgvector, we demonstrated how generated embeddings immediately unlock real application features: query-to-product semantic search, product-to-product similarity, and Spotify-style taste matching by embedding the user’s question (or preference statement) with api.openai_embed and ranking results with pgvector distance operators. The system now behaves like a semantic engine while still adhering to SQL’s discipline.
In Chapter 19*,* Production-Ready AI Embedding Pipeline Patterns, we will take this foundation and operationalize it fully. We will design embedding pipelines for production (synchronous, asynchronous, and real-time) and show how to keep embeddings fresh when data changes. We will also explore when query embeddings should be generated on demand versus cached, and we will build two practical assistants: a basic SQL chatbot and a more advanced chatbot that can generate dynamic SQL safely and predictably.
You’ve now learned how to create embeddings, store them, and use them inside PostgreSQL. Next, we turn that capability into a system design—one that stays reliable at scale, stays correct as data evolves, and delivers AI features without fragmenting your architecture into multiple databases and custom glue code.