Local LLMs with Ollama
File: Ollama.lean
Ollama runs language models on your own computer and serves them over HTTP on port 11434. This program sends a prompt and prints the reply. It is the first program in the book that builds and reads JSON.
The Code
1 -- lean --run Ollama.lean (needs curl + a local Ollama server)
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 ollama (prompt : String) (model : String := "qwen3.5:4b") :
12 IO String := do
13 let body := Json.mkObj [
14 ("model", model), ("prompt", prompt),
15 ("stream", false), ("think", false)]
16 let raw ← run "curl" #["-sS",
17 "http://localhost:11434/api/generate", "-d", body.compress]
18 IO.ofExcept do
19 let json ← Json.parse raw
20 (← json.getObjVal? "response").getStr?
21
22 def main : IO Unit := do
23 IO.println (← ollama "what is 1 + 10?")
How It Works
import Lean.Data.Jsonloads the JSON library from the Lean distribution.open Lean (Json)lets the code writeJsonin place ofLean.Json.runstarts a program and returns its output, or throws an error if the program fails.{ cmd, args }is short for{ cmd := cmd, args := args }.curl -sShides the progress meter but still writes errors to stderr. If Ollama is not running,runreportscurl: (7) Failed to connectin place of an empty message.Json.mkObjbuilds a JSON object from a list of pairs. The values here are Lean strings and booleans. Lean converts each one to aJsonvalue.body.compresswrites the object as text with no extra spaces. The library adds the quotes and escapes, so a prompt can contain any characters.Json.parseand the accessor functions returnExcept String. The result is a value or an error message.getObjVal?reads a field of an object andgetStr?reads a string.IO.ofExceptturns anExceptinto anIOaction: it returns the value or throws the error.
"stream": false makes the server return one object. With streaming on, the reply is a sequence of JSON lines, and one Json.parse call fails; parse each line and collect the response fields.
The Reply
A reply to /api/generate is one JSON object. This shortened example shows the fields the program reads and two it could read:
1 {
2 "model": "qwen3.5:4b",
3 "response": "The sum of **1** and **10** is **11**.",
4 "done": true,
5 "done_reason": "stop",
6 "eval_count": 14,
7 "total_duration": 812000000
8 }
getObjVal? "response" selects the text. eval_count counts generated tokens and total_duration is nanoseconds, so eval_count / (total_duration / 1000000000) gives tokens per second. Fields not shown include created_at, load_duration, and prompt_eval_count.
Multi-turn Chat
/api/generate takes one prompt. For a conversation, use /api/chat with a list of messages. Each message has a role (system, user, or assistant) and content:
1 def ollamaChat (messages : List (String × String)) : IO String := do
2 let body := Json.mkObj [
3 ("model", "qwen3.5:4b"),
4 ("messages", Json.arr (messages.toArray.map fun (role, text) =>
5 Json.mkObj [("role", role), ("content", text)])),
6 ("stream", false)]
7 let raw ← run "curl" #["-sS",
8 "http://localhost:11434/api/chat", "-d", body.compress]
9 IO.ofExcept do
10 let json ← Json.parse raw
11 let message ← json.getObjVal? "message"
12 (← message.getObjVal? "content").getStr?
The reply nests the text under message, so the accessor path differs from /api/generate.
Generation Options
Add an options object to either request:
1 "options": {
2 "temperature": 0.2,
3 "num_predict": 256
4 }
temperature sets how much the output varies, and num_predict limits the number of generated tokens. Both are server-side settings, not part of the prompt. In the Lean builder, num_predict is a Nat and coerces to Json; a Float such as temperature needs an explicit JSON number. A system message at the start of the chat list is the usual place to set tone or output format.
Lean 4 Notes
Opening one name. open Lean would make every name in the Lean namespace available without its prefix. open Lean (Json) opens only Json. Other names keep their prefix, which avoids clashes with your own definitions.
How a string becomes JSON. Json is an inductive type with a constructor for each JSON form: null, boolean, number, string, array, and object. Json.mkObj takes a list of pairs of String and Json. In ("model", model), model is a String. The JSON library defines coercions from String, Bool, and Nat to Json, and Lean inserts them, as it inserts the Term coercion in the triple store chapter.
Except. Except String α has two constructors: ok with a value of type α, and error with a String. It is Option with a reason for the failure. A do block in Except stops at the first error and returns it.
One do inside another. ollama is an IO function, so its outer do block is in IO. The inner block after IO.ofExcept is in Except, because that is the type IO.ofExcept expects. Inside it, ← unwraps Except values. Lean picks the meaning of each block from its type.
Names that end in ?. By convention a function whose name ends in ? can fail and returns an Option or an Except. A name that ends in ! stops the program on failure.
Field shorthand. { cmd, args } builds a structure from two local variables whose names match the field names.
Running It
Install Ollama from https://ollama.com, start it, and pull the model:
1 ollama pull qwen3.5:4b
1 $ lean --run Ollama.lean
2 The sum of **1** and **10** is **11**.
Using It
Pass a second argument to use another model: ollama "your prompt" "llama3.2:3b". Run ollama list to see the models you have. The request sets "think" to false so that a reasoning model returns only its answer. Models without that option may reject or ignore the field, so drop it if the server returns an error.
Try this: print eval_count and compute tokens per second from total_duration. Then request JSON output by adding Ollama’s format field with a schema.