openai.el 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. (goto-char (point-max))
  27. (insert (format ">>> %s -- Response: %s"
  28. (format-time-string "%Y-%m-%d %H:%M:%S")
  29. (cdr (assoc 'content
  30. (cdr (assoc 'message
  31. (elt
  32. (cdr (assoc 'choices data)) 0))))))))))
  33. :success (cl-function (lambda (&key data &allow-other-keys)
  34. (setq response-json data)))
  35. :error (cl-function (lambda (&key error-thrown data &allow-other-keys)
  36. (with-current-buffer openai-response-buffer
  37. (goto-char (point-max))
  38. (insert "\n")
  39. (insert (format "Response Error: %S \n %s \n" error-thrown data))))))))
  40. (defun ask-gpt (prompt)
  41. (interactive "sEnter a prompt: ")
  42. (openai-api-request prompt))