Skip to content

Instantly share code, notes, and snippets.

@whilo
Last active March 17, 2024 02:59
Show Gist options
  • Save whilo/bc7e7c066a8fbe1b964e6e8ca61cb3b1 to your computer and use it in GitHub Desktop.
Save whilo/bc7e7c066a8fbe1b964e6e8ca61cb3b1 to your computer and use it in GitHub Desktop.
OpenAI calls from Clojure
(ns openai.example
(:require [clojure.java.io :as io]
[libpython-clj2.require :refer [require-python]]
[libpython-clj2.python :refer [py. py.. py.-] :as py]
[taoensso.timbre :as log]))
(require-python '[openai :refer [OpenAI]])
(def client (OpenAI :api_key "..."))
(defn ask-gpt35 [text]
(let [res ((py.- (py.- (py.- client chat) completions) create) :model "gpt-3.5-turbo" :messages [{:role "system" :content text}])]
(py.- (py.- (first (py.- res choices)) message) content)))
(defn use-dalle-2 [text]
(let [res ((py.- (py.- client images) generate) :model "dall-e-2" :prompt text)]
(prn "res" res)
(py.- (first (py.- res data)) url)))
(defn use-whisper [input-path]
(let [audio-file ((py.- (py.- (py.- client audio) transcriptions) create) :model "whisper-1" :file ((py/path->py-obj "builtins.open") input-path "rb"))]
(py.- audio-file text)))
(require-python '[pathlib :refer [Path]])
(defn use-tts [text]
(let [res ((py.- (py.- (py.- client audio) speech) create) :model "tts-1" :voice "alloy" :input text)
rand-path (str "/tmp/" (java.util.UUID/randomUUID) ".mp3")]
((py.- res stream_to_file) (Path rand-path))
rand-path))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment