OCaml Claude SDK using Eio and Jsont
at main 93 lines 3.1 kB view raw
1(*--------------------------------------------------------------------------- 2 Copyright (c) 2025 Anil Madhavapeddy <anil@recoil.org>. All rights reserved. 3 SPDX-License-Identifier: ISC 4 ---------------------------------------------------------------------------*) 5 6(* Simple example showing structured output with explicit JSON Schema *) 7 8module C = Claude 9 10let () = 11 Logs.set_reporter (Logs_fmt.reporter ()); 12 Logs.set_level (Some Logs.Info) 13 14let simple_example env = 15 Printf.printf "\n=== Simple Structured Output Example ===\n\n"; 16 17 (* Define a simple schema for a person's info *) 18 let person_schema = 19 let open Jsont in 20 Object 21 ( [ 22 (("type", Meta.none), String ("object", Meta.none)); 23 ( ("properties", Meta.none), 24 Object 25 ( [ 26 ( ("name", Meta.none), 27 Object 28 ( [ (("type", Meta.none), String ("string", Meta.none)) ], 29 Meta.none ) ); 30 ( ("age", Meta.none), 31 Object 32 ( [ (("type", Meta.none), String ("integer", Meta.none)) ], 33 Meta.none ) ); 34 ( ("occupation", Meta.none), 35 Object 36 ( [ (("type", Meta.none), String ("string", Meta.none)) ], 37 Meta.none ) ); 38 ], 39 Meta.none ) ); 40 ( ("required", Meta.none), 41 Array 42 ( [ 43 String ("name", Meta.none); 44 String ("age", Meta.none); 45 String ("occupation", Meta.none); 46 ], 47 Meta.none ) ); 48 ], 49 Meta.none ) 50 in 51 52 let output_format = 53 Claude.Proto.Structured_output.of_json_schema person_schema 54 in 55 56 let options = 57 C.Options.default 58 |> C.Options.with_output_format output_format 59 |> C.Options.with_max_turns 1 60 in 61 62 Printf.printf "Asking Claude to provide structured data...\n\n"; 63 64 Eio.Switch.run @@ fun sw -> 65 let process_mgr = Eio.Stdenv.process_mgr env in 66 let clock = Eio.Stdenv.clock env in 67 let client = C.Client.create ~sw ~process_mgr ~clock ~options () in 68 69 C.Client.query client 70 "Tell me about a famous computer scientist. Provide their name, age, and \ 71 occupation in the exact JSON structure I specified."; 72 73 let responses = C.Client.receive_all client in 74 List.iter 75 (function 76 | C.Response.Complete result -> ( 77 Printf.printf "Response received!\n"; 78 match C.Response.Complete.structured_output result with 79 | Some json -> 80 Printf.printf "\nStructured Output:\n%s\n" 81 (Test_json_utils.to_string ~minify:false json) 82 | None -> Printf.printf "No structured output\n") 83 | C.Response.Error err -> 84 Printf.printf "Error: %s\n" (C.Response.Error.message err) 85 | _ -> ()) 86 responses 87 88let () = 89 Eio_main.run @@ fun env -> 90 try simple_example env 91 with exn -> 92 Printf.eprintf "Error: %s\n" (Printexc.to_string exn); 93 exit 1