Using Large Language Model APIs

This chapter builds command-line clients for three large language model APIs: a local Ollama model, the OpenAI chat API, and the Google Gemini API. All three follow one pattern, so once you have written one you can write any of them:

  1. Build the request as JSON with Yojson.
  2. POST it with Cohttp over Lwt.
  3. Decode the response with Yojson, returning a result.
  4. Read the API key from the environment, and turn every failure into a clear message.

There is no special SDK here. A REST endpoint plus a hand-written JSON codec is all you need, and doing it by hand shows exactly what goes over the wire. The examples are in source-code/ollama_commandline/, source-code/openai_api_client/, and source-code/gemini_commandline/.

A Local Ollama Client

Ollama runs a model on your own machine and serves it at http://localhost:11434. The file lib/ollama.ml defines records for the request, the response, and an error, then a codec for each. The request encoder is direct:

1 let request_to_yojson req =
2   `Assoc
3     [ ("model", `String req.model)
4     ; ("prompt", `String req.prompt)
5     ; ("stream", `Bool req.stream)
6     ]

The response decoder reads each field and returns a result, so a malformed reply becomes an Error instead of an exception. Note how it handles an optional field:

 1 let response_of_yojson json =
 2   let open Yojson.Safe.Util in
 3   try
 4     let m = json |> member "model" |> to_string in
 5     ...
 6     let dr =
 7       match json |> member "done_reason" with
 8       | `Null -> None
 9       | v -> Some (to_string v)
10     in
11     Ok { resp_model = m; ...; resp_done_reason = dr }
12   with
13   | _ -> Error "failed to parse OllamaResponse"

member "done_reason" returns `Null when the field is absent, which maps to None; otherwise the value maps to Some. Wrapping the whole read in a try turns any decode slip into the Error case.

The program in bin/main.ml makes the HTTP call. This client uses the Lwt.Infix operators, so promises chain with >>= rather than let*; the two styles are equivalent:

 1 let http_call () =
 2   Cohttp_lwt_unix.Client.post ~body ~headers uri
 3   >>= fun (resp, resp_body) ->
 4   let status = Cohttp.Response.status resp in
 5   let code = Cohttp.Code.code_of_status status in
 6   Cohttp_lwt.Body.to_string resp_body
 7   >>= fun body_str ->
 8   if Cohttp.Code.is_success code then
 9     match Yojson.Safe.from_string body_str |> Ollama.response_of_yojson with
10     | Ok r -> Lwt.return_ok r
11     | Error e -> Lwt.return_error ("JSON parse error: " ^ e)
12   else
13     ...

It POSTs the request, checks the status code, and decodes the body on success. If the call cannot connect at all, Lwt.catch reports that the Ollama service is not running, which is the common first-run problem. The command line takes a prompt and an optional model name:

1 cd source-code/ollama_commandline
2 dune exec bin/main.exe -- "What is the capital of France?"
3 dune exec bin/main.exe -- "Explain monads" "llama3.2"

The -- separates dune’s arguments from your program’s. With one argument it uses the default model, qwen3.5:4b, a small model that runs well on a laptop (pull it first with ollama pull qwen3.5:4b); with two it uses the model you name.

An OpenAI Chat Client

The OpenAI client, in openai_api_client/, calls the chat-completion endpoint. Its default model is gpt-5-mini, named once at the top of lib/openai.ml as default_model, a low-cost model that is plenty for the examples here. The codec is smaller than Ollama’s because the request is simpler: a model and a list of messages:

1 let chat_request_json ~model ~prompt =
2   `Assoc
3     [ ("model", `String model);
4       ( "messages",
5         `List
6           [ `Assoc [ ("role", `String "user"); ("content", `String prompt) ] ] )
7     ]

Reading the reply pulls the text out of choices[0].message.content, and falls back to the API’s own error message when the shape is different:

 1 let content_of_json json =
 2   let open Yojson.Safe.Util in
 3   match json |> member "choices" |> to_list with
 4   | choice :: _ -> (
 5     match choice |> member "message" |> member "content" with
 6     | `String s -> Ok s
 7     | _ -> Error "no content in first choice")
 8   | [] -> Error "no choices returned"
 9   | exception _ -> (
10     match json |> member "error" |> member "message" with
11     | `String s -> Error s
12     | _ -> Error "unexpected response shape")

The exception _ case is a nice touch: if reading choices throws because the response is actually an error object, it reads error.message instead and returns that as the Error. So an API error like an invalid key comes back as a readable string, not a crash.

The program posts to the endpoint with a Bearer token header and decodes on a 2xx status. It reads the key from the environment first, so a missing key fails early with instructions:

1 let () =
2   match Sys.getenv_opt "OPENAI_API_KEY" with
3   | None ->
4     print_endline "Error: OPENAI_API_KEY environment variable not set.";
5     ...
6     exit 1
7   | Some api_key -> ...

A Gemini Client

The Gemini client, in gemini_commandline/, calls the generateContent endpoint. With Gemini the model name is part of the URL rather than the request body, so lib/gemini.ml names the model once and builds the URL from it:

1 let default_model = "gemini-3.5-flash"
2 
3 let endpoint_for model =
4   "https://generativelanguage.googleapis.com/v1beta/models/" ^ model
5   ^ ":generateContent"

Gemini 3.5 Flash is Google’s current fast, low-cost model. When a newer one ships, changing default_model is the only edit, and a test checks the URL it produces. The codec builds a request with optional temperature and token limits, using OCaml’s optional arguments:

 1 let request_json ?(temperature = 0.1) ?(max_output_tokens = 800) prompt =
 2   `Assoc
 3     [ ( "contents",
 4         `List
 5           [ `Assoc
 6               [ ("parts", `List [ `Assoc [ ("text", `String prompt) ] ]) ] ] );
 7       ( "generationConfig",
 8         `Assoc
 9           [ ("temperature", `Float temperature);
10             ("maxOutputTokens", `Int max_output_tokens) ] )
11     ]

The ?(temperature = 0.1) gives a default, so callers pass only the prompt. Reading the reply walks down to candidates[0].content.parts[0].text, and when there are no candidates it checks whether the prompt was blocked, so a safety block gives a clear reason:

 1 let text_of_json json =
 2   let open Yojson.Safe.Util in
 3   match json |> member "candidates" |> to_list with
 4   | candidate :: _ -> (
 5     match candidate |> member "content" |> member "parts" |> to_list with
 6     | part :: _ -> Ok (part |> member "text" |> to_string)
 7     | [] -> Error "candidate with no parts")
 8   | [] -> (
 9     match json |> member "promptFeedback" |> member "blockReason" with
10     | `String r -> Error ("Blocked - " ^ r)
11     | _ -> Error "no candidates found in response")
12   | exception _ -> Error "unexpected response shape"

Entity Extraction With a Model

Both the OpenAI and Gemini clients show a small but useful trick: ask the model to return a comma-separated list, then parse it. Each codec has the same split_entities:

1 let split_entities response =
2   String.split_on_char ',' response
3   |> List.map String.trim
4   |> List.filter (fun s -> s <> "")

The Gemini demo wraps this in extract_entities, which builds a prompt that names the kind of entity and gives an example, then maps split_entities over the result:

 1 let extract_entities ~kind ~example ~api_key text =
 2   let prompt =
 3     Printf.sprintf
 4       "Extract only the %s strictly separated by commas from the following \
 5        text. Do not include any explanation or introduction. Example: %s\n\n\
 6        Text:\"%s\""
 7       kind example text
 8   in
 9   let* r = completion ~api_key prompt in
10   Lwt.return (Result.map Gemini.split_entities r)

Result.map applies split_entities only when the call succeeded, and leaves an Error untouched, so the parsing never runs on a failed request. The labelled arguments ~kind and ~example make each call read clearly:

1 let* places =
2   extract_entities ~kind:"place names" ~example:"London,Paris,Tokyo" ~api_key text
3 in
4 print_entities "Places" places;

With no command-line argument the Gemini demo runs this extraction on a sample paragraph, pulling out places, people, and companies. With an argument it runs that text as a single completion. This is the same task the classic NLP toolkit in Chapter 7 does with lexicons; here a model does it from a prompt.

Running the Clients

Each client needs its service or key. Ollama needs a running local server:

1 cd source-code/ollama_commandline
2 dune exec bin/main.exe -- "What is the capital of France?"

OpenAI and Gemini need an API key in the environment:

1 cd source-code/openai_api_client
2 export OPENAI_API_KEY=sk-...
3 dune exec ./bin/main.exe
4 
5 cd ../gemini_commandline
6 export GOOGLE_API_KEY=your-key-here
7 dune exec ./bin/main.exe                 # demo entity extraction
8 dune exec ./bin/main.exe -- "Explain OCaml functors"

Every one of these clients keeps its codec pure and separate from the HTTP call, so the tests exercise the JSON encode and decode offline, with no key and no network. That separation is the single most useful habit in this chapter: build and parse JSON in pure functions you can test, and let a thin Lwt wrapper do the I/O.