Generate, Complete Code in Emacs using OpenAI Codex
- API Key with access to OpenAI’s Codex You can get on the Codex beta waitlist by enrolling here
- Direct Install
- Put
codex-completion.el
in your Emacs load path. For e.g~/.emacs.d/lisp
- Load via use-package in your
~/.emacs.d/init.el
or.emacs
file by adding below snippet;; Codex Completion Package (use-package codex-completion :load-path "~/.emacs.d/lisp/codex-completion.el" :bind ("C-c ." . 'codex-complete) :config (setq codex-completion-openai-api-token <YOUR_OPENAI_API_TOKEN>))
- Put
- Using straight.el
- Ensure straight.el, straight-use-package are setup
- Add below snippet to your emacs config, e.g
~/.emacs.d/init.el
and evaluate it;; Codex-Completion Package (use-package codex-completion :straight (codex-completion :type git :host github :repo "debanjum/codex-completion") :bind ("C-c ." . 'codex-complete) :config (setq codex-completion-openai-api-token <YOUR_OPENAI_API_TOKEN>))
- Note: Procedure using Quelpa etc would be similar to straight.el
- Call
M-x codex-complete
it’ll take current paragraph till point as context to generate code OR - Call
M-x codex-complete-region
after marking text to use as context for the model OR - Call
M-x codex-complete-query
, then enter your instructions at prompt in minibuffer
Note: The code generated by the model will be inserted into the current buffer at point
Codex was instrumental in writing this tool.
Codex seems to understand the OpenAI API response schema.
Notice the choices
, text
keys used in the codex-get-completions
function below
- Prompt to Codex
;; define a elisp function to query OpenAI davinci codex at https://api.openai.com/v1/engines/davinci/completions for completion suggestions
- Response from Codex
;; define a elisp function to query OpenAI davinci codex at https://api.openai.com/v1/engines/davinci/completions for completion suggestions (defun codex-query (query) "Query OpenAI davinci codex at https://api.openai.com/v1/engines/davinci/completions for completion suggestions" (let ((url-request-method "POST") (url-request-extra-headers '(("Content-Type" . "application/json") ("Authorization" . "Bearer ") ("User-Agent" . "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36") ("Accept" . "application/json") ("Accept-Language" . "en-US,en;q=0.8"))) (url-request-data (json-encode `(("text" . ,query)))) (url-show-status nil)) (with-current-buffer (url-retrieve-synchronously "https://api.openai.com/v1/engines/davinci/completions") (goto-char (point-min)) (re-search-forward "^$") (json-read)))) ;; define a elisp function to get the completion suggestions from the json response (defun codex-get-completions (json) "Get the completion suggestions from the json response" (let ((completions (cdr (assoc 'choices json)))) (mapcar (lambda (completion) (cdr (assoc 'text completion))) completions)))