Web search with Exa and Brave

File: search.lisp

Two search APIs, one calling convention: esearch and bsearch each take a query string and return a list of (title url text) triples.

The code

 1 ;; sbcl --script search.lisp (Exa and Brave Search APIs)
 2 #-quicklisp (load "~/quicklisp/setup.lisp")
 3 (ql:quickload :com.inuoe.jzon :silent t)
 4 
 5 (defun curl-json (&rest args)
 6   (com.inuoe.jzon:parse
 7    (uiop:run-program (list* "curl" "-s" args) :output :string)))
 8 
 9 (defun api-key (name)
10   (or (uiop:getenv name) (error "~a is not set" name)))
11 
12 (defun unescape (s)
13   "Decode the few HTML entities that show up in search snippets."
14   (when s
15     (loop for (from . to) in '(("'" . "'") ("'" . "'")
16                                ("&quot;" . "\"") ("&lt;" . "<")
17                                ("&gt;" . ">") ("&amp;" . "&"))
18           do (loop for i = (search from s)
19                      then (search from s :start2 (+ i (length to)))
20                    while i
21                    do (setf s (concatenate 'string (subseq s 0 i) to
22                                            (subseq s (+ i (length from))))))
23           finally (return s))))
24 
25 (defun results (items text-key)
26   "List of (title url text) for each hit."
27   (map 'list
28        (lambda (h)
29          (list (unescape (gethash "title" h))
30                (gethash "url" h)
31                (unescape (gethash text-key h))))
32        items))
33 
34 (defun esearch (query &optional (n 5))
35   (results
36    (gethash "results"
37             (curl-json
38              "https://api.exa.ai/search"
39              "-H" (format nil "x-api-key: ~a"
40                           (api-key "EXA_SEARCH_API_KEY"))
41              "-H" "Content-Type: application/json"
42              "-d" (format nil
43                    (concatenate
44                     'string
45                     "{\"query\":~a,\"numResults\":~d,"
46                     "\"contents\":{\"text\":{\"maxCharacters\":300}}}")
47                    (com.inuoe.jzon:stringify query) n)))
48    "text"))
49 
50 (defun bsearch (query &optional (n 5))
51   (results
52    (gethash
53     "results"
54     (gethash
55      "web"
56      (curl-json
57       "-G" "https://api.search.brave.com/res/v1/web/search"
58       "-H" (format nil "X-Subscription-Token: ~a"
59                    (api-key "BRAVE_SEARCH_API_KEY"))
60       "-H" "Accept: application/json"
61       "--data-urlencode" (format nil "q=~a" query)
62       "--data-urlencode" (format nil "count=~d" n)
63       "--data-urlencode" "text_decorations=false")))
64    "description"))
65 
66 (print (esearch "Common Lisp SPARQL client" 3))
67 (print (bsearch "Sedona Arizona hiking" 3))

How it works

  • curl-json is a small, reusable helper: run curl -s with any arguments and parse the reply as JSON. list* puts "curl" "-s" in front of the caller’s arguments.
  • api-key reads an environment variable and signals an error if it is unset, so a missing key fails at once instead of going out as the text NIL.
  • results gives both APIs the same output shape. The two engines differ in one detail (Exa returns page content under the key text, Brave returns a snippet under description), so the text key is a parameter.
  • unescape decodes the few HTML entities (&#x27;, &quot;, &amp;, …) that search snippets contain. The inner loop restarts each search just past the text it inserted, so it never decodes a decoded & a second time.
  • esearch POSTs JSON and asks Exa for up to 300 characters of page text per hit.
  • bsearch uses curl -G with --data-urlencode to build a URL-encoded GET request, the right choice when parameters go in the query string rather than a JSON body. The text_decorations=false parameter tells Brave not to wrap matching words in <strong> tags.

Running it

1 $ export EXA_SEARCH_API_KEY=...
2 $ export BRAVE_SEARCH_API_KEY=...
3 $ sbcl --script search.lisp

The program prints two lists, one per engine; each element is a (title url text) list. Actual output, with long README metadata lines in the Exa snippets cut:

 1 (("mark-watson/sparql" "https://github.com/mark-watson/sparql"
 2   "# Repository: mark-watson/sparql
 3 
 4 Common Lisp SPARQL client code - see book \"Loving Common Lisp,
 5 or the Savvy Programmer's Secret Weapon\"
 6 
 7 - Primary language: Common Lisp ...")
 8  ("madnificent/cl-fuseki" "https://github.com/madnificent/cl-fuseki"
 9   "# madnificent/cl-fuseki
10 
11 Common Lisp library for connecting to SPARQL endpoints.
12 
13 - License: MIT License ...")
14  ("mmontone/cl-sparql" "https://github.com/mmontone/cl-sparql"
15   "# mmontone/cl-sparql
16 
17 SPARQL query builder for Common Lisp
18 
19 - License: MIT License ..."))
20 
21 (("Hiking in Sedona, Arizona" "https://visitsedona.com/things-to-do/hiking/"
22   "Sedona and the Verde Valley offer some of the most picturesque
23 hikes in the world. There are dozens of options to keep the novice
24 and experienced hiker delighted for many days–trails along rivers,
25 trails on mesas and high up in the mountains, ...")
26  ("10 Best trails and hikes in Sedona | AllTrails"
27   "https://www.alltrails.com/us/arizona/sedona"
28   "Apart from the shuttle service, ... The Cathedral Rock hike is a
29 challenging yet beautiful trail in Sedona that offers great views of
30 the unique natural rock... ... An amazing natural wonder, Devil's
31 Bridge, is located near Sedona in Arizona's ...")
32  ("The Best Hikes in Sedona, Arizona | A Hiking Travel Guide"
33   "https://zannavandijk.co.uk/the-best-hikes-in-sedona/"
34   "This is a relatively easy hike with non-stop views of iconic Sedona
35 rock formations. The trail starts as a loop around the butte and then
36 you have the option of adding on the climb up Bell Rock which I highly
37 recommend, the views are incredible!"))

Search results change over time, so your hits will differ. Devil's Bridge prints with a real apostrophe: Brave sent Devil&#x27;s, and unescape decoded it.

Using it

Use these two functions for retrieval-augmented generation: search, then put the (title url text) triples into a prompt for the Gemini or Ollama chapters. Exa is a neural search engine and often finds related pages that share no keywords with the query; Brave is a classic keyword index with its own crawl of the web. Running both and merging the results is a cheap way to improve recall.