Calling Google Gemini
File: Gemini.lean
This program calls the Gemini API. The reply is nested JSON, so the program shows how to read a path of several steps and report an error if any step fails.
The Code
1 -- lean --run Gemini.lean (needs curl + GOOGLE_API_KEY)
2 import Lean.Data.Json
3 open Lean (Json)
4
5 def run (cmd : String) (args : Array String) : IO String := do
6 let out ← IO.Process.output { cmd, args }
7 if out.exitCode != 0 then
8 throw (IO.userError s!"{cmd} failed: {out.stderr}")
9 return out.stdout
10
11 def extractText (raw : String) : Except String String := do
12 let json ← Json.parse raw
13 let candidate ← (← json.getObjVal? "candidates").getArrVal? 0
14 let content ← candidate.getObjVal? "content"
15 let part ← (← content.getObjVal? "parts").getArrVal? 0
16 (← part.getObjVal? "text").getStr?
17
18 def gemini (prompt : String)
19 (model : String := "gemini-3.5-flash-lite") : IO String := do
20 let some key ← IO.getEnv "GOOGLE_API_KEY"
21 | throw (IO.userError "GOOGLE_API_KEY is not set")
22 let base := "https://generativelanguage.googleapis.com/v1beta/models/"
23 let url := s!"{base}{model}:generateContent"
24 let parts := Json.arr #[Json.mkObj [("text", prompt)]]
25 let body := Json.mkObj [
26 ("contents", Json.arr #[Json.mkObj [("parts", parts)]])]
27 let raw ← run "curl" #["-sS", url,
28 "-H", "Content-Type: application/json",
29 "-H", s!"x-goog-api-key: {key}",
30 "-d", body.compress]
31 match extractText raw with
32 | .ok text => return text
33 | .error err => throw (IO.userError s!"{err}\nResponse: {raw}")
34
35 def main : IO Unit := do
36 IO.println (← gemini "what is 1 + 10?")
How It Works
extractTextis a pure function inExcept String. Each←reads one level of the reply: the first candidate, its content, the first part, and the text. If a field is absent, the function returns an error that names the field.- In
gemini,let some key ← IO.getEnv "GOOGLE_API_KEY" | throw ...reads the environment variable.IO.getEnvreturns anOption. The patternsome keynames the value, and the code after|runs if the result isnone. - The program passes the key to
curlin a header, not in the URL. The next section explains a risk that remains. - The
matchat the end adds the raw reply to the error message. When the API returns an error object in place of an answer, you see what the API said.
Keeping the Key Private
The program passes the key to curl as a command-line argument. On macOS and Linux, any user on the same machine can list running processes with their arguments, for example with ps aux. Another user can read the key while curl runs. On your own laptop the risk is small. On a shared server, keep the key off the command line. curl -H @file reads headers from a file, so you can write the header to a file that only you can read. curl -H @- reads headers from stdin; in Lean, start curl with IO.Process.spawn and stdin := .piped, then write the header to the child’s stdin. I left the code in its simple form so the JSON handling stays easy to read. The Search chapter has the same risk.
The Response
| Path | Holds |
|---|---|
candidates |
list of replies; empty when a safety filter blocks the prompt |
candidates[0].content |
the reply content object |
content.parts |
list of parts, usually one text part |
parts[0].text |
the answer text |
candidates[0].finishReason |
why generation stopped |
usageMetadata |
token counts for the request |
A blocked prompt returns no candidates, so getArrVal? 0 fails with a missing field. The final match prints the raw reply, which includes the block reason.
Generation Options
Add a generationConfig object next to contents:
1 "generationConfig": {
2 "temperature": 0.2,
3 "maxOutputTokens": 256
4 }
maxOutputTokens limits the reply length and lowers cost; temperature sets how much the output varies. responseMimeType can request JSON, and responseSchema gives the schema that JSON must follow. The API documents the exact field names for the current model.
The API error object has code, message, and status fields. Read error.message and error.status when they exist, so an invalid key and a retired model produce different messages. The raw reply already shows them.
Lean 4 Notes
A let that can fail. A let with a pattern on its left side needs a plan for values that do not match. The form is:
1 let some key ← IO.getEnv "GOOGLE_API_KEY"
2 | throw (IO.userError "GOOGLE_API_KEY is not set")
If the result matches some key, the block goes on with key defined. If not, the code after | runs. That code must leave the block, with throw or return. This keeps the main path of the function at one level of indentation.
Matching on Except. The match at the end of gemini handles both constructors: .ok text and .error err. IO.ofExcept, which the Ollama program uses, does the same thing in one call but cannot add the raw reply to the message.
Pure parsing. extractText takes a string and returns Except String String. It has no IO in its type, so you can test it on a saved reply:
1 #eval extractText "{}"
That call returns an Except.error that says the candidates field is absent.
Arrays in JSON. Json.arr takes an Array Json. The program builds the body from the inside out and names each level, which keeps the lines short. getArrVal? 0 reads the first element of a JSON array.
Long literals. Lean has no line limit, but I keep lines short for print. The URL is two strings joined by interpolation.
Running It
Create an API key in Google AI Studio and export it:
1 export GOOGLE_API_KEY=your-key
1 $ lean --run Gemini.lean
2 1 + 10 = 11
Using It
Pass a model name as the second argument to gemini. Google retires model names over time. If the default model in this file stops working, the error message will include the reply from the API, and you can replace the name. Try this: send contents with two entries, the first with "role": "user" and the second with "role": "model" and the earlier answer, then add a new user turn.