emacs-openai / openai

Elisp library for the OpenAI API
GNU General Public License v3.0
103 stars 17 forks source link

Support Azure Active Directory authentication #16

Closed JCZuurmond closed 1 year ago

JCZuurmond commented 1 year ago

As a follow-up on #14, when using the Azure OpenAI Service REST API, support the Azure Active Directory Authentication.

JCZuurmond commented 1 year ago

This is solved by using the following function:

(defun get-openai-key ()
  "Retrieve the OpenAI API key from Azure CLI."
  (let* ((output (with-output-to-string
                  (call-process "az" nil standard-output nil
                                  "account" "get-access-token" "--resource" "https://cognitiveservices.azure.com")))
          (json (json-read-from-string output)))
  (cdr (assoc 'accessToken json))))

Then set the openai-key: `(setq openai-key (get-openai-key))).

Note that this does not work at start-up for some reason. Emacs warns that the output is empty. I run it after loading the openai package, using the after function in Doom Emacs as such:

(defun get-openai-key ()
  "Retrieve the OpenAI API key from Azure CLI."
  (let* ((output (with-output-to-string
                  (call-process "az" nil standard-output nil
                                  "account" "get-access-token" "--resource" "https://cognitiveservices.azure.com")))
          (json (json-read-from-string output)))
  (cdr (assoc 'accessToken json))))

(after! openai
  (setq openai-key (get-openai-key)))