Skip to content

Instantly share code, notes, and snippets.

@chase-lambert
Last active June 7, 2023 08:35
Show Gist options
  • Save chase-lambert/c5533d8e8fbb71268a25e83ecf8e3cc6 to your computer and use it in GitHub Desktop.
Save chase-lambert/c5533d8e8fbb71268a25e83ecf8e3cc6 to your computer and use it in GitHub Desktop.
chatGPT API cli
#!/usr/bin/env bb
;; You need to have an OpenAI API key and set it like:
;; export OPENAI_API_KEY=<your key> in your .bashrc
;;
;; Make sure you have babashka installed
;; https://github.com/babashka/babashka#installation
;;
;; One way to run this is to install bbin
;; https://github.com/babashka/bbin
;; and then run
;; bbin install https://gist.githubusercontent.com/chase-lambert/c5533d8e8fbb71268a25e83ecf8e3cc6/raw/9cc7b4208f9bed2609f4736c4f469e1828273af5/chatgpt-cli.clj
;;
;; I need to use rlwrap to get it working how I like it
;; so after installing with bbin I created an alias in
;; my .bashrc: alias chat="rlwrap chatgpt-cli"
;; so I can just run this in my terminal with "chat"
;; Or you can just copy/paste this code into a file, make it executable:
;; chmod +x file
;; and run it with:
;; ./file
(require '[babashka.http-client :as client])
(require '[cheshire.core :as json])
(def api-key (System/getenv "OPENAI_API_KEY"))
(defonce messages (atom [{:role "system"
:content "You are a helpful assistant"}]))
(defn request [prompt]
(swap! messages conj {:role "user"
:content prompt})
(client/post "https://api.openai.com/v1/chat/completions"
{:headers {"Content-Type" "application/json"
"Authorization" (str "Bearer " api-key)}
:body (json/generate-string
{:model "gpt-3.5-turbo"
:messages @messages})}))
(defn response [resp]
(let [resp (json/parse-string (:body resp) true)
content (get-in resp [:choices 0 :message :content])
_ (swap! messages conj {:role "assistant"
:content content})]
content))
(println "Welcome to ChatGPT CLI")
(print "Please enter a prompt: ")
(flush)
(loop [prompt (read-line)]
(let [resp (response (request prompt))]
(println)
(println "ChatGPT response:" resp)
(println)
(print "User: ")
(flush)
(recur (read-line))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment