emacs/elisp/openai.el
1	(straight-use-package 'request)
2 (defvar openai-response-buffer (get-buffer-create "*openai-response*"))
3 (defvar openai-api-key (getenv "OPENAI_API_KEY"))
4
5 (defun openai-api-request (prompt)
6 "Send a request to the OpenAI API with the given prompt and return the response."
7 (let* ((url "https://api.openai.com/v1/chat/completions")
8 (params `(("model" . "gpt-3.5-turbo")
9 ("messages" . ,(vector (list (cons "role" "user") (cons "content" prompt))))))
10 (headers `(("Content-Type" . "application/json")
11 ("Authorization" . ,(concat "Bearer " openai-api-key))))
12 (response-json nil))
13 (with-current-buffer openai-response-buffer
14 (goto-char (point-max))
15 (insert "\n\n")
16 (insert (format ">>> %s -- Prompt: %s\n" (format-time-string "%Y-%m-%d %H:%M:%S") prompt)))
17 (request
18 url
19 ;; :sync t
20 :timeout 60
21 :type "POST"
22 :data (json-encode params)
23 :headers headers
24 :parser 'json-read
25 :complete (cl-function (lambda (&key data &allow-other-keys)
26 (with-current-buffer openai-response-buffer
27 (when (not (get-buffer-window (buffer-name openai-response-buffer)))
28 (let ((window (split-window)))
29 (set-window-buffer window openai-response-buffer)))
30 (goto-char (point-max))
31 (insert (format ">>> %s -- Response: %s"
32 (format-time-string "%Y-%m-%d %H:%M:%S")
33 (cdr (assoc 'content
34 (cdr (assoc 'message
35 (elt
36 (cdr (assoc 'choices data)) 0))))))))))
37 :success (cl-function (lambda (&key data &allow-other-keys)
38 (setq response-json data)))
39 :error (cl-function (lambda (&key error-thrown data &allow-other-keys)
40 (with-current-buffer openai-response-buffer
41 (goto-char (point-max))
42 (insert "\n")
43 (insert (format "Response Error: %S \n %s \n" error-thrown data))))))))
44
45 (defun ask-gpt (prompt)
46 (interactive "sEnter a prompt: ")
47 (openai-api-request prompt))