package openai

  1. Overview
  2. Docs

Source file audio_transcription.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
let endpoint = "/v1/audio/transcriptions"

open Basic.Audio

let send
  (client : Client.t)
  ~(file : Basic.file_format)
  ?(model = "whisper-1")
  ?prompt
  ?(response_format = `Json)
  ?temperature
  ?language
  ()
  =
  let%lwt file = Basic.read_file file in
  let prompt = Json.to_field_opt "prompt" yojson_of_string prompt in
  let temperature = Json.to_field_opt "temperature" yojson_of_float temperature in
  let language = Json.to_field_opt "language" yojson_of_string language in
  let body =
    List.filter
      (fun (_, v) -> v <> `Null)
      [ "file", `String file
      ; "model", `String model
      ; "response_format", yojson_of_response_format response_format
      ; prompt
      ; temperature
      ; language
      ]
    |> fun l -> Yojson.Safe.to_string (`Assoc l)
  in
  let headers =
    [ "content-type", "application/json"
    ; "Authorization", String.concat " " [ "Bearer"; client.api_key ]
    ]
  in
  let%lwt resp =
    Ezcurl_lwt.post
      ~client:client.c
      ~headers
      ~content:(`String body)
      ~url:(client.gen_url endpoint)
      ~params:[]
      ()
  in
  match resp with
  | Ok { body; _ } ->
    let json = Yojson.Safe.from_string body in
    json |> json_to_response response_format |> Lwt.return
  | Error (_code, e) -> Lwt.fail_with e
;;