OCaml Claude SDK using Eio and Jsont
at main 38 lines 1.3 kB view raw
1(*--------------------------------------------------------------------------- 2 Copyright (c) 2025 Anil Madhavapeddy <anil@recoil.org>. All rights reserved. 3 SPDX-License-Identifier: ISC 4 ---------------------------------------------------------------------------*) 5 6let src = Logs.Src.create "claude.structured_output" ~doc:"Structured output" 7 8module Log = (val Logs.src_log src : Logs.LOG) 9 10type t = { json_schema : Jsont.json } 11 12let json_to_string json = 13 match Jsont_bytesrw.encode_string' Jsont.json json with 14 | Ok str -> str 15 | Error err -> failwith (Jsont.Error.to_string err) 16 17let of_json_schema schema = 18 Log.debug (fun m -> 19 m "Created output format from JSON schema: %s" (json_to_string schema)); 20 { json_schema = schema } 21 22let json_schema t = t.json_schema 23 24(* Codec for serializing structured output format *) 25let jsont : t Jsont.t = 26 Jsont.Object.map ~kind:"StructuredOutput" (fun json_schema -> { json_schema }) 27 |> Jsont.Object.mem "jsonSchema" Jsont.json ~enc:(fun t -> t.json_schema) 28 |> Jsont.Object.finish 29 30let to_json t = 31 match Jsont.Json.encode jsont t with 32 | Ok json -> json 33 | Error msg -> failwith ("Structured_output.to_json: " ^ msg) 34 35let of_json json = 36 match Jsont.Json.decode jsont json with 37 | Ok t -> t 38 | Error msg -> raise (Invalid_argument ("Structured_output.of_json: " ^ msg))