Web Search with Exa and Brave
File: Search.lean
Exa and Brave both offer web search APIs. Their requests and replies differ, but this program returns results from both in one structure.
The Two APIs
| Exa | Brave | |
|---|---|---|
| Method | POST | GET |
| Auth header | x-api-key |
X-Subscription-Token |
| Parameters | JSON body | URL parameters |
| Results path | results |
web.results |
| Snippet field | text |
description |
| Count field | numResults |
count |
Both return a list of objects, but the field names and the wrapper differ. results takes a snippet key so one function reads both replies.
The Code
1 -- lean --run Search.lean (Exa and Brave Search APIs; needs curl,
2 -- EXA_SEARCH_API_KEY and BRAVE_SEARCH_API_KEY)
3 import Lean.Data.Json
4 open Lean (Json)
5
6 structure Hit where
7 title : String
8 url : String
9 text : String
10
11 instance : ToString Hit where
12 toString h := s!"{h.title}\n {h.url}\n {h.text}\n"
13
14 -- --fail-with-body makes curl exit nonzero on an HTTP error
15 -- status but still print the body, which holds the API's message.
16 def curlJson (args : Array String) : IO Json := do
17 let out ← IO.Process.output {
18 cmd := "curl", args := #["-sS", "--fail-with-body"] ++ args }
19 if out.exitCode != 0 then
20 throw (IO.userError
21 s!"curl exited with {out.exitCode}: {out.stderr}{out.stdout}")
22 match Json.parse out.stdout with
23 | .ok json => return json
24 | .error err =>
25 throw (IO.userError s!"{err}\nResponse: {out.stdout}")
26
27 def getEnv (name : String) : IO String := do
28 let some value ← IO.getEnv name
29 | throw (IO.userError s!"{name} is not set")
30 return value
31
32 -- textKey names the field that holds the snippet
33 def results (items : Json) (textKey : String) :
34 Except String (List Hit) := do
35 let str (h : Json) (key : String) : String :=
36 ((h.getObjVal? key).bind (·.getStr?)).toOption.getD ""
37 return (← items.getArr?).toList.map fun h =>
38 { title := str h "title", url := str h "url", text := str h textKey }
39
40 def exaSearch (query : String) (n : Nat := 5) : IO (List Hit) := do
41 let text := Json.mkObj [("maxCharacters", (300 : Nat))]
42 let body := Json.mkObj [
43 ("query", query), ("numResults", n),
44 ("contents", Json.mkObj [("text", text)])]
45 let json ← curlJson #["https://api.exa.ai/search",
46 "-H", s!"x-api-key: {← getEnv "EXA_SEARCH_API_KEY"}",
47 "-H", "Content-Type: application/json",
48 "-d", body.compress]
49 IO.ofExcept do results (← json.getObjVal? "results") "text"
50
51 def braveSearch (query : String) (n : Nat := 5) : IO (List Hit) := do
52 let json ← curlJson #["-G",
53 "https://api.search.brave.com/res/v1/web/search",
54 "-H", s!"X-Subscription-Token: {← getEnv "BRAVE_SEARCH_API_KEY"}",
55 "-H", "Accept: application/json",
56 "--data-urlencode", s!"q={query}",
57 "--data-urlencode", s!"count={n}"]
58 IO.ofExcept do
59 let web ← json.getObjVal? "web"
60 results (← web.getObjVal? "results") "description"
61
62 def main : IO Unit := do
63 for hit in ← exaSearch "Lean 4 theorem prover tutorial" 3 do
64 IO.println hit
65 for hit in ← braveSearch "Sedona Arizona hiking" 3 do
66 IO.println hit
How It Works
Hitis a structure with three string fields. TheToStringinstance prints a hit on three lines.resultsturns a JSON array into a list of hits. Its local functionstrreads a string field and returns""if the field is absent or is not a string..toOptionconverts theExceptto anOption, and.getD ""supplies the default.{ title := ..., url := ..., text := ... }builds aHit. Lean knows the type from the return type ofresults.exaSearchsends a JSON body with POST.nis aNat, and Lean converts it to a JSON number.braveSearchsends its parameters in the URL with GET. Its results are one level deeper, underweb, and the snippet field isdescription.{← getEnv "EXA_SEARCH_API_KEY"}runs anIOaction inside a string interpolation.
maxCharacters cuts each snippet at 300 characters, so the printed text may stop mid-sentence. str returns "" for a missing or non-string field, which hides an API change; print the raw object when a result looks empty.
curlJson passes -sS and --fail-with-body. -s hides the progress meter and -S still prints errors. With --fail-with-body, an HTTP error status such as 401 or 429 makes curl exit with code 22 but still print the body, so the error shows the status and the API’s own message. A bad Brave key gives curl: (22) The requested URL returned error: 422 followed by a JSON object with the code SUBSCRIPTION_TOKEN_INVALID.
exaSearch and braveSearch pass each API key to curl as a command-line argument, so another user on the same machine can read the keys with ps while curl runs. The Gemini chapter explains the risk and how to avoid it. The code here keeps the simple form.
Lean 4 Notes
Structures. structure Hit where defines a type with three named fields. Lean creates a constructor, Hit.mk, and a function for each field, so h.title reads the title of h. Structures are immutable. To change one field, write { h with title := "new" }, which returns a copy.
Three ways to build a structure. You can write { title := a, url := b, text := c }, or ⟨a, b, c⟩, or Hit.mk a b c. The first form names each field and is the clearest for strings that are easy to mix up.
Instances for your own types. instance : ToString Hit has one function, toString, written here with a named parameter h. Once it exists, IO.println hit and s!"{hit}" both work.
Chained calls. In str, read ((h.getObjVal? key).bind (·.getStr?)).toOption.getD "" from left to right. getObjVal? returns an Except. bind applies the next step if the first one worked. toOption drops the error message. getD "" supplies the default. This is a do block written as one expression.
A step in the loop header. for hit in ← exaSearch "..." 3 do runs the search and then loops over its result.
A typed literal. (300 : Nat) gives the literal a type so that Lean can find the coercion from Nat to Json.
Running It
Set both keys:
1 export EXA_SEARCH_API_KEY=your-exa-key
2 export BRAVE_SEARCH_API_KEY=your-brave-key
The program prints three hits from each service. I show the first hit from each and cut the Exa text short.
1 $ lean --run Search.lean
2 Theorem Proving in Lean 4
3 https://leanprover.github.io/theorem_proving_in_lean4/
4 Theorem Proving in Lean 4
5 ...
6
7 Hiking in Sedona, Arizona
8 https://visitsedona.com/things-to-do/hiking/
9 Sedona and the Verde Valley offer some of the most picturesque hikes in the world. ...
Using It
Change the queries and the result counts in main. To use one service, delete the other loop. Pass the text of the hits to one of the LLM chapters to answer a question from current web pages. Try this: merge both result lists, deduplicate by URL, and print a single ranked list.