openai.el 2.0 KB

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