Question Answering using Embeddings¶
Many use cases require GPT-3 to respond to user questions with insightful answers. For example, a customer support chatbot may need to provide answers to common questions. The GPT models have picked up a lot of general knowledge in training, but we often need to ingest and use a large library of more specific information.
In this notebook we will demonstrate a method for enabling GPT-3 to answer questions using a library of text as a reference, by using document embeddings and retrieval. We'll be using a dataset of Wikipedia articles about the 2020 Summer Olympic Games. Please see this notebook to follow the data gathering process.
import numpy as np
import openai
import pandas as pd
import pickle
import tiktoken
COMPLETIONS_MODEL = "text-davinci-003"
EMBEDDING_MODEL = "text-embedding-ada-002"
By default, GPT-3 isn't an expert on the 2020 Olympics:
prompt = "Who won the 2020 Summer Olympics men's high jump?"
openai.Completion.create(
prompt=prompt,
temperature=0,
max_tokens=300,
model=COMPLETIONS_MODEL
)["choices"][0]["text"].strip(" \n")
"Marcelo Chierighini of Brazil won the gold medal in the men's high jump at the 2020 Summer Olympics."
Marcelo is a gold medalist swimmer, and, we assume, not much of a high jumper! Evidently GPT-3 needs some assistance here.
The first issue to tackle is that the model is hallucinating an answer rather than telling us "I don't know". This is bad because it makes it hard to trust the answer that the model gives us!
0) Preventing hallucination with prompt engineering¶
We can address this hallucination issue by being more explicit with our prompt:
prompt = """Answer the question as truthfully as possible, and if you're unsure of the answer, say "Sorry, I don't know".
Q: Who won the 2020 Summer Olympics men's high jump?
A:"""
openai.Completion.create(
prompt=prompt,
temperature=0,
max_tokens=300,
model=COMPLETIONS_MODEL
)["choices"][0]["text"].strip(" \n")
"Sorry, I don't know."
To help the model answer the question, we provide extra contextual information in the prompt. When the total required context is short, we can include it in the prompt directly. For example we can use this information taken from Wikipedia. We update the initial prompt to tell the model to explicitly make use of the provided text.
prompt = """Answer the question as truthfully as possible using the provided text, and if the answer is not contained within the text below, say "I don't know"
Context:
The men's high jump event at the 2020 Summer Olympics took place between 30 July and 1 August 2021 at the Olympic Stadium.
33 athletes from 24 nations competed; the total possible number depended on how many nations would use universality places
to enter athletes in addition to the 32 qualifying through mark or ranking (no universality places were used in 2021).
Italian athlete Gianmarco Tamberi along with Qatari athlete Mutaz Essa Barshim emerged as joint winners of the event following
a tie between both of them as they cleared 2.37m. Both Tamberi and Barshim agreed to share the gold medal in a rare instance
where the athletes of different nations had agreed to share the same medal in the history of Olympics.
Barshim in particular was heard to ask a competition official "Can we have two golds?" in response to being offered a
'jump off'. Maksim Nedasekau of Belarus took bronze. The medals were the first ever in the men's high jump for Italy and
Belarus, the first gold in the men's high jump for Italy and Qatar, and the third consecutive medal in the men's high jump
for Qatar (all by Barshim). Barshim became only the second man to earn three medals in high jump, joining Patrik Sjöberg
of Sweden (1984 to 1992).
Q: Who won the 2020 Summer Olympics men's high jump?
A:"""
openai.Completion.create(
prompt=prompt,
temperature=0,
max_tokens=300,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
model=COMPLETIONS_MODEL
)["choices"][0]["text"].strip(" \n")
'Gianmarco Tamberi and Mutaz Essa Barshim emerged as joint winners of the event.'
Adding extra information into the prompt only works when the dataset of extra content that the model may need to know is small enough to fit in a single prompt. What do we do when we need the model to choose relevant contextual information from within a large body of information?
In the remainder of this notebook, we will demonstrate a method for augmenting GPT-3 with a large body of additional contextual information by using document embeddings and retrieval. This method answers queries in two steps: first it retrieves the information relevant to the query, then it writes an answer tailored to the question based on the retrieved information. The first step uses the Embeddings API, the second step uses the Completions API.
The steps are:
- Preprocess the contextual information by splitting it into chunks and create an embedding vector for each chunk.
- On receiving a query, embed the query in the same vector space as the context chunks and find the context embeddings which are most similar to the query.
- Prepend the most relevant context embeddings to the query prompt.
- Submit the question along with the most relevant context to GPT, and receive an answer which makes use of the provided contextual information.
1) Preprocess the document library¶
We plan to use document embeddings to fetch the most relevant part of parts of our document library and insert them into the prompt that we provide to GPT-3. We therefore need to break up the document library into "sections" of context, which can be searched and retrieved separately.
Sections should be large enough to contain enough information to answer a question; but small enough to fit one or several into the GPT-3 prompt. We find that approximately a paragraph of text is usually a good length, but you should experiment for your particular use case. In this example, Wikipedia articles are already grouped into semantically related headers, so we will use these to define our sections. This preprocessing has already been done in this notebook, so we will load the results and use them.
# We have hosted the processed dataset, so you can download it directly without having to recreate it.
# This dataset has already been split into sections, one row for each section of the Wikipedia page.
df = pd.read_csv('https://cdn.openai.com/API/examples/data/olympics_sections_text.csv')
df = df.set_index(["title", "heading"])
print(f"{len(df)} rows in the data.")
df.sample(5)
3964 rows in the data.
content | tokens | ||
---|---|---|---|
title | heading | ||
Jamaica at the 2020 Summer Olympics | Swimming | Jamaican swimmers further achieved qualifying ... | 51 |
Archery at the 2020 Summer Olympics – Women's individual | Background | This is the 13th consecutive appearance of the... | 136 |
Germany at the 2020 Summer Olympics | Sport climbing | Germany entered two sport climbers into the Ol... | 98 |
Cycling at the 2020 Summer Olympics – Women's BMX racing | Competition format | The competition was a three-round tournament, ... | 215 |
Volleyball at the 2020 Summer Olympics – Men's tournament | Format | The preliminary round was a competition betwee... | 104 |
We preprocess the document sections by creating an embedding vector for each section. An embedding is a vector of numbers that helps us understand how semantically similar or different the texts are. The closer two embeddings are to each other, the more similar are their contents. See the documentation on OpenAI embeddings for more information.
This indexing stage can be executed offline and only runs once to precompute the indexes for the dataset so that each piece of content can be retrieved later. Since this is a small example, we will store and search the embeddings locally. If you have a larger dataset, consider using a vector search engine like Pinecone, Weaviate or Qdrant to power the search.
def get_embedding(text: str, model: str=EMBEDDING_MODEL) -> list[float]:
result = openai.Embedding.create(
model=model,
input=text
)
return result["data"][0]["embedding"]
def compute_doc_embeddings(df: pd.DataFrame) -> dict[tuple[str, str], list[float]]:
"""
Create an embedding for each row in the dataframe using the OpenAI Embeddings API.
Return a dictionary that maps between each embedding vector and the index of the row that it corresponds to.
"""
return {
idx: get_embedding(r.content) for idx, r in df.iterrows()
}
def load_embeddings(fname: str) -> dict[tuple[str, str], list[float]]:
"""
Read the document embeddings and their keys from a CSV.
fname is the path to a CSV with exactly these named columns:
"title", "heading", "0", "1", ... up to the length of the embedding vectors.
"""
df = pd.read_csv(fname, header=0)
max_dim = max([int(c) for c in df.columns if c != "title" and c != "heading"])
return {
(r.title, r.heading): [r[str(i)] for i in range(max_dim + 1)] for _, r in df.iterrows()
}
Again, we have hosted the embeddings for you so you don't have to re-calculate them from scratch.
document_embeddings = load_embeddings("https://cdn.openai.com/API/examples/data/olympics_sections_document_embeddings.csv")
# ===== OR, uncomment the below line to recaculate the embeddings from scratch. ========
# document_embeddings = compute_doc_embeddings(df)
# An example embedding:
example_entry = list(document_embeddings.items())[0]
print(f"{example_entry[0]} : {example_entry[1][:5]}... ({len(example_entry[1])} entries)")
('2020 Summer Olympics', 'Summary') : [0.0037565305829048, -0.0061981128528714, -0.0087078781798481, -0.0071364338509738, -0.0025227521546185]... (1536 entries)
So we have split our document library into sections, and encoded them by creating embedding vectors that represent each chunk. Next we will use these embeddings to answer our users' questions.
2) Find the most similar document embeddings to the question embedding¶
At the time of question-answering, to answer the user's query we compute the query embedding of the question and use it to find the most similar document sections. Since this is a small example, we store and search the embeddings locally. If you have a larger dataset, consider using a vector search engine like Pinecone, Weaviate or Qdrant to power the search.
def vector_similarity(x: list[float], y: list[float]) -> float:
"""
Returns the similarity between two vectors.
Because OpenAI Embeddings are normalized to length 1, the cosine similarity is the same as the dot product.
"""
return np.dot(np.array(x), np.array(y))
def order_document_sections_by_query_similarity(query: str, contexts: dict[(str, str), np.array]) -> list[(float, (str, str))]:
"""
Find the query embedding for the supplied query, and compare it against all of the pre-calculated document embeddings
to find the most relevant sections.
Return the list of document sections, sorted by relevance in descending order.
"""
query_embedding = get_embedding(query)
document_similarities = sorted([
(vector_similarity(query_embedding, doc_embedding), doc_index) for doc_index, doc_embedding in contexts.items()
], reverse=True)
return document_similarities
order_document_sections_by_query_similarity("Who won the men's high jump?", document_embeddings)[:5]
[(0.884864308450606, ("Athletics at the 2020 Summer Olympics – Men's high jump", 'Summary')), (0.8633938355935518, ("Athletics at the 2020 Summer Olympics – Men's pole vault", 'Summary')), (0.861639730583851, ("Athletics at the 2020 Summer Olympics – Men's long jump", 'Summary')), (0.8560523857031264, ("Athletics at the 2020 Summer Olympics – Men's triple jump", 'Summary')), (0.8469039130441247, ("Athletics at the 2020 Summer Olympics – Men's 110 metres hurdles", 'Summary'))]
order_document_sections_by_query_similarity("Who won the women's high jump?", document_embeddings)[:5]
[(0.8726165220223294, ("Athletics at the 2020 Summer Olympics – Women's long jump", 'Summary')), (0.8682196158313358, ("Athletics at the 2020 Summer Olympics – Women's high jump", 'Summary')), (0.863191526370672, ("Athletics at the 2020 Summer Olympics – Women's pole vault", 'Summary')), (0.8609374262115406, ("Athletics at the 2020 Summer Olympics – Women's triple jump", 'Summary')), (0.8581515607285688, ("Athletics at the 2020 Summer Olympics – Women's 100 metres hurdles", 'Summary'))]
We can see that the most relevant document sections for each question include the summaries for the Men's and Women's high jump competitions - which is exactly what we would expect.
3) Add the most relevant document sections to the query prompt¶
Once we've calculated the most relevant pieces of context, we construct a prompt by simply prepending them to the supplied query. It is helpful to use a query separator to help the model distinguish between separate pieces of text.
MAX_SECTION_LEN = 500
SEPARATOR = "\n* "
ENCODING = "gpt2" # encoding for text-davinci-003
encoding = tiktoken.get_encoding(ENCODING)
separator_len = len(encoding.encode(SEPARATOR))
f"Context separator contains {separator_len} tokens"
'Context separator contains 3 tokens'
def construct_prompt(question: str, context_embeddings: dict, df: pd.DataFrame) -> str:
"""
Fetch relevant
"""
most_relevant_document_sections = order_document_sections_by_query_similarity(question, context_embeddings)
chosen_sections = []
chosen_sections_len = 0
chosen_sections_indexes = []
for _, section_index in most_relevant_document_sections:
# Add contexts until we run out of space.
document_section = df.loc[section_index]
chosen_sections_len += document_section.tokens + separator_len
if chosen_sections_len > MAX_SECTION_LEN:
break
chosen_sections.append(SEPARATOR + document_section.content.replace("\n", " "))
chosen_sections_indexes.append(str(section_index))
# Useful diagnostic information
print(f"Selected {len(chosen_sections)} document sections:")
print("\n".join(chosen_sections_indexes))
header = """Answer the question as truthfully as possible using the provided context, and if the answer is not contained within the text below, say "I don't know."\n\nContext:\n"""
return header + "".join(chosen_sections) + "\n\n Q: " + question + "\n A:"
prompt = construct_prompt(
"Who won the 2020 Summer Olympics men's high jump?",
document_embeddings,
df
)
print("===\n", prompt)
Selected 2 document sections: ("Athletics at the 2020 Summer Olympics – Men's high jump", 'Summary') ("Athletics at the 2020 Summer Olympics – Men's long jump", 'Summary') === Answer the question as truthfully as possible using the provided context, and if the answer is not contained within the text below, say "I don't know." Context: * The men's high jump event at the 2020 Summer Olympics took place between 30 July and 1 August 2021 at the Olympic Stadium. 33 athletes from 24 nations competed; the total possible number depended on how many nations would use universality places to enter athletes in addition to the 32 qualifying through mark or ranking (no universality places were used in 2021). Italian athlete Gianmarco Tamberi along with Qatari athlete Mutaz Essa Barshim emerged as joint winners of the event following a tie between both of them as they cleared 2.37m. Both Tamberi and Barshim agreed to share the gold medal in a rare instance where the athletes of different nations had agreed to share the same medal in the history of Olympics. Barshim in particular was heard to ask a competition official "Can we have two golds?" in response to being offered a 'jump off'. Maksim Nedasekau of Belarus took bronze. The medals were the first ever in the men's high jump for Italy and Belarus, the first gold in the men's high jump for Italy and Qatar, and the third consecutive medal in the men's high jump for Qatar (all by Barshim). Barshim became only the second man to earn three medals in high jump, joining Patrik Sjöberg of Sweden (1984 to 1992). * The men's long jump event at the 2020 Summer Olympics took place between 31 July and 2 August 2021 at the Japan National Stadium. Approximately 35 athletes were expected to compete; the exact number was dependent on how many nations use universality places to enter athletes in addition to the 32 qualifying through time or ranking (1 universality place was used in 2016). 31 athletes from 20 nations competed. Miltiadis Tentoglou won the gold medal, Greece's first medal in the men's long jump. Cuban athletes Juan Miguel Echevarría and Maykel Massó earned silver and bronze, respectively, the nation's first medals in the event since 2008. Q: Who won the 2020 Summer Olympics men's high jump? A:
We have now obtained the document sections that are most relevant to the question. As a final step, let's put it all together to get an answer to the question.
4) Answer the user's question based on the context.¶
Now that we've retrieved the relevant context and constructed our prompt, we can finally use the Completions API to answer the user's query.
COMPLETIONS_API_PARAMS = {
# We use temperature of 0.0 because it gives the most predictable, factual answer.
"temperature": 0.0,
"max_tokens": 300,
"model": COMPLETIONS_MODEL,
}
def answer_query_with_context(
query: str,
df: pd.DataFrame,
document_embeddings: dict[(str, str), np.array],
show_prompt: bool = False
) -> str:
prompt = construct_prompt(
query,
document_embeddings,
df
)
if show_prompt:
print(prompt)
response = openai.Completion.create(
prompt=prompt,
**COMPLETIONS_API_PARAMS
)
return response["choices"][0]["text"].strip(" \n")
answer_query_with_context("Who won the 2020 Summer Olympics men's high jump?", df, document_embeddings)
Selected 2 document sections: ("Athletics at the 2020 Summer Olympics – Men's high jump", 'Summary') ("Athletics at the 2020 Summer Olympics – Men's long jump", 'Summary')
'Gianmarco Tamberi and Mutaz Essa Barshim emerged as joint winners of the event following a tie between both of them as they cleared 2.37m. Both Tamberi and Barshim agreed to share the gold medal.'
By combining the Embeddings and Completions APIs, we have created a question-answering model which can answer questions using a large base of additional knowledge. It also understands when it doesn't know the answer!
For this example we have used a dataset of Wikipedia articles, but that dataset could be replaced with books, articles, documentation, service manuals, or much much more. We can't wait to see what you create with GPT-3!
More Examples¶
Let's have some fun and try some more examples.
query = "Why was the 2020 Summer Olympics originally postponed?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 1 document sections: ('Concerns and controversies at the 2020 Summer Olympics', 'Summary') Q: Why was the 2020 Summer Olympics originally postponed? A: The 2020 Summer Olympics were originally postponed due to the COVID-19 pandemic.
query = "In the 2020 Summer Olympics, how many gold medals did the country which won the most medals win?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 2 document sections: ('2020 Summer Olympics medal table', 'Summary') ('List of 2020 Summer Olympics medal winners', 'Summary') Q: In the 2020 Summer Olympics, how many gold medals did the country which won the most medals win? A: The United States won the most medals overall, with 113, and the most gold medals, with 39.
query = "What was unusual about the men’s shotput competition?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 2 document sections: ("Athletics at the 2020 Summer Olympics – Men's shot put", 'Summary') ("Athletics at the 2020 Summer Olympics – Men's discus throw", 'Summary') Q: What was unusual about the men’s shotput competition? A: The same three competitors received the same medals in back-to-back editions of the same individual event.
query = "In the 2020 Summer Olympics, how many silver medals did Italy win?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 2 document sections: ('Italy at the 2020 Summer Olympics', 'Summary') ('San Marino at the 2020 Summer Olympics', 'Summary') Q: In the 2020 Summer Olympics, how many silver medals did Italy win? A: 10 silver medals.
Our Q&A model is less prone to hallucinating answers, and has a better sense of what it does or doesn't know. This works when the information isn't contained in the context; when the question is nonsensical; or when the question is theoretically answerable but beyond GPT-3's powers!
query = "What is the total number of medals won by France, multiplied by the number of Taekwondo medals given out to all countries?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 4 document sections: ('France at the 2020 Summer Olympics', 'Taekwondo') ('Taekwondo at the 2020 Summer Olympics – Qualification', 'Qualification summary') ('2020 Summer Olympics medal table', 'Medal count') ("Taekwondo at the 2020 Summer Olympics – Men's 80 kg", 'Competition format') Q: What is the total number of medals won by France, multiplied by the number of Taekwondo medals given out to all countries? A: I don't know.
query = "What is the tallest mountain in the world?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 3 document sections: ("Sport climbing at the 2020 Summer Olympics – Men's combined", 'Route-setting') ("Ski mountaineering at the 2020 Winter Youth Olympics – Boys' individual", 'Summary') ("Ski mountaineering at the 2020 Winter Youth Olympics – Girls' individual", 'Summary') Q: What is the tallest mountain in the world? A: I don't know.
query = "Who won the grimblesplatch competition at the 2020 Summer Olympic games?"
answer = answer_query_with_context(query, df, document_embeddings)
print(f"\nQ: {query}\nA: {answer}")
Selected 2 document sections: ("Gymnastics at the 2020 Summer Olympics – Women's trampoline", 'Summary') ('Equestrian at the 2020 Summer Olympics – Team jumping', 'Summary') Q: Who won the grimblesplatch competition at the 2020 Summer Olympic games? A: I don't know.