Skip to content

18. Managing the API Key

In this lesson, we will focus on securely managing the OpenAI API key within Emacs. Currently, the chatgpt-api-key variable is defined in the chatgpt.el file. However, storing API keys in code is not advisable. Instead, we can utilize the ~/.authinfo and ~/.authinfo.gpg files (the latter being the encrypted version using GPG) to securely store our API keys.

This section outlines the process for retrieving the API key from these files. We will provide an example using the non-encrypted file; however, the code can be applied uniformly across both encrypted and non-encrypted file methods.

Redefining the API Key Variable

First, we reset the chatgpt-api-key variable to nil:

(defvar chatgpt-api-key nil "OpenAI API key.")

Modifying the chatgpt-command Function

Next, we update the chatgpt-command function. This function checks if chatgpt-api-key is nil. If it is, it fetches the API key from either ~/.authinfo or ~/.authinfo.gpg using auth-source-pick-first-password and then store it for future use:

(defun chatgpt-command (req-path)
  "Return the curl command."
  (when (null chatgpt-api-key)
    (setq chatgpt-api-key
          (auth-source-pick-first-password :host "openai")))
  (format
   (concat "curl https://api.openai.com/v1/chat/completions "
           "-H 'Content-Type: application/json' "
           "-H 'Authorization: Bearer %s' "
           "-d @%s")
   chatgpt-api-key req-path))

Adding the API Key to ~/.authinfo File

We add our OpenAI API key in ~/.authinfo with the following format:

machine openai password sk-proj-7pQDxN...w-D40A

Restarting Emacs for Changes to Take Effect

I don't know why, but if we make changes to ~/.authinfo or ~/.authinfo.gpg during our Emacs session, they will not be reflected immediately. To test, we can evaluate the following which returns nil instead of our API key:

(auth-source-pick-first-password :host "openai") ;; nil

So we restart Emacs, open the chatgpt.el file, and evaluate it using M-x eval-buffer.

Testing the Setup

Now, we invoke the chatgpt-command function. In the prompt buffer, we enter the prompt foo, and press C-c C-c to send the request to OpenAI. We then receive a response which confirms that the integration is functioning as expected.

Finally, we verify that the chatgpt-api-key variable now contains the API key from our ~/.authinfo file by evaluating it in the minibuffer.