Repository Public
1# Web QA with embeddings23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45This tutorial walks through a simple example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the [Embeddings API](https://developers.openai.com/api/docs/guides/embeddings), and then creating a basic search functionality that allows a user to ask questions about the embedded information. This is intended to be a starting point for more sophisticated applications that make use of custom knowledge bases.67# Getting started89Some basic knowledge of Python and GitHub is helpful for this tutorial. Before diving in, make sure to [set up an OpenAI API key](https://developers.openai.com/api/reference/overview) and walk through the [quickstart tutorial](https://developers.openai.com/api/docs/quickstart). This will give a good intuition on how to use the API to its full potential.1011Python is used as the main programming language along with the OpenAI, Pandas, transformers, NumPy, and other popular packages. If you run into any issues working through this tutorial, please ask a question on the [OpenAI Community Forum](https://community.openai.com).1213To start with the code, clone the [full code for this tutorial on GitHub](https://github.com/openai/web-crawl-q-and-a-example). Alternatively, follow along and copy each section into a Jupyter notebook and run the code step by step, or just read along. A good way to avoid any issues is to set up a new virtual environment and install the required packages by running the following commands:1415```bash16python -m venv env1718source env/bin/activate1920pip install -r requirements.txt21```2223## Setting up a web crawler2425The primary focus of this tutorial is the OpenAI API so if you prefer, you can skip the context on how to create a web crawler and just [download the source code](https://github.com/openai/web-crawl-q-and-a-example). Otherwise, expand the section below to work through the scraping mechanism implementation.26272829### Learn how to build a web crawler303132333435 3637 Acquiring data in text form is the first step to use embeddings. This38 tutorial creates a new set of data by crawling the OpenAI website, a39 technique that you can also use for your own company or personal website.40 4142 4344 4546View source code474849 5051 5253545556While this crawler is written from scratch, open source packages like [Scrapy](https://github.com/scrapy/scrapy) can also help with these operations.5758This crawler will start from the root URL passed in at the bottom of the code below, visit each page, find additional links, and visit those pages as well (as long as they have the same root domain). To begin, import the required packages, set up the basic URL, and define a HTMLParser class.5960```python61import requests62import re63import urllib.request64from bs4 import BeautifulSoup65from collections import deque66from html.parser import HTMLParser67from urllib.parse import urlparse68import os6970# Regex pattern to match a URL71HTTP_URL_PATTERN = r"^http[s]*://.+"7273domain = "openai.com" # <- put your domain to be crawled74full_url = "https://openai.com/" # <- put your domain to be crawled with https or http757677# Create a class to parse the HTML and get the hyperlinks78class HyperlinkParser(HTMLParser):79 def __init__(self):80 super().__init__()81 # Create a list to store the hyperlinks82 self.hyperlinks = []8384 # Override the HTMLParser's handle_starttag method to get the hyperlinks85 def handle_starttag(self, tag, attrs):86 attrs = dict(attrs)8788 # If the tag is an anchor tag and it has an href attribute, add the href attribute to the list of hyperlinks89 if tag == "a" and "href" in attrs:90 self.hyperlinks.append(attrs["href"])91```929394The next function takes a URL as an argument, opens the URL, and reads the HTML content. Then, it returns all the hyperlinks found on that page.9596```python97# Function to get the hyperlinks from a URL98def get_hyperlinks(url):99 # Try to open the URL and read the HTML100 try:101 with urllib.request.urlopen(url, timeout=30) as response:102 # If the response is not HTML, return an empty list103 if not response.info().get("Content-Type", "").startswith("text/html"):104 return []105106 # Decode the HTML107 html = response.read().decode("utf-8")108 except Exception as error:109 print(error)110 return []111112 # Create the HTML Parser and then Parse the HTML to get hyperlinks113 parser = HyperlinkParser()114 parser.feed(html)115116 return parser.hyperlinks117```118119120The goal is to crawl through and index only the content that lives under the OpenAI domain. For this purpose, a function that calls the `get_hyperlinks` function but filters out any URLs that are not part of the specified domain is needed.121122```python123# Function to get the hyperlinks from a URL that are within the same domain124def get_domain_hyperlinks(local_domain, url):125 clean_links = []126 for link in set(get_hyperlinks(url)):127 clean_link = None128129 # If the link is a URL, check if it is within the same domain130 if re.search(HTTP_URL_PATTERN, link):131 # Parse the URL and check if the domain is the same132 url_obj = urlparse(link)133 if url_obj.netloc == local_domain:134 clean_link = link135136 # If the link is not a URL, check if it is a relative link137 else:138 if link.startswith("/"):139 link = link[1:]140 elif link.startswith("#") or link.startswith("mailto:"):141 continue142 clean_link = "https://" + local_domain + "/" + link143144 if clean_link is not None:145 if clean_link.endswith("/"):146 clean_link = clean_link[:-1]147 clean_links.append(clean_link)148149 # Return the list of hyperlinks that are within the same domain150 return list(set(clean_links))151```152153154The `crawl` function is the final step in the web scraping task setup. It keeps track of the visited URLs to avoid repeating the same page, which might be linked across multiple pages on a site. It also extracts the raw text from a page without the HTML tags, and writes the text content into a local .txt file specific to the page.155156```python157def crawl(url):158 # Parse the URL and get the domain159 local_domain = urlparse(url).netloc160161 # Create a queue to store the URLs to crawl162 queue = deque([url])163164 # Create a set to store the URLs that have already been seen (no duplicates)165 seen = set([url])166167 # Create a directory to store the text files168 if not os.path.exists("text/"):169 os.mkdir("text/")170171 if not os.path.exists("text/" + local_domain + "/"):172 os.mkdir("text/" + local_domain + "/")173174 # Create a directory to store the csv files175 if not os.path.exists("processed"):176 os.mkdir("processed")177178 # While the queue is not empty, continue crawling179 while queue:180 # Get the next URL from the queue181 url = queue.pop()182 print(url) # for debugging and to see the progress183184 # Save text from the url to a <url>.txt file185 page_name = (local_domain + urlparse(url).path).replace("/", "_")186 with open(187 "text/" + local_domain + "/" + page_name + ".txt",188 "w",189 encoding="UTF-8",190 ) as f:191 # Get the text from the URL using BeautifulSoup192 response = requests.get(url, timeout=10)193 response.raise_for_status()194 soup = BeautifulSoup(response.text, "html.parser")195196 # Get the text but remove the tags197 text = soup.get_text()198199 # If the crawler gets to a page that requires JavaScript, it will stop the crawl200 if "You need to enable JavaScript to run this app." in text:201 print(202 "Unable to parse page " + url + " due to JavaScript being required"203 )204205 # Otherwise, write the text to the file in the text directory206 f.write(text)207208 # Get the hyperlinks from the URL and add them to the queue209 for link in get_domain_hyperlinks(local_domain, url):210 if link not in seen:211 queue.append(link)212 seen.add(link)213214215crawl(full_url)216```217218219The last line of the above example runs the crawler which goes through all the accessible links and turns those pages into text files. This will take a few minutes to run depending on the size and complexity of your site.220221222223224225## Building an embeddings index226227228229 230231 CSV is a common format for storing embeddings. You can use this format232 with Python by converting the raw text files (which are in the text233 directory) into Pandas data frames. Pandas is a popular open source234 library that helps you work with tabular data (data stored in rows and235 columns).236 237238 239240 Blank empty lines can clutter the text files and make them harder to241 process. A simple function can remove those lines and tidy up the files.242 243244 245246247248249```python250def remove_newlines(serie):251 serie = serie.str.replace("\n", " ")252 serie = serie.str.replace("\\n", " ")253 serie = serie.str.replace(" ", " ")254 serie = serie.str.replace(" ", " ")255 return serie256```257258259Converting the text to CSV requires looping through the text files in the text directory created earlier. After opening each file, remove the extra spacing and append the modified text to a list. Then, add the text with the new lines removed to an empty Pandas data frame and write the data frame to a CSV file.260261Extra spacing and new lines can clutter the text and complicate the embeddings262 process. The code used here helps to remove some of them but you may find 3rd263 party libraries or other methods useful to get rid of more unnecessary264 characters.265266```python267import pandas as pd268269# Create a list to store the text files270texts = []271272# Get all the text files in the text directory273for file in os.listdir("text/" + domain + "/"):274 # Open the file and read the text275 with open("text/" + domain + "/" + file, "r", encoding="UTF-8") as f:276 text = f.read()277278 page_name = Path(file).stem279 domain_prefix = f"{domain}_"280 if page_name.startswith(domain_prefix):281 page_name = page_name[len(domain_prefix) :]282 elif page_name == domain:283 page_name = "index"284285 # Replace -, _, and #update with spaces.286 texts.append(287 (288 page_name.replace("-", " ").replace("_", " ").replace("#update", ""),289 text,290 )291 )292293# Create a dataframe from the list of texts294df = pd.DataFrame(texts, columns=["fname", "text"])295296# Set the text column to be the raw text with the newlines removed297df["text"] = df.fname + ". " + remove_newlines(df.text)298df.to_csv("processed/scraped.csv")299df.head()300```301302303Tokenization is the next step after saving the raw text into a CSV file. This process splits the input text into tokens by breaking down the sentences and words. A visual demonstration of this can be seen by [checking out our Tokenizer](https://platform.openai.com/tokenizer) in the docs.304305> A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly ¾ of a word (so 100 tokens ~= 75 words).306307The API has a limit on the maximum number of input tokens for embeddings. To stay below the limit, the text in the CSV file needs to be broken down into multiple rows. The existing length of each row will be recorded first to identify which rows need to be split.308309```python310import tiktoken311312# Load the cl100k_base tokenizer which is designed to work with the ada-002 model313tokenizer = tiktoken.get_encoding("cl100k_base")314315df = pd.read_csv("processed/scraped.csv", index_col=0)316df.columns = ["title", "text"]317318# Tokenize the text and save the number of tokens to a new column319df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))320321# Visualize the distribution of the number of tokens per row using a histogram322df.n_tokens.hist()323```324325326327328 329330 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-initial-histrogram.png"331 alt="Embeddings histogram"332 width="553"333 height="413"334 />335 336337338339340The newest embeddings model can handle inputs with up to 8191 input tokens so most of the rows would not need any chunking, but this may not be the case for every subpage scraped so the next code chunk will split the longer lines into smaller chunks.341342```python343max_tokens = 500344345346# Function to split the text into chunks of a maximum number of tokens347def split_into_many(text, max_tokens=max_tokens):348349 # Split the text into sentences350 sentences = text.split(". ")351352 # Get the number of tokens for each sentence353 n_tokens = [len(tokenizer.encode(" " + sentence)) for sentence in sentences]354355 chunks = []356 tokens_so_far = 0357 chunk = []358359 # Loop through the sentences and tokens joined together in a tuple360 for sentence, token in zip(sentences, n_tokens):361 # If the number of tokens so far plus the number of tokens in the current sentence is greater362 # than the max number of tokens, then add the chunk to the list of chunks and reset363 # the chunk and tokens so far364 if tokens_so_far + token > max_tokens:365 chunks.append(". ".join(chunk) + ".")366 chunk = []367 tokens_so_far = 0368369 # If the number of tokens in the current sentence is greater than the max number of370 # tokens, go to the next sentence371 if token > max_tokens:372 continue373374 # Otherwise, add the sentence to the chunk and add the number of tokens to the total375 chunk.append(sentence)376 tokens_so_far += token + 1377378 return chunks379380381shortened = []382383# Loop through the dataframe384for row in df.iterrows():385 # If the text is None, go to the next row386 if row[1]["text"] is None:387 continue388389 # If the number of tokens is greater than the max number of tokens, split the text into chunks390 if row[1]["n_tokens"] > max_tokens:391 shortened += split_into_many(row[1]["text"])392393 # Otherwise, add the text to the list of shortened texts394 else:395 shortened.append(row[1]["text"])396```397398399Visualizing the updated histogram again can help to confirm if the rows were successfully split into shortened sections.400401```python402df = pd.DataFrame(shortened, columns=["text"])403df["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))404df.n_tokens.hist()405```406407408409410 411412 <img src="https://cdn.openai.com/API/docs/images/tutorials/web-qa/embeddings-tokenized-output.png"413 alt="Embeddings tokenized output"414 width="552"415 height="418"416 />417 418419420421422The content is now broken down into smaller chunks and a simple request can be sent to the OpenAI API specifying the use of the new text-embedding-ada-002 model to create the embeddings:423424```python425from openai import OpenAI426427client = OpenAI()428429df["embeddings"] = df.text.apply(430 lambda x: client.embeddings.create(431 input=x, model="text-embedding-3-small"432 ).data[0].embedding433)434435df.to_csv("processed/embeddings.csv")436df.head()437```438439440This should take about 3-5 minutes but after you will have your embeddings ready to use!441442## Building a question answer system with your embeddings443444445446 447448 The embeddings are ready and the final step of this process is to create a449 simple question and answer system. This will take a user's question,450 create an embedding of it, and compare it with the existing embeddings to451 retrieve the most relevant text from the scraped website. The452 gpt-3.5-turbo-instruct model will then generate a natural sounding answer453 based on the retrieved text.454 455456 457458459460461---462463Turning the embeddings into a NumPy array is the first step, which will provide more flexibility in how to use it given the many functions available that operate on NumPy arrays. It will also flatten the dimension to 1-D, which is the required format for many subsequent operations.464465```python466import numpy as np467468df = pd.read_csv("processed/embeddings.csv", index_col=0)469df["embeddings"] = df["embeddings"].apply(eval).apply(np.array)470471df.head()472```473474475The question needs to be converted to an embedding with a simple function, now that the data is ready. This is important because the search with embeddings compares the vector of numbers (which was the conversion of the raw text) using cosine distance. The vectors are likely related and might be the answer to the question if they are close in cosine distance. The OpenAI python package has a built in `distances_from_embeddings` function which is useful here.476477```python478def create_context(question, df, max_len=1800, size="ada"):479 """480 Create a context for a question by finding the most similar context from the dataframe481 """482483 # Get the embeddings for the question484 q_embeddings = (485 client.embeddings.create(input=question, model="text-embedding-3-small")486 .data[0]487 .embedding488 )489490 # Get the distances from the embeddings491 df["distances"] = distances_from_embeddings(492 q_embeddings, df["embeddings"].values, distance_metric="cosine"493 )494495 returns = []496 cur_len = 0497498 # Sort by distance and add the text to the context until the context is too long499 for _, row in df.sort_values("distances", ascending=True).iterrows():500 # Add the length of the text to the current length501 cur_len += row["n_tokens"] + 4502503 # If the context is too long, break504 if cur_len > max_len:505 break506507 # Else add it to the text that is being returned508 returns.append(row["text"])509510 # Return the context511 return "\n\n###\n\n".join(returns)512```513514515The text was broken up into smaller sets of tokens, so looping through in ascending order and continuing to add the text is a critical step to ensure a full answer. The max_len can also be modified to something smaller, if more content than desired is returned.516517The previous step only retrieved chunks of texts that are semantically related to the question, so they might contain the answer, but there's no guarantee of it. The chance of finding an answer can be further increased by returning the top 5 most likely results.518519The answering prompt will then try to extract the relevant facts from the retrieved contexts, in order to formulate a coherent answer. If there is no relevant answer, the prompt will return “I don’t know”.520521A realistic sounding answer to the question can be created with the completion endpoint using `gpt-3.5-turbo-instruct`.522523```python524def answer_question(525 df,526 model="gpt-3.5-turbo-instruct",527 question="Am I allowed to publish model outputs to Twitter, without a human review?",528 max_len=1800,529 size="ada",530 debug=False,531 max_tokens=150,532 stop_sequence=None,533):534 """535 Answer a question based on the most similar context from the dataframe texts536 """537 context = create_context(538 question,539 df,540 max_len=max_len,541 size=size,542 )543 # If debug, print the raw model response544 if debug:545 print("Context:\n" + context)546 print("\n\n")547548 try:549 # Create a completion using the question and context550 response = client.completions.create(551 model=model,552 prompt=(553 "Answer the question based on the context below, and if the "554 "question can't be answered based on the context, say "555 '"I don\'t know"'556 f"\n\nContext: {context}\n\n---\n\nQuestion: {question}\nAnswer:"557 ),558 temperature=0,559 max_tokens=max_tokens,560 top_p=1,561 frequency_penalty=0,562 presence_penalty=0,563 stop=stop_sequence,564 )565 return response.choices[0].text.strip()566 except Exception as error:567 print(error)568 return ""569```570571572It is done! A working Q/A system that has the knowledge embedded from the OpenAI website is now ready. A few quick tests can be done to see the quality of the output:573574```python575answer_question(df, question="What day is it?", debug=False)576577answer_question(df, question="What is our newest embeddings model?")578579answer_question(df, question="What is ChatGPT?")580```581582583The responses will look something like the following:584585```response586"I don't know."587588'The newest embeddings model is text-embedding-ada-002.'589590'ChatGPT is a model trained to interact in a conversational way. It is able to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests.'591```592593If the system is not able to answer a question that is expected, it is worth searching through the raw text files to see if the information that is expected to be known actually ended up being embedded or not. The crawling process that was done initially was setup to skip sites outside the original domain that was provided, so it might not have that knowledge if there was a subdomain setup.594595Currently, the dataframe is being passed in each time to answer a question. For more production workflows, a [vector database solution](https://developers.openai.com/api/docs/guides/embeddings#how-can-i-retrieve-k-nearest-embedding-vectors-quickly) should be used instead of storing the embeddings in a CSV file, but the current approach is a great option for prototyping.