Skip to main content
In this guide, we’ll continue from having a text column ready as context. Next, we’ll generate word embeddings for each sentence, compute similarities, and dynamically build context for OpenAI API calls—all using a pandas DataFrame.

1. Generate Embeddings for the text Column

Use your embedding function to vectorize each row in the DataFrame:
Generating embeddings for a large dataset may take some time. For 121 rows, expect multiple API calls.
Inspect the new embedding column:
Example output:
To view a specific example:

2. Define a Similarity Function

We’ll use the dot product to measure vector similarity:
When asking a question (e.g., “Who won the Best Picture award?”), follow these steps:
  1. Embed the query
  2. Compute similarity against each row
  3. Select top candidates

4. Build the Context Block

Concatenate the top candidates into one string:
Now craft the prompt and call the API:
The film “Everything Everywhere All at Once” won the Best Picture award at the 95th Oscar awards.
Expected response:

6. Resources and References


This workflow—building dynamic context from a DataFrame using embeddings, then crafting prompts on the fly—unlocks powerful generative AI applications with OpenAI.

Watch Video

Practice Lab