How to build an AI that can answer questions about your website.
This tutorial walks through an example of crawling a website (in this example, the OpenAI website), turning the crawled pages into embeddings using the Embeddings API, 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.
Copy the Python examples into a file or notebook in the order shown.
Download and extract the TypeScript sample archive. From the extracted typescript-examples directory, run pnpm install --ignore-workspace --frozen-lockfile. The lockfile pins OpenAI, Cheerio, CSV, tokenizer, and canvas dependencies. Set OPENAI_API_KEY before the API steps.
Run each complete program separately from the same working directory with node --experimental-strip-types tutorial-crawl-website-embeddings/<filename>.ts. Do not concatenate the excerpts: each file includes its own imports and setup. Run crawl-website, build-scraped-dataframe, tokenize-scraped-text, split-long-text, visualize-chunk-token-counts, create-embeddings, and answer-question in that order. The hyperlink helpers share one program; context retrieval, answering, and test questions share answer-question.ts.
Replace https://example.com with your website’s URL in the crawler, hyperlink, and scraped-data programs. Replace {{MODEL}} in the downloaded answering program with the model shown below. The crawler saves text under text; later stages produce processed/scraped.csv, processed/chunks.json, and processed/embeddings.csv. Run create-embeddings before answering questions; the package’s synthetic CSV fixtures are only for local analysis tests.
The Go examples use github.com/openai/openai-go/v3, github.com/tiktoken-go/tokenizer, and golang.org/x/net/html. Use the complete programs in the Go tutorial sample directory. When running downloaded source files, replace {{MODEL}} with the model shown in the rendered example. Run each workflow step separately from the same working directory; don’t concatenate their main functions. The hyperlink helpers share one program, and context retrieval, answering, and test questions share another.
Replace https://example.com with your website’s URL in the crawler, hyperlink, and scraped-data programs. Set OPENAI_API_KEY before the API steps. The Go crawler follows same-domain redirects and writes files under text; subsequent programs read and write processed/scraped.csv, processed/chunks.json, and processed/embeddings.csv in order. The histogram steps write token-histogram.png locally.
For Ruby, install the openai, nokogiri, tiktoken_ruby, and chunky_png gems. The sample dependencies list tested versions.
Set OPENAI_API_KEY before running examples in your selected language.
For Ruby, append all snippets to one .rb file and run it in a directory where the script can create text and processed. Set CRAWL_URL to the website to crawl; it defaults to https://example.com. Ruby saves the scraped rows in processed/scraped.csv, the chunks in processed/chunks.json, and the completed index in processed/embeddings.csv. Each later step reads the preceding output.
For Java, use these tested Maven dependencies: com.openai:openai-java:4.105.0, org.jsoup:jsoup:1.24.1, org.apache.commons:commons-csv:1.14.1, com.knuddels:jtokkit:1.1.0, and com.fasterxml.jackson.core:jackson-databind:2.18.11. Use one Java class for the four crawler excerpts, one class for the three final question-answering excerpts, and a separate class for each intermediate example. In each Java file, put imports at the top, place executable statements in a main method that declares checked exceptions, and place helper methods, fields, and records at class scope. Set OPENAI_API_KEY and run the classes in order from your IDE or build tool, with the Maven dependencies on the runtime classpath. Use the same working directory so each program can read the preceding program’s text/ and processed/ outputs.
Setting up a web crawler
Choose a website you can crawl. Expand the steps below to collect page text for the embeddings.
Acquiring data in text form is the first step to use embeddings. This
tutorial creates a new set of data by crawling the OpenAI website, a
technique that you can also use for your own company or personal website.
While this crawler is written from scratch, open source packages like Scrapy can also help with these operations.
This 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 and set the starting URL. Python uses an HTMLParser subclass; Java uses jsoup. Combine the four Java excerpts in this section into the same crawler class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30import requestsimport reimport urllib.requestfrom bs4 import BeautifulSoupfrom collections import dequefrom html.parser import HTMLParserfrom urllib.parse import urldefrag, urljoin, urlparseimport os# Regex pattern to match a URLHTTP_URL_PATTERN = r"^http[s]*://.+"domain = "openai.com" # <- put your domain to be crawledfull_url = "https://openai.com/" # <- put your domain to be crawled with https or http# Create a class to parse the HTML and get the hyperlinksclass HyperlinkParser(HTMLParser): def __init__(self): super().__init__() # Create a list to store the hyperlinks self.hyperlinks = [] # Override the HTMLParser's handle_starttag method to get the hyperlinks def handle_starttag(self, tag, attrs): attrs = dict(attrs) # If the tag is an anchor tag and it has an href attribute, add the href attribute to the list of hyperlinks if tag == "a" and "href" in attrs: self.hyperlinks.append(attrs["href"])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# Function to get the hyperlinks from a URLdef get_hyperlinks(url): # Try to open the URL and read the HTML try: with urllib.request.urlopen(url, timeout=30) as response: # If the response is not HTML, return an empty list if not response.info().get("Content-Type", "").startswith("text/html"): return [] # Decode the HTML html = response.read().decode("utf-8") except Exception as error: print(error) return [] # Create the HTML Parser and then Parse the HTML to get hyperlinks parser = HyperlinkParser() parser.feed(html) return parser.hyperlinks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93static async Task<IReadOnlyList<string>> GetHyperlinksAsync( HttpClient client, Uri url, HtmlDocument? fetchedDocument = null){ // Reuse the already fetched HTML when calling this helper from a crawl. if (fetchedDocument is not null) return Hyperlinks(fetchedDocument); HtmlPage? page = await FetchHtmlAsync(client, url, url); return page is null ? [] : Hyperlinks(page.Document);}static string[] Hyperlinks(HtmlDocument document) => document.DocumentNode.Descendants("a") .Where(node => node.Attributes["href"] is not null) .Take(MaxLinksPerPage) .Select(node => HtmlEntity.DeEntitize(node.GetAttributeValue("href", ""))) .ToArray();static async Task<HtmlPage?> FetchHtmlAsync( HttpClient client, Uri initial, Uri origin, HashSet<string>? fetched = null){ Uri current = initial; HashSet<string> redirects = new(StringComparer.Ordinal); using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(10)); for (int hop = 0; hop <= MaxRedirects; hop++) { if (!SameAuthority(origin, current)) { Console.Error.WriteLine($"Skipping redirect outside the same-authority boundary: {current}"); return null; } if (!redirects.Add(current.AbsoluteUri)) { Console.Error.WriteLine($"Skipping redirect loop: {current}"); return null; } // Shared across the traversal, so redirect targets are fetched only once. if (fetched is not null && !fetched.Add(current.AbsoluteUri)) { return null; } using HttpRequestMessage request = new(HttpMethod.Get, current); using HttpResponseMessage response = await client.SendAsync( request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); int status = (int)response.StatusCode; if (status is 301 or 302 or 303 or 307 or 308) { Uri? location = response.Headers.Location; Uri? target = location is null ? null : ResolveLink(current, location.OriginalString); if (hop == MaxRedirects || target is null) { Console.Error.WriteLine($"Skipping invalid redirect or redirect limit: {current}"); return null; } current = target; continue; } if (response.StatusCode != HttpStatusCode.OK) { Console.Error.WriteLine($"Skipping HTTP {status}: {current}"); return null; } if (!string.Equals(response.Content.Headers.ContentType?.MediaType, "text/html", StringComparison.OrdinalIgnoreCase)) { Console.Error.WriteLine($"Skipping non-HTML content: {current}"); return null; } if (response.Content.Headers.ContentLength is > MaxPageBytes) { throw new InvalidDataException($"HTML page exceeds {MaxPageBytes} bytes: {current}"); } await using Stream input = await response.Content.ReadAsStreamAsync(deadline.Token); using MemoryStream body = new(); byte[] buffer = new byte[8192]; int count; while ((count = await input.ReadAsync(buffer.AsMemory(), deadline.Token)) != 0) { if (body.Length + count > MaxPageBytes) { throw new InvalidDataException($"HTML page exceeds {MaxPageBytes} bytes: {current}"); } body.Write(buffer, 0, count); } string? charset = response.Content.Headers.ContentType?.CharSet?.Trim('"'); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding encoding = string.IsNullOrWhiteSpace(charset) ? Encoding.UTF8 : Encoding.GetEncoding(charset); body.Position = 0; using StreamReader reader = new(body, encoding, detectEncodingFromByteOrderMarks: true); HtmlDocument document = new(); document.LoadHtml(await reader.ReadToEndAsync(deadline.Token)); return new HtmlPage(current, document); } throw new InvalidOperationException("Unreachable redirect state.");}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46def fetch_page(url, local_domain = nil) uri = URI.parse(url) raise ArgumentError, "Expected an HTTP or HTTPS URL" unless uri.is_a?(URI::HTTP) local_domain ||= uri.authority 6.times do |redirect_count| unless uri.authority == local_domain raise ArgumentError, "Expected a same-domain HTTP or HTTPS URL" end response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 10, read_timeout: 10) do |http| http.get(uri.request_uri) end return [uri, response] unless response.is_a?(Net::HTTPRedirection) raise ArgumentError, "Too many redirects" if redirect_count == 5 location = response["location"] raise ArgumentError, "Redirect has no location" if location.to_s.empty? target = URI.join(uri.to_s, location) unless target.is_a?(URI::HTTP) && target.authority == local_domain raise ArgumentError, "Expected a same-domain HTTP or HTTPS URL" end uri = target uri.fragment = nil endenddef get_hyperlinks(url) uri, response = fetch_page(url) return [] unless response.is_a?(Net::HTTPSuccess) && response.content_type == "text/html" parser = HyperlinkParser.new parser.feed(response.body) parser.hyperlinks.filter_map do |link| next if link.empty? || link.start_with?("#") begin URI.join(uri.to_s, link).to_s rescue URI::InvalidURIError nil end endend
The 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.
1
2
3
4
5
6
7
8
9
10
11# Function to get the hyperlinks from a URL that are within the same domaindef get_domain_hyperlinks(local_domain, url): links = set() for link in get_hyperlinks(url): if not link or link.startswith("#"): continue candidate, _ = urldefrag(urljoin(url, link)) parsed = urlparse(candidate) if parsed.scheme in {"http", "https"} and parsed.netloc == local_domain: links.add(candidate) return list(links)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23static Set<URI> getDomainHyperlinks(String domain, URI url) throws Exception { return domainHyperlinks(domain, url, getHyperlinks(url));}static Set<URI> domainHyperlinks(String domain, URI url, List<String> hrefs) { var links = new LinkedHashSet<URI>(); for (String href : hrefs) { if (href.isEmpty() || href.startsWith("#")) continue; try { // Query-only references keep the current path, including its final segment. URI link = href.startsWith("?") ? URI.create(url.toString().split("[?#]", 2)[0] + href) : url.resolve(href); link = URI.create(link.toString().split("#", 2)[0]); if (("http".equals(link.getScheme()) || "https".equals(link.getScheme())) && domain.equals(link.getRawAuthority())) links.add(link); } catch (IllegalArgumentException malformed) { /* Ignore malformed links. */ } } return links;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52static async Task<IReadOnlyList<string>> GetDomainHyperlinksAsync( HttpClient client, Uri origin, Uri url, IReadOnlyList<string>? fetchedHyperlinks = null){ if (!SameAuthority(origin, url)) { throw new ArgumentException("The page must have the same authority as the crawl origin.", nameof(url)); } if (fetchedHyperlinks is not null) return DomainHyperlinks(origin, url, fetchedHyperlinks).Select(link => link.AbsoluteUri).ToArray(); HtmlPage? page = await FetchHtmlAsync(client, url, origin); return page is null ? [] : DomainHyperlinks(origin, page.Url, Hyperlinks(page.Document)) .Select(link => link.AbsoluteUri).ToArray();}static List<Uri> DomainHyperlinks(Uri origin, Uri page, IEnumerable<string> hrefs){ HashSet<string> seen = new(StringComparer.Ordinal); List<Uri> links = []; foreach (string href in hrefs) { string reference = href.Trim(); if (reference.Length == 0 || reference.StartsWith('#')) { continue; } Uri? link = ResolveLink(page, reference); if (link is not null && SameAuthority(origin, link) && seen.Add(link.AbsoluteUri)) { links.Add(link); } } return links;}static bool SameAuthority(Uri origin, Uri candidate) => candidate.IsAbsoluteUri && candidate.Scheme is "http" or "https" && candidate.UserInfo.Length == 0 && string.Equals(origin.Authority, candidate.Authority, StringComparison.OrdinalIgnoreCase);static Uri? ResolveLink(Uri page, string reference){ // System.Uri preserves the current path for query-only references. if (!Uri.TryCreate(page, reference, out Uri? resolved) || resolved.Scheme is not ("http" or "https") || resolved.UserInfo.Length != 0) { return null; } // Slice the escaped absolute URI so query escapes keep their identity. string absolute = resolved.AbsoluteUri; int fragment = absolute.IndexOf('#', StringComparison.Ordinal); return fragment < 0 ? resolved : new Uri(absolute[..fragment]);}
1
2
3
4
5
6
7
8
9
10
11
12
13def get_domain_hyperlinks(local_domain, url) get_hyperlinks(url).filter_map do |link| next if link.empty? || link.start_with?("#") begin candidate = URI.join(url, link) candidate.fragment = nil candidate.to_s if candidate.is_a?(URI::HTTP) && candidate.authority == local_domain rescue URI::InvalidURIError nil end end.uniqend
The 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91from hashlib import sha256def crawl(url): # Parse the URL and get the domain parsed = urlparse(url) local_domain = parsed.netloc url = parsed._replace(path=parsed.path or "/").geturl() # Create a queue to store the URLs to crawl queue = deque([url]) # Create a set to store the URLs that have already been seen (no duplicates) seen = set([url]) # Create a directory to store the text files if not os.path.exists("text/"): os.mkdir("text/") if not os.path.exists("text/" + local_domain + "/"): os.mkdir("text/" + local_domain + "/") # Create a directory to store the csv files if not os.path.exists("processed"): os.mkdir("processed") # While the queue is not empty, continue crawling while queue: # Get the next URL from the queue url = queue.pop() requested = url for redirects in range(6): response = requests.get(url, timeout=10, allow_redirects=False) if response.status_code not in {301, 302, 303, 307, 308}: break location = response.headers.get("Location", "") target, _ = urldefrag(urljoin(url, location)) parsed_target = urlparse(target) if ( not location or parsed_target.scheme not in {"http", "https"} or parsed_target.netloc != local_domain ): break if redirects == 5: raise ValueError("Too many redirects") url = target if url != requested and url in seen: continue seen.add(url) if response.status_code != 200 or not response.headers.get( "Content-Type", "" ).startswith("text/html"): continue url = response.url print(url) soup = BeautifulSoup(response.text, "html.parser") for element in soup(["script", "style"]): element.decompose() text = soup.get_text() # Include the full URL digest so nested paths and query variants cannot collide. parsed_page = urlparse(url) prefix = (local_domain + parsed_page.path).replace("/", "_") suffix = "#" + sha256(url.encode("utf-8")).hexdigest() prefix = prefix.encode("utf-8")[: 255 - len(suffix) - len(".txt")].decode( "utf-8", errors="ignore" ) with open( "text/" + local_domain + "/" + prefix + suffix + ".txt", "w", encoding="UTF-8", ) as f: f.write(text) for anchor in soup.find_all("a", href=True): link = anchor["href"] if not link or link.startswith("#"): continue candidate, _ = urldefrag(urljoin(url, link)) parsed_link = urlparse(candidate) if ( parsed_link.scheme in {"http", "https"} and parsed_link.netloc == local_domain and candidate not in seen ): queue.append(candidate) seen.add(candidate)crawl(full_url)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67import java.net.URI;import java.net.http.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.time.Duration;import java.util.*;import org.jsoup.Jsoup;crawl(URI.create("https://example.com/"));static void crawl(URI initial) throws Exception { URI start = initial.getRawPath().isEmpty() ? URI.create(initial + "/") : initial; String domain = start.getRawAuthority(); Path directory = Path.of("text", domain); Files.createDirectories(directory); Files.createDirectories(Path.of("processed")); var queue = new ArrayDeque<URI>(); queue.add(start); var seen = new HashSet<URI>(); seen.add(start); while (!queue.isEmpty()) { URI url = queue.removeLast(); URI requested = url; HttpResponse<String> response; for (int redirects = 0; ; redirects++) { response = HTTP.send( HttpRequest.newBuilder(url).timeout(Duration.ofSeconds(10)).GET().build(), HttpResponse.BodyHandlers.ofString()); if (!Set.of(301, 302, 303, 307, 308).contains(response.statusCode())) break; String location = response.headers().firstValue("location").orElse(""); if (location.isEmpty()) break; URI next = location.startsWith("?") ? URI.create(url.toString().split("[?#]", 2)[0] + location) : url.resolve(location); next = URI.create(next.toString().split("#", 2)[0]); // Follow redirects only within the original HTTP(S) authority. if (!("http".equals(next.getScheme()) || "https".equals(next.getScheme())) || !domain.equals(next.getRawAuthority())) break; if (redirects == 5) throw new java.io.IOException("Too many redirects"); url = next; } if (!url.equals(requested) && !seen.add(url)) continue; if (response.statusCode() != 200 || !response .headers() .firstValue("content-type") .orElse("") .toLowerCase(Locale.ROOT) .startsWith("text/html")) continue; System.out.println(url); String filename = (domain + url.getRawPath()).replace("/", "_"); String suffix = "#" + HexFormat.of() .formatHex( java.security.MessageDigest.getInstance("SHA-256") .digest(url.toString().getBytes(StandardCharsets.UTF_8))); while (filename.getBytes(StandardCharsets.UTF_8).length > 255 - suffix.length() - 4) filename = filename.substring(0, filename.offsetByCodePoints(filename.length(), -1)); filename += suffix; Files.writeString(directory.resolve(filename + ".txt"), Jsoup.parse(response.body()).text()); for (URI link : domainHyperlinks(domain, url, hyperlinks(response.body()))) if (seen.add(link)) queue.add(link); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133// Replace this with a website you own or have permission to crawl.Uri start = new("https://example.com/");using HttpClient client = CreateClient();IReadOnlyList<LinkObservation> observations = await CrawlAsync(client, start);static async Task<IReadOnlyList<LinkObservation>> CrawlAsync(HttpClient client, Uri start){ List<LinkObservation> observations = []; if (!SameAuthority(start, start)) { throw new ArgumentException("Use an HTTP or HTTPS URL without embedded credentials.", nameof(start)); } start = new UriBuilder(start) { Fragment = "" }.Uri; string directory = Path.Combine("text", OutputDirectoryName(start)); Directory.CreateDirectory(directory); Directory.CreateDirectory("processed"); Queue<Uri> queue = new(); queue.Enqueue(start); HashSet<string> scheduled = new(StringComparer.Ordinal) { start.AbsoluteUri }; HashSet<string> fetched = new(StringComparer.Ordinal); int saved = 0; while (queue.TryDequeue(out Uri? url)) { HtmlPage? page = await FetchHtmlAsync(client, url, start, fetched); if (page is null) { continue; } // Redirect aliases can share a final page; FetchHtmlAsync deduplicates requests. string path = Path.Combine(directory, PageFilename(page.Url)); await File.WriteAllTextAsync(path, VisibleText(page.Document.DocumentNode), new UTF8Encoding(false)); Console.WriteLine(page.Url.AbsoluteUri); saved++; IReadOnlyList<string> hyperlinks = await GetHyperlinksAsync(client, page.Url, page.Document); IReadOnlyList<string> domainHyperlinks = await GetDomainHyperlinksAsync(client, start, page.Url, hyperlinks); observations.Add(new(page.Url, hyperlinks, domainHyperlinks)); foreach (string address in domainHyperlinks) { Uri link = new(address); if (scheduled.Contains(link.AbsoluteUri)) { continue; } if (scheduled.Count == MaxPages) { Console.Error.WriteLine($"Crawl limited to {MaxPages} scheduled pages."); break; } scheduled.Add(link.AbsoluteUri); queue.Enqueue(link); } } Console.Error.WriteLine($"Saved {saved} HTML pages."); return observations;}static string OutputDirectoryName(Uri origin){ string host = origin.IdnHost; bool ordinaryHost = origin.IsDefaultPort && host.Length <= 200 && host.All(character => char.IsAsciiLetterOrDigit(character) || character is '.' or '-') && !host.EndsWith('.') && !Regex.IsMatch(host, @"^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); // Keep the guide's text/example.com layout; ports, IPv6 and device names use ASCII. return ordinaryHost ? host : "site-" + Convert.ToHexString( SHA256.HashData(Encoding.UTF8.GetBytes(origin.Authority))).ToLowerInvariant();}static string PageFilename(Uri url){ string digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url.AbsoluteUri))) .ToLowerInvariant(); string suffix = "#" + digest + ".txt"; string readable = Uri.UnescapeDataString(url.Authority + url.AbsolutePath); StringBuilder prefix = new(); int bytes = 0; // Windows reserves device basenames even before an extension, such as con.example. if (Regex.IsMatch(readable, @"^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { prefix.Append('_'); bytes++; } foreach (Rune rune in readable.EnumerateRunes()) { bool invalid = rune.Value < 32 || rune.Value is '/' or '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|'; string part = invalid ? "_" : rune.ToString(); int length = Encoding.UTF8.GetByteCount(part); if (bytes + length > 255 - suffix.Length) { break; } prefix.Append(part); bytes += length; } return prefix.ToString() + suffix;}static string VisibleText(HtmlNode root){ StringBuilder text = new(); AppendText(root, text); return Regex.Replace(HtmlEntity.DeEntitize(text.ToString()), @"\s+", " ").Trim();}static void AppendText(HtmlNode node, StringBuilder text){ if (node.Name is "script" or "style" || node.NodeType == HtmlNodeType.Comment) { return; } if (node.NodeType == HtmlNodeType.Text) { text.Append(node.InnerText); return; } bool block = node.Name is "address" or "article" or "aside" or "blockquote" or "br" or "dd" or "div" or "dl" or "dt" or "fieldset" or "figcaption" or "figure" or "footer" or "form" or "h1" or "h2" or "h3" or "h4" or "h5" or "h6" or "header" or "hr" or "li" or "main" or "nav" or "ol" or "p" or "pre" or "section" or "table" or "td" or "th" or "tr" or "ul"; if (block) text.Append(' '); foreach (HtmlNode child in node.ChildNodes) { AppendText(child, text); } if (block) text.Append(' ');}internal sealed record LinkObservation( Uri Url, IReadOnlyList<string> Hyperlinks, IReadOnlyList<string> DomainHyperlinks);sealed record HtmlPage(Uri Url, HtmlDocument Document);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46def crawl(full_url) initial = URI.parse(full_url) raise ArgumentError, "Expected an HTTP or HTTPS URL" unless initial.is_a?(URI::HTTP) local_domain = initial.authority or raise ArgumentError, "URL has no host" initial.path = "/" if initial.path.to_s.empty? queue = [initial.to_s] seen = Set.new(queue) directory = File.join("text", local_domain) FileUtils.mkdir_p([directory, "processed"]) until queue.empty? url = queue.pop uri, response = fetch_page(url, local_domain) next if uri.to_s != url && !seen.add?(uri.to_s) url = uri.to_s next unless response.is_a?(Net::HTTPSuccess) && response.content_type == "text/html" puts url page_name = (local_domain + uri.path).tr("/", "_") suffix = "##{Digest::SHA256.hexdigest(url)}" prefix = page_name.byteslice(0, 255 - suffix.bytesize - ".txt".bytesize).to_s.scrub("") page_name = prefix + suffix document = Nokogiri::HTML.parse(response.body) document.css("script, style").remove text = document.text File.write(File.join(directory, "#{page_name}.txt"), text) document.css("a[href]").each do |anchor| link = anchor["href"].to_s next if link.empty? || link.start_with?("#") begin candidate = URI.join(url, link) candidate.fragment = nil if candidate.is_a?(URI::HTTP) && candidate.authority == local_domain queue << candidate.to_s if seen.add?(candidate.to_s) end rescue URI::InvalidURIError next end end endendcrawl(ENV.fetch("CRAWL_URL", "https://example.com"))
The 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.
Building an embeddings index
CSV is a common format for storing embeddings. You can use this format
with Python by converting the raw text files (which are in the text
directory) into Pandas data frames. Pandas is a popular open source
library that helps you work with tabular data (data stored in rows and
columns).
Blank empty lines can clutter the text files and make them harder to
process. A function can remove those lines and tidy up the files.
Converting 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.
Extra spacing and new lines can clutter the text and complicate the embeddings
process. The code used here helps to remove some of them but you may find 3rd
party libraries or other methods useful to get rid of more unnecessary
characters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36from pathlib import Pathimport pandas as pdimport re# Create a list to store the text filestexts = []# Get all the text files in the text directoryfor file in sorted(os.listdir("text/" + domain + "/")): # Open the file and read the text with open("text/" + domain + "/" + file, "r", encoding="UTF-8") as f: text = f.read() page_name = re.sub(r"#[a-f0-9]{64}$", "", Path(file).stem) domain_prefix = f"{domain}_" if page_name in {domain, domain_prefix}: page_name = "index" elif page_name.startswith(domain_prefix): page_name = page_name[len(domain_prefix) :] # Replace -, _, and #update with spaces. texts.append( ( page_name.replace("-", " ").replace("_", " ").replace("#update", ""), text, ) )# Create a dataframe from the list of textsdf = pd.DataFrame(texts, columns=["fname", "text"])# Set the text column to be the raw text with the newlines removeddf["text"] = df.fname + ". " + remove_newlines(df.text)df.to_csv("processed/scraped.csv")df.head()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86package mainimport ( "encoding/csv" "encoding/hex" "encoding/json" "fmt" "log" "net/url" "os" "path/filepath" "strings")func removeNewlines(texts []string) []string { result := make([]string, len(texts)) for i, text := range texts { text = strings.ReplaceAll(text, "\n", " ") text = strings.ReplaceAll(text, `\n`, " ") text = strings.ReplaceAll(text, " ", " ") result[i] = strings.ReplaceAll(text, " ", " ") } return result}func main() { address := "https://example.com" initial, err := url.Parse(address) if err != nil { log.Fatal(err) } if (initial.Scheme != "http" && initial.Scheme != "https") || initial.Host == "" || initial.User != nil { log.Fatal("expected an HTTP or HTTPS URL") } directory := filepath.Join("text", initial.Host) entries, err := os.ReadDir(directory) if err != nil { log.Fatal(err) } rows := []map[string]string{} for _, entry := range entries { if !entry.Type().IsRegular() || filepath.Ext(entry.Name()) != ".txt" { continue } title := strings.TrimSuffix(entry.Name(), ".txt") // The crawler's URL digest prevents filename collisions, but isn't a page title. if i := strings.LastIndex(title, "#"); i >= 0 && len(title)-i == 65 { if _, err := hex.DecodeString(title[i+1:]); err == nil { title = title[:i] } } if title == initial.Host || title == initial.Host+"_" { title = "index" } else { title = strings.TrimPrefix(title, initial.Host+"_") } title = strings.NewReplacer("-", " ", "_", " ", "#update", "").Replace(title) data, err := os.ReadFile(filepath.Join(directory, entry.Name())) if err != nil { log.Fatal(err) } text := removeNewlines([]string{string(data)})[0] rows = append(rows, map[string]string{"fname": title, "text": fmt.Sprintf("%s. %s", title, text)}) } if err := os.MkdirAll("processed", 0700); err != nil { log.Fatal(err) } file, err := os.Create("processed/scraped.csv") if err != nil { log.Fatal(err) } records := [][]string{{"fname", "text"}} for _, row := range rows { records = append(records, []string{row["fname"], row["text"]}) } if err := csv.NewWriter(file).WriteAll(records); err != nil { file.Close() log.Fatal(err) } if err := file.Close(); err != nil { log.Fatal(err) } if err := json.NewEncoder(os.Stdout).Encode(rows); err != nil { log.Fatal(err) }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32import com.fasterxml.jackson.databind.ObjectMapper;import java.nio.file.*;import java.util.*;import org.apache.commons.csv.*;String domain = java.net.URI.create("https://example.com/").getRawAuthority();var rows = new ArrayList<Map<String, String>>();try (var files = Files.list(Path.of("text", domain))) { for (var file : files.sorted().toList()) { String title = file.getFileName() .toString() .replaceFirst("\\.txt$", "") .replaceFirst("#[0-9a-f]{64}$", ""); if (title.startsWith(domain + "_")) title = title.substring(domain.length() + 1); else if (title.equals(domain)) title = "index"; if (title.isEmpty()) title = "index"; title = title.replace("-", " ").replace("_", " ").replace("#update", ""); String text = Files.readString(file).replace("\n", " ").replace("\\n", " "); rows.add(Map.of("fname", title, "text", title + ". " + text)); }}Files.createDirectories(Path.of("processed"));try (var writer = CSVFormat.DEFAULT .builder() .setHeader("id", "fname", "text") .get() .print(Files.newBufferedWriter(Path.of("processed/scraped.csv")))) { for (int i = 0; i < rows.size(); i++) writer.printRecord(i, rows.get(i).get("fname"), rows.get(i).get("text"));}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91using System;using System.Collections.Generic;using System.Globalization;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Text.Json;using System.Text.RegularExpressions;using System.Threading.Tasks;// Use the same origin and working directory as the crawler.Uri origin = new("https://example.com/");string workingDirectory = ".";string domain = origin.Authority;List<Dictionary<string, string>> rows = [];string[] files = Directory.GetFiles(Path.Combine(workingDirectory, "text", OutputDirectoryName(origin)), "*.txt");Array.Sort(files, StringComparer.Ordinal);foreach (string file in files){ string title = TitleFromFilename(Path.GetFileName(file), domain); string text = RemoveNewlines(await File.ReadAllTextAsync(file)); rows.Add(new() { ["fname"] = title, ["text"] = title + ". " + text });}Directory.CreateDirectory(Path.Combine(workingDirectory, "processed"));using (StreamWriter output = new(Path.Combine(workingDirectory, "processed", "scraped.csv"), false, new UTF8Encoding(false))){ await output.WriteLineAsync("id,fname,text"); for (int index = 0; index < rows.Count; index++) { await output.WriteLineAsync(string.Join(",", index.ToString(CultureInfo.InvariantCulture), QuoteCsv(rows[index]["fname"]), QuoteCsv(rows[index]["text"]))); }}static string OutputDirectoryName(Uri origin){ string host = origin.IdnHost; bool ordinaryHost = origin.IsDefaultPort && host.Length <= 200 && host.All(character => char.IsAsciiLetterOrDigit(character) || character is '.' or '-') && !host.EndsWith('.') && !Regex.IsMatch(host, @"^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); // Match the crawler's portable folder, preserving text/example.com for ordinary DNS. return ordinaryHost ? host : "site-" + Convert.ToHexString( SHA256.HashData(Encoding.UTF8.GetBytes(origin.Authority))).ToLowerInvariant();}static string TitleFromFilename(string filename, string domain){ // PageFilename replaces these authority characters before writing the file. domain = Regex.Replace(domain, @"[\x00-\x1f/\\:*?""<>|]", "_"); string title = Regex.Replace(Path.GetFileNameWithoutExtension(filename), "#[0-9a-f]{64}$", ""); // Remove only the crawler's Windows-device escape for this authority. if (Regex.IsMatch(domain, @"^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) && title.StartsWith("_" + domain, StringComparison.Ordinal)) { title = title[1..]; } if (title.StartsWith(domain + "_", StringComparison.Ordinal)) { title = title[(domain.Length + 1)..]; } else if (title == domain) { title = "index"; } if (title.Length == 0) { title = "index"; } return title.Replace("-", " ", StringComparison.Ordinal) .Replace("_", " ", StringComparison.Ordinal) .Replace("#update", "", StringComparison.Ordinal);}static string QuoteCsv(string value) => "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"";static string RemoveNewlines(string text){ ArgumentNullException.ThrowIfNull(text); return Regex.Replace( text.Replace("\r\n", " ", StringComparison.Ordinal) .Replace("\r", " ", StringComparison.Ordinal) .Replace("\n", " ", StringComparison.Ordinal) .Replace(@"\n", " ", StringComparison.Ordinal), " {2,}", " ");}
The next step is tokenization 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 in the docs.
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).
The 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.
1
2
3
4
5
6
7
8
9
10
11
12
13import tiktoken# Load the cl100k_base tokenizer which is designed to work with the ada-002 modeltokenizer = tiktoken.get_encoding("cl100k_base")df = pd.read_csv("processed/scraped.csv", index_col=0)df.columns = ["title", "text"]# Tokenize the text and save the number of tokens to a new columndf["n_tokens"] = df.text.apply(lambda x: len(tokenizer.encode(x)))# Visualize the distribution of the number of tokens per row using a histogramdf.n_tokens.hist()
The Java programs pass data between steps through CSV files. The splitting step reads processed/scraped.csv and writes each chunk and its token count to processed/chunks.csv. The following histogram and embedding steps read that file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47max_tokens = 500# Function to split the text into chunks of a maximum number of tokensdef split_into_many(text, max_tokens=max_tokens): if max_tokens < 1: raise ValueError("max_tokens must be positive.") if not text.strip(): return [] sentences = text.split(". ") chunks = [] chunk = "" for index, sentence in enumerate(sentences): if index < len(sentences) - 1: sentence += "." # Do not silently discard a sentence that needs finer-grained splitting. if len(tokenizer.encode(sentence)) > max_tokens: raise ValueError("A sentence exceeds max_tokens; split it before chunking.") candidate = f"{chunk} {sentence}" if chunk else sentence if len(tokenizer.encode(candidate)) > max_tokens: chunks.append(chunk) chunk = sentence else: chunk = candidate if chunk: chunks.append(chunk) return chunksshortened = []# Loop through the dataframefor row in df.iterrows(): # If the text is None, go to the next row if row[1]["text"] is None: continue # If the number of tokens is greater than the max number of tokens, split the text into chunks if row[1]["n_tokens"] > max_tokens: shortened += split_into_many(row[1]["text"]) # Otherwise, add the text to the list of shortened texts else: shortened.append(row[1]["text"])
Create an embedding for each chunk with text-embedding-3-small. Use the same model for query embeddings. If you change embedding models, rebuild the index before searching it.
For the C# example, first export the text column of the chunked df to processed/chunks.json as a JSON array of strings. The example reads those chunks and writes the embeddings used by the question-answering step.
This should take about 3-5 minutes but after you will have your embeddings ready to use!
Building a question answer system with your embeddings
Embed the user’s question and compare it with the indexed chunks to find
the most relevant text. Send that text and the question to the Responses
API to generate an answer.
Load the saved embeddings as numeric vectors: NumPy arrays in Python or lists in Java. The Java embedding step preserves the text and n_tokens columns alongside each vector in processed/embeddings.csv, which the answer program reads.
For Java, combine the next three excerpts—the context builder, answer function, and question calls—into one class. Collect their imports at the top. Place the Page record and helper methods at class scope; put the client setup, CSV loading, and question calls in the same main method.
Embed the question using the same model you used to build the index. Compare the vectors using cosine similarity and retrieve the closest text chunks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42def distances_from_embeddings(query, embeddings, distance_metric="cosine"): if distance_metric != "cosine": raise ValueError("This example supports cosine distance only.") return [ 1 - float(np.dot(query, item) / (np.linalg.norm(query) * np.linalg.norm(item))) for item in embeddings ]def create_context(question, df, max_len=1800): """ Create a context for a question by finding the most similar context from the dataframe """ # Get the embeddings for the question q_embeddings = ( client.embeddings.create(input=question, model="text-embedding-3-small") .data[0] .embedding ) # Get the distances from the embeddings df["distances"] = distances_from_embeddings( q_embeddings, df["embeddings"].values, distance_metric="cosine" ) returns = [] cur_len = 0 # Sort by distance and add the text to the context until the context is too long for _, row in df.sort_values("distances", ascending=True).iterrows(): # Add the length of the text to the current length cur_len += row["n_tokens"] + 4 # If the context is too long, break if cur_len > max_len: break # Else add it to the text that is being returned returns.append(row["text"]) # Return the context return "\n\n###\n\n".join(returns)
The max_len argument in Python, or maxTokens in Java, limits how many tokens of retrieved text to include. Pass that text and the question to the Responses API using gpt-6-luna. The example extracts the response’s output text.
Answer a question from the website
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16asyncfunctionanswerQuestion(client:OpenAI,rows:EmbeddedRow[],question:string):Promise<string> {constcontext=awaitcreateContext(client, question, rows);constresponse=await client.responses.create({ model: "gpt-6-luna", instructions:'Answer the question using only the supplied context. If the context does not answer the question, say "I don\'t know."', input: `Context: ${context}\n\nQuestion: ${question}`, });if (response.status !=="completed")thrownewError(`Response ended with status ${response.status}`);return response.output_text.trim();}
1
2
3
4
5
6
7
8
9
10
11def answer_question(df, question, max_len=1800): context = create_context(question, df, max_len=max_len) response = client.responses.create( model="gpt-6-luna", instructions=( "Answer the question using only the supplied context. " "If the context doesn't answer the question, say \"I don't know.\"" ), input=f"Context: {context}\n\nQuestion: {question}", ) return response.output_text.strip()
1
2
3
4
5
6
7
8
9
10
11
12
13
14func answerQuestion(ctx context.Context, client *openai.Client, rows []embeddedRow, question string, maxLen int) (string, error) { retrieved, err := createContext(ctx, client, question, rows, maxLen) if err != nil { return "", err } response, err := client.Responses.New(ctx, responses.ResponseNewParams{Model: "gpt-6-luna", Instructions: openai.String("Answer the question using only the supplied context. If the context doesn't answer the question, say \"I don't know.\""), Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Context: " + retrieved + "\n\nQuestion: " + question)}}) if err != nil { return "", err } if response.Status != responses.ResponseStatusCompleted { return "", fmt.Errorf("response ended with status %s", response.Status) } return strings.TrimSpace(response.OutputText()), nil}
1
2
3
4
5
6
7
8
9
10private static async Task<string> AnswerQuestionAsync(EmbeddingClient embeddings, ResponsesClient responses, IEnumerable<Page> pages, string question){ string context = await CreateContextAsync(embeddings, question, pages); ResponseResult response = await responses.CreateResponseAsync(new CreateResponseOptions( "gpt-6-luna", [ResponseItem.CreateUserMessageItem($"Context: {context}\n\nQuestion: {question}")]) { Instructions = "Answer the question using only the supplied context. If the context doesn't answer the question, say \"I don't know.\"", }); return response.GetOutputText().Trim();}
1
2
3
4
5
6
7
8
9
10def answer_question(client, rows, question, max_len: 1800) context = create_context(client, question, rows, max_len: max_len) response = client.responses.create( model: "gpt-6-luna", instructions: "Answer the question using only the supplied context. " \ "If the context doesn't answer the question, say \"I don't know.\"", input: "Context: #{context}\n\nQuestion: #{question}" ) response.output_text.stripend
Ask a question the indexed pages can answer, then ask one they cannot. If the index contains a description of ChatGPT, the first call should answer from it. The second should return “I don’t know.”
Try example questions
TypeScript
1
2
3
4
5
6
7
8constclient=newOpenAI();constrows=awaitloadEmbeddings("processed/embeddings.csv");for (constquestionof ["What is ChatGPT?","What did I have for breakfast today?",]) { console.log(awaitanswerQuestion(client, rows, question));}
1
2print(answer_question(df, "What is ChatGPT?"))print(answer_question(df, "What did I have for breakfast today?"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16func main() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() client := openai.NewClient() rows, err := loadEmbeddings("processed/embeddings.csv") if err != nil { log.Fatal(err) } for _, question := range []string{"What is ChatGPT?", "What did I have for breakfast today?"} { answer, err := answerQuestion(ctx, &client, rows, question, 1800) if err != nil { log.Fatal(err) } fmt.Println(answer) }}
1
2System.out.println(answerQuestion(client, pages, "What is ChatGPT?", 1800));System.out.println(answerQuestion(client, pages, "What did I have for breakfast today?", 1800));
1
2
3
4
5
6client = OpenAI::Client.newrows = CSV.read("processed/embeddings.csv", headers: true).map do |row| row.to_h.merge("embeddings" => JSON.parse(row.fetch("embeddings")))endputs answer_question(client, rows, "What is ChatGPT?")puts answer_question(client, rows, "What did I have for breakfast today?")
If 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.
Currently, the data frame is being passed in each time to answer a question. For more production workflows, a vector database solution should be used instead of storing the embeddings in a CSV file, but the current approach is a great option for prototyping.