Notebooks
E
Elastic
Openai KNN RAG

Openai KNN RAG

openai-chatgptlangchain-pythonchatgptgenaielasticsearchelasticopenaiAIintegrationschatlogvectordatabasenotebooksPythonsearchgenaistackvectorelasticsearch-labslangchainapplications

Semantic search and Retrieval augmented generation using Elasticsearch and OpenAI

Open In Colab

This notebook demonstrates how to:

  • Index the OpenAI Wikipedia vector dataset into Elasticsearch
  • Embed a question with the OpenAI embeddings endpoint
  • Perform semantic search on the Elasticsearch index using the encoded question
  • Send the top search results to the OpenAI Chat Completions API endpoint for retrieval augmented generation (RAG)

Install packages and import modules

[ ]

Connect to Elasticsearch

ℹ️ We're using an Elastic Cloud deployment of Elasticsearch for this notebook. If you don't already have an Elastic deployment, you can sign up for a free Elastic Cloud trial.

To connect to Elasticsearch, you need to create a client instance with the Cloud ID and password for your deployment.

Find the Cloud ID for your deployment by going to https://cloud.elastic.co/deployments and selecting your deployment.

[ ]

Download the dataset

In this step we download the OpenAI Wikipedia embeddings dataset, and extract the zip file.

[ ]

Read CSV file into a Pandas DataFrame

Next we use the Pandas library to read the unzipped CSV file into a DataFrame. This step makes it easier to index the data into Elasticsearch in bulk.

[ ]

Create index with mapping

Now we need to create an Elasticsearch index with the necessary mappings. This will enable us to index the data into Elasticsearch.

We use the dense_vector field type for the title_vector and content_vector fields. This is a special field type that allows us to store dense vectors in Elasticsearch.

Later, we'll need to target the dense_vector field for kNN search.

[ ]

Index data into Elasticsearch

The following function generates the required bulk actions that can be passed to Elasticsearch's Bulk API, so we can index multiple documents efficiently in a single request.

For each row in the DataFrame, the function yields a dictionary representing a single document to be indexed.

[ ]

As the dataframe is large, we will index data in batches of 100. We index the data into Elasticsearch using the Python client's helpers for the bulk API.

[ ]

Let's test the index with a simple match query.

[ ]

Encode a question with OpenAI embedding model

To perform semantic search, we need to encode queries with the same embedding model used to encode the documents at index time. In this example, we need to use the text-embedding-ada-002 model.

You'll need your OpenAI API key to generate the embeddings.

[ ]

Run semantic search queries

Now we're ready to run queries against our Elasticsearch index using our encoded question. We'll be doing a k-nearest neighbors search, using the Elasticsearch kNN query option.

First, we define a small function to pretty print the results.

[ ]

Now let's run our kNN query.

[ ]

Success! Now you know how to use Elasticsearch as a vector database to store embeddings, encode queries by calling the OpenAI embeddings endpoint, and run semantic search using kNN search to find the top results.

Play around with different queries, and if you want to try with your own data, you can experiment with different embedding models.

Now we can use the Chat completions API to work some generative AI magic using the top search result as additional context.

Use Chat Completions API for retrieval augmented generation

Now we can send the question and the text to OpenAI's Chat completions API.

Using a LLM model together with a retrieval model is known as retrieval augmented generation (RAG). We're using Elasticsearch to do what it does best, retrieve relevant documents. Then we use the LLM to do what it does best, tasks like generating summaries and answering questions, using the retrieved documents as context.

The model will generate a response to the question, using the top kNN hit as context. Use the messages list to shape your prompt to the model. In this example, we're using the gpt-3.5-turbo model.

[ ]

Code explanation

Here's what that code does:

  • Uses OpenAI's model to generate a response
  • Sends a conversation containing a system message and a user message to the model
  • The system message sets the assistant's role as "helpful assistant"
  • The user message contains a question as specified in the original kNN query and some input text
  • The response from the model is stored in the summary.choices variable

Next steps

Now you know how to use Elasticsearch as a vector database to store embeddings, encode queries by calling the OpenAI embeddings endpoint, and run semantic search using kNN search to find the top results.

That was just one example of how to combine Elasticsearch with the power of OpenAI's models, to store embeddings, run a semantic search and enable retrieval augmented generation. RAG allows you to avoid the costly and complex process of training or fine-tuning models, by leveraging out-of-the-box models, enhanced with additional context.

Use this as a blueprint for your own experiments.

To adapt the conversation for different use cases, customize the system message to define the assistant's behavior or persona. Adjust the user message to specify the task, such as summarization or question answering, along with the desired format of the response.