Configuring ChatGPT in Emacs

I've been delaying this for a while but finally got to setup ChatGPT in Emacs, leveraging 1Password to keep the OpenAPI API key secure.
I'm surprised by how well it works and how easy it was to setup. Before we go into the steps to make this happen, you're going to need a few things:
  • OpenAI API key
  • 1Password CLI
  • Emacs (I'm going to assume you have this one installed already)
  • Emacs package chatgpt-shell

Create an OpenAI API Key

First, you'll need to create an OpenAI account. You can do this by going to https://www.openai.com/. Once you've created an account, you'll need to create an API key.
You can do this by going to https://platform.openai.com/api-keys. Once you've created an API key, you'll need to copy it. You'll need this later.

Installation

First, you'll need to install the 1Password CLI. Follow these instructions. Once you have it installed, you'll need to login to your 1Password account. You can do this by running the following command:

op signin my.1password.com <email>

Once you've logged in, you'll need to create a new item in 1Password. You can do this by running the following command:

op item create --category passwords --title "OpenAI API key" 'password=<your API key>'

Once you've created the item, you'll need its title, the name of the vault it is stored in, and your 1Password account ID. Here's how it looks:

ID:          dwwvqrtlz5bdsdh3oihjtbomuu
Title:       OpenAI API key
Vault:       Personal (lmaicnh3f663z56c3i4563x67i)
Created:     now
Updated:     now
Favorite:    false
Version:     1
Category:    PASSWORD
Fields:
  password:    yaygpt
  

From the output, your title is OpenAI API key and the vault is Personal.

You can get the account ID by running the following command:

op account list

Setup Emacs

Now that you have your API key stored in 1Password, you'll need to setup Emacs to use it. You can do this by adding the following to your Emacs config (note the places where you need to swap with the title, vault and account id):

    
(use-package chatgpt-shell
  :ensure t
  :bind (("C-x c" . chatgpt-shell)
         :map chatgpt-shell-mode-map
         ("RET" . newline)
         ("M-RET" . shell-maker-submit))
  :custom
  (chatgpt-shell-openai-key
    (lambda ()
        (shell-command-to-string "op --no-color --account \
               <account id> read \
               'op://<vault>/<title>/password' \
               -n"))))
    
  
~ fin ~