2023-03-08 01:00:06 -08:00
;;; gptel.el --- A simple ChatGPT client -*- lexical-binding: t; -*-
2023-03-05 16:59:44 -08:00
;; Copyright (C) 2023 Karthik Chikmagalur
;; Author: Karthik Chikmagalur
2023-03-08 19:25:14 -08:00
;; Version: 0.10
2023-03-17 23:46:30 -07:00
;; Package-Requires: ((emacs "27.1") (transient "0.3.7"))
2023-03-05 16:59:44 -08:00
;; Keywords: convenience
2023-03-05 17:46:38 -08:00
;; URL: https://github.com/karthink/gptel
2023-03-05 16:59:44 -08:00
2023-03-05 18:08:53 -08:00
;; SPDX-License-Identifier: GPL-3.0-or-later
2023-03-05 16:59:44 -08:00
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-03-05 18:08:53 -08:00
;; This file is NOT part of GNU Emacs.
2023-03-05 16:59:44 -08:00
;;; Commentary:
2023-03-19 19:58:19 -07:00
;; A simple ChatGPT client for Emacs.
2023-03-05 17:46:38 -08:00
;;
;; Requirements:
2023-03-05 16:59:44 -08:00
;; - You need an OpenAI API key. Set the variable `gptel-api-key' to the key or to
;; a function of no arguments that returns the key.
;;
;; - Not required but recommended: Install `markdown-mode'.
;;
2023-03-05 17:46:38 -08:00
;; Usage:
2023-03-19 19:58:19 -07:00
;; gptel can be used in any buffer or in a dedicated chat buffer.
;;
;; To use this in a dedicated buffer:
2023-03-05 16:59:44 -08:00
;; - M-x gptel: Start a ChatGPT session
2023-03-19 19:58:19 -07:00
;; - C-u M-x gptel: Start another session or multiple independent ChatGPT sessions
;;
;; - In the chat session: Press `C-c RET' (`gptel-send') to send
;; your prompt. Use a prefix argument (`C-u C-c RET') to set chat parameters.
;;
;; To use this in any buffer:
2023-03-05 16:59:44 -08:00
;;
2023-03-19 19:58:19 -07:00
;; - Select a region of text and call `gptel-send'. Call with a prefix argument
;; to set chat parameters.
;; - You can select previous prompts and responses to continue the conversation.
2023-03-05 16:59:44 -08:00
;;; Code:
( declare-function markdown-mode " markdown-mode " )
2023-03-08 19:17:14 -08:00
( declare-function gptel-curl-get-response " gptel-curl " )
2023-03-08 19:25:14 -08:00
( declare-function gptel-send-menu " gptel-transient " )
2023-03-09 22:01:28 -08:00
( declare-function pulse-momentary-highlight-region " pulse " )
2023-03-08 00:52:48 -08:00
2023-03-05 16:59:44 -08:00
( eval-when-compile
2023-03-08 00:52:48 -08:00
( require 'subr-x )
( require 'cl-lib ) )
2023-03-05 16:59:44 -08:00
2023-03-17 23:46:30 -07:00
( require 'url )
2023-03-05 16:59:44 -08:00
( require 'json )
( require 'map )
2023-03-08 19:10:20 -08:00
( require 'text-property-search )
2023-03-05 16:59:44 -08:00
2023-03-18 08:41:25 +01:00
( defcustom gptel-api-key #' gptel-api-key-from-auth-source
2023-03-05 17:46:38 -08:00
" An OpenAI API key (string).
Can also be a function of no arguments that returns an API
key ( more secure ) . "
:group 'gptel
2023-03-05 16:59:44 -08:00
:type ' ( choice
( string :tag " API key " )
2023-03-18 08:41:25 +01:00
( function :tag " Function that returns the API key " ) ) )
2023-03-05 16:59:44 -08:00
2023-03-08 00:52:48 -08:00
( defcustom gptel-playback nil
" Whether responses from ChatGPT be played back in chunks.
When set to nil , it is inserted all at once.
'tis a bit silly. "
:group 'gptel
:type 'boolean )
( defcustom gptel-use-curl ( and ( executable-find " curl " ) t )
" Whether gptel should prefer Curl when available. "
:group 'gptel
:type 'boolean )
2023-03-10 04:12:32 -08:00
( defcustom gptel-response-filter-functions
' ( gptel--convert-org )
" Abnormal hook for transforming the response from ChatGPT.
This is useful if you want to format the response in some way,
such as filling paragraphs, adding annotations or recording
information in the response like links.
Each function in this hook receives two arguments, the response
string to transform and the ChatGPT interaction buffer. It should
return the transformed string. "
:group 'gptel
:type 'hook )
2023-03-05 17:46:38 -08:00
( defvar gptel-default-session " *ChatGPT* " )
( defvar gptel-default-mode ( if ( featurep 'markdown-mode )
'markdown-mode
'text-mode ) )
( defvar gptel-prompt-string " ### " )
2023-03-05 16:59:44 -08:00
2023-03-08 19:20:00 -08:00
;; Model and interaction parameters
( defvar-local gptel--system-message
" You are a large language model living in Emacs and a helpful assistant. Respond concisely. " )
( defvar gptel--system-message-alist
` ( ( default . , gptel--system-message )
2023-03-10 03:55:43 -08:00
( programming . " You are a large language model and a careful programmer. Provide code and only code as output without any additional text, prompt or note. " )
2023-03-08 19:20:00 -08:00
( writing . " You are a large language model and a writing assistant. Respond concisely. " )
( chat . " You are a large language model and a conversation partner. Respond concisely. " ) )
" Prompt templates (directives). " )
2023-03-12 15:40:39 -07:00
( defvar gptel--debug nil )
2023-03-08 19:20:00 -08:00
( defvar-local gptel--max-tokens nil )
( defvar-local gptel--model " gpt-3.5-turbo " )
( defvar-local gptel--temperature 1.0 )
2023-03-08 19:10:20 -08:00
( defvar-local gptel--num-messages-to-send nil )
2023-03-18 08:41:25 +01:00
( defun gptel-api-key-from-auth-source ( &optional host user )
" Lookup api key in the auth source.
By default, \"openai.com\" is used as HOST and \"apikey\" as USER. "
( if-let ( ( secret ( plist-get ( car ( auth-source-search
:host ( or host " openai.com " )
:user ( or user " apikey " ) ) )
:secret ) ) )
( if ( functionp secret ) ( funcall secret ) secret )
( user-error " No `gptel-api-key' found in the auth source " ) ) )
( defun gptel--api-key ( )
" Get api key from `gptel-api-key' . "
( pcase gptel-api-key
( ( pred stringp ) gptel-api-key )
( ( pred functionp ) ( funcall gptel-api-key ) )
( _ ( error " `gptel-api-key' is not set " ) ) ) )
2023-03-10 22:27:31 -08:00
( defun gptel--update-header-line ( msg face )
2023-03-10 22:43:28 -08:00
" Update header line with status MSG in FACE. "
2023-03-10 22:27:31 -08:00
( and header-line-format
( setf ( nth 1 header-line-format )
( propertize msg 'face face ) )
( force-mode-line-update ) ) )
2023-03-08 19:10:20 -08:00
( defsubst gptel--numberize ( val )
" Ensure VAL is a number. "
( if ( stringp val ) ( string-to-number val ) val ) )
2023-03-10 22:43:28 -08:00
( defvar-local gptel--old-header-line nil )
( define-minor-mode gptel-mode
" Minor mode for interacting with ChatGPT. "
:glboal nil
:lighter " GPT "
:keymap
( let ( ( map ( make-sparse-keymap ) ) )
( define-key map ( kbd " C-c RET " ) #' gptel-send )
map )
( if gptel-mode
( setq gptel--old-header-line header-line-format
header-line-format
( list ( concat ( propertize " " 'display ' ( space :align-to 0 ) )
( format " %s " ( buffer-name ) ) )
( propertize " Ready " 'face 'success ) ) )
( setq header-line-format gptel--old-header-line ) ) )
;; TODO: Handle read-only buffers. Should we spawn a new buffer automatically?
;; TODO: Handle multiple requests(#15). (Only one request from one buffer at a time?)
2023-03-17 23:46:30 -07:00
;; TODO: Since we capture a marker for the insertion location, `gptel-buffer' no
;; longer needs to be recorded
2023-03-25 04:16:55 +09:00
;;;###autoload
2023-03-17 23:46:30 -07:00
( defun gptel-send ( &optional arg )
" Submit this prompt to ChatGPT.
With prefix arg ARG activate a transient menu with more options
instead. "
2023-03-08 19:25:14 -08:00
( interactive " P " )
2023-03-09 16:56:26 -08:00
( if ( and arg ( require 'gptel-transient nil t ) )
2023-03-08 19:25:14 -08:00
( call-interactively #' gptel-send-menu )
2023-03-05 16:59:44 -08:00
( message " Querying ChatGPT... " )
2023-03-10 22:27:31 -08:00
( gptel--update-header-line " Waiting... " 'warning )
2023-03-14 02:04:02 -07:00
( let* ( ( response-pt
( if ( use-region-p )
( set-marker ( make-marker ) ( region-end ) )
( point-marker ) ) )
2023-03-10 22:27:31 -08:00
( gptel-buffer ( current-buffer ) )
2023-03-17 23:46:30 -07:00
( full-prompt ( gptel--create-prompt response-pt ) ) )
( funcall
( if gptel-use-curl
#' gptel-curl-get-response #' gptel--url-get-response )
( list :prompt full-prompt
:gptel-buffer gptel-buffer
:insert-marker response-pt ) ) ) ) )
( defun gptel--insert-response ( response info )
" Insert RESPONSE from ChatGPT into the gptel buffer.
INFO is a plist containing information relevant to this buffer.
See ` gptel--url-get-response ' for details. "
( let* ( ( content-str ( plist-get response :content ) )
( status-str ( plist-get response :status ) )
( gptel-buffer ( plist-get info :gptel-buffer ) )
( response-pt ( plist-get info :insert-marker ) ) )
2023-03-08 00:52:48 -08:00
( if content-str
2023-03-09 14:14:06 -08:00
( with-current-buffer gptel-buffer
2023-03-10 04:12:32 -08:00
( setq content-str ( gptel--transform-response
content-str gptel-buffer ) )
2023-03-09 14:14:06 -08:00
( save-excursion
( put-text-property 0 ( length content-str ) 'gptel 'response content-str )
( message " Querying ChatGPT... done. " )
2023-03-10 22:27:31 -08:00
( goto-char response-pt )
( unless ( bobp ) ( insert-before-markers-and-inherit " \n \n " ) )
2023-03-09 14:14:06 -08:00
( if gptel-playback
2023-03-10 22:27:31 -08:00
( gptel--playback gptel-buffer content-str response-pt )
2023-03-09 22:01:28 -08:00
( let ( ( p ( point ) ) )
( insert content-str )
2023-03-10 22:27:31 -08:00
( pulse-momentary-highlight-region p ( point ) ) )
( when gptel-mode
( insert " \n \n " gptel-prompt-string )
( gptel--update-header-line " Ready " 'success ) ) ) )
( goto-char ( - ( point ) 2 ) ) )
( gptel--update-header-line
2023-03-17 23:46:30 -07:00
( format " Response Error: %s " status-str ) 'error ) ) ) )
2023-03-10 22:27:31 -08:00
( defun gptel--create-prompt ( &optional prompt-end )
2023-03-08 19:10:20 -08:00
" Return a full conversation prompt from the contents of this buffer.
If ` gptel--num-messages-to-send ' is set, limit to that many
recent exchanges.
If the region is active limit the prompt to the region contents
2023-03-10 22:27:31 -08:00
instead.
If PROMPT-END ( a marker ) is provided, end the prompt contents
there. "
2023-03-08 19:10:20 -08:00
( save-excursion
( save-restriction
2023-03-10 22:27:31 -08:00
( if ( use-region-p )
( progn ( narrow-to-region ( region-beginning ) ( region-end ) )
( goto-char ( point-max ) ) )
( goto-char ( or prompt-end ( point-max ) ) ) )
2023-03-08 19:10:20 -08:00
( let ( ( max-entries ( and gptel--num-messages-to-send
( * 2 ( gptel--numberize
gptel--num-messages-to-send ) ) ) )
( prop ) ( prompts ) )
( while ( and
( or ( not max-entries ) ( >= max-entries 0 ) )
( setq prop ( text-property-search-backward
'gptel 'response
( when ( get-char-property ( max ( point-min ) ( 1- ( point ) ) )
'gptel )
t ) ) ) )
( push ( list :role ( if ( prop-match-value prop ) " assistant " " user " )
:content
( string-trim
( buffer-substring-no-properties ( prop-match-beginning prop )
( prop-match-end prop ) )
" [*# \t \n \r ]+ " ) )
prompts )
( and max-entries ( cl-decf max-entries ) ) )
( cons ( list :role " system "
2023-03-10 04:12:32 -08:00
:content gptel--system-message )
2023-03-08 19:10:20 -08:00
prompts ) ) ) ) )
2023-03-08 19:20:00 -08:00
( defun gptel--request-data ( prompts )
" JSON encode PROMPTS for sending to ChatGPT. "
( let ( ( prompts-plist
` ( :model , gptel--model
:messages [ ,@ prompts ] ) ) )
( when gptel--temperature
( plist-put prompts-plist :temperature ( gptel--numberize gptel--temperature ) ) )
( when gptel--max-tokens
( plist-put prompts-plist :max_tokens ( gptel--numberize gptel--max-tokens ) ) )
prompts-plist ) )
2023-03-05 16:59:44 -08:00
2023-03-10 04:12:32 -08:00
;; TODO: Use `run-hook-wrapped' with an accumulator instead to handle
;; buffer-local hooks, etc.
( defun gptel--transform-response ( content-str buffer )
2023-03-10 22:43:28 -08:00
" Filter CONTENT-STR through ` gptel-response-filter-functions ` .
BUFFER is passed along with CONTENT-STR to each function in this
hook. "
2023-03-10 04:12:32 -08:00
( let ( ( filtered-str content-str ) )
( dolist ( filter-func gptel-response-filter-functions filtered-str )
( condition-case nil
( when ( functionp filter-func )
( setq filtered-str
( funcall filter-func filtered-str buffer ) ) )
( error
( display-warning ' ( gptel filter-functions )
( format " Function %S returned an error "
filter-func ) ) ) ) ) ) )
( defun gptel--convert-org ( content buffer )
" Transform CONTENT according to required major-mode.
2023-03-10 22:43:28 -08:00
Currently only ` org-mode ' is handled.
2023-03-10 04:12:32 -08:00
BUFFER is the interaction buffer for ChatGPT. "
( pcase ( buffer-local-value 'major-mode buffer )
( 'org-mode ( gptel--convert-markdown->org content ) )
( _ content ) ) )
2023-03-17 23:46:30 -07:00
( defun gptel--url-get-response ( info )
" Fetch response to prompt in INFO from ChatGPT.
2023-03-05 17:46:38 -08:00
2023-03-17 23:46:30 -07:00
INFO is a plist with the following keys:
- :prompt ( the prompt being sent )
- :gptel-buffer ( the gptel buffer )
- :insert-marker ( marker at which to insert the response ) . "
2023-03-08 00:52:48 -08:00
( let* ( ( inhibit-message t )
( message-log-max nil )
2023-03-05 16:59:44 -08:00
( url-request-method " POST " )
( url-request-extra-headers
` ( ( " Content-Type " . " application/json " )
2023-03-18 08:41:25 +01:00
( " Authorization " . , ( concat " Bearer " ( gptel--api-key ) ) ) ) )
2023-03-05 16:59:44 -08:00
( url-request-data
2023-03-17 23:46:30 -07:00
( encode-coding-string
( json-encode ( gptel--request-data ( plist-get info :prompt ) ) )
'utf-8 ) ) )
( url-retrieve " https://api.openai.com/v1/chat/completions "
( lambda ( _ )
( let ( ( response
( gptel--url-parse-response ( current-buffer ) ) ) )
( gptel--insert-response response info )
( kill-buffer ) ) )
nil t nil ) ) )
2023-03-08 00:52:48 -08:00
2023-03-10 03:55:43 -08:00
( defun gptel--url-parse-response ( response-buffer )
2023-03-08 00:52:48 -08:00
" Parse response in RESPONSE-BUFFER. "
( when ( buffer-live-p response-buffer )
2023-03-12 15:40:39 -07:00
( when gptel--debug
( with-current-buffer response-buffer
( clone-buffer " *gptel-error* " 'show ) ) )
2023-03-08 00:52:48 -08:00
( with-current-buffer response-buffer
( if-let* ( ( status ( buffer-substring ( line-beginning-position ) ( line-end-position ) ) )
2023-03-12 15:40:39 -07:00
( json-object-type 'plist )
2023-03-08 00:52:48 -08:00
( response ( progn ( forward-paragraph )
2023-03-22 18:34:18 -07:00
( condition-case nil
( json-read )
( json-readtable-error 'json-read-error ) ) ) ) )
( cond
( ( string-match-p " 200 OK " status )
( list :content ( string-trim
( decode-coding-string
2023-03-23 14:34:26 -07:00
( map-nested-elt
response ' ( :choices 0 :message :content ) )
2023-03-22 18:34:18 -07:00
'utf-8 ) )
:status status ) )
( ( plist-get response :error )
( let* ( ( error-plist ( plist-get response :error ) )
( error-msg ( plist-get error-plist :message ) )
( error-type ( plist-get error-plist :type ) ) )
( message " ChatGPT error: %s " error-msg )
( list :content nil :status ( concat status " : " error-type ) ) ) )
( ( eq response 'json-read-error )
( message " ChatGPT error: Malformed JSON in response. " )
( list :content nil :status ( concat http-msg " : Malformed JSON in response. " ) ) )
( t ( message " ChatGPT error: Could not parse HTTP response. " )
( list :content nil :status ( concat status " : Could not parse HTTP response. " ) ) ) )
( message " ChatGPT error: Could not parse HTTP response. " )
( list :content nil
:status ( concat status " : Could not parse HTTP response. " ) ) ) ) ) )
2023-03-05 16:59:44 -08:00
2023-03-05 17:46:38 -08:00
;;;###autoload
2023-03-09 22:58:54 -08:00
( defun gptel ( name &optional api-key initial )
2023-03-05 17:46:38 -08:00
" Switch to or start ChatGPT session with NAME.
With a prefix arg, query for a ( new ) session name.
2023-03-09 22:58:54 -08:00
Ask for API-KEY if ` gptel-api-key ' is unset.
2023-03-11 18:40:06 -08:00
If region is active, use it as the INITIAL prompt. Returns the
buffer created or switched to. "
2023-03-05 17:46:38 -08:00
( interactive ( list ( if current-prefix-arg
( read-string " Session name: " ( generate-new-buffer-name gptel-default-session ) )
gptel-default-session )
2023-03-18 12:59:25 -07:00
( condition-case nil
( gptel--api-key )
( ( error user-error )
( read-passwd " OpenAI API key: " ) ) )
2023-03-09 22:58:54 -08:00
( and ( use-region-p )
( buffer-substring ( region-beginning )
( region-end ) ) ) ) )
2023-03-05 17:46:38 -08:00
( unless api-key
( user-error " No API key available " ) )
( with-current-buffer ( get-buffer-create name )
2023-03-05 18:43:49 -08:00
( cond ;Set major mode
( ( eq major-mode gptel-default-mode ) )
( ( eq gptel-default-mode 'text-mode )
( text-mode )
( visual-line-mode 1 ) )
( t ( funcall gptel-default-mode ) ) )
2023-03-05 17:46:38 -08:00
( unless gptel-mode ( gptel-mode 1 ) )
2023-03-09 22:58:54 -08:00
( if ( bobp ) ( insert ( or initial gptel-prompt-string ) ) )
2023-03-05 17:46:38 -08:00
( pop-to-buffer ( current-buffer ) )
( goto-char ( point-max ) )
( skip-chars-backward " \t \r \n " )
( message " Send your query with %s! "
( substitute-command-keys " \\ [gptel-send] " ) ) ) )
2023-03-10 04:12:32 -08:00
( defun gptel--convert-markdown->org ( str )
" Convert string STR from markdown to org markup.
This is a very basic converter that handles only a few markup
elements. "
( interactive )
( with-temp-buffer
( insert str )
( goto-char ( point-min ) )
( while ( re-search-forward " ` \\ | \\ * \\ {1,2 \\ } \\ |_ " nil t )
( pcase ( match-string 0 )
( " ` " ( if ( looking-at " ` ` " )
( progn ( backward-char )
( delete-char 3 )
( insert " #+begin_src " )
( when ( re-search-forward " ^ ` ` ` " nil t )
( replace-match " #+end_src " ) ) )
( replace-match " = " ) ) )
( " ** " ( cond
( ( looking-at " \\ * \\ (?:[[:word:]] \\ | \s \\ ) " )
( delete-char 1 ) )
( ( looking-back " \\ (?:[[:word:]] \\ | \s \\ ) \\ * \\ {2 \\ } "
( max ( - ( point ) 3 ) ( point-min ) ) )
( backward-delete-char 1 ) ) ) )
( ( or " _ " " * " )
( if ( save-match-data
( and ( looking-back " \\ (?:[[:space:]] \\ | \s \\ ) \\ (?:_ \\ | \\ * \\ ) "
( max ( - ( point ) 2 ) ( point-min ) ) )
( not ( looking-at " [[:space:]] \\ | \s " ) ) ) )
;; Possible beginning of italics
( and
( save-excursion
( when ( and ( re-search-forward ( regexp-quote ( match-string 0 ) ) nil t )
( looking-at " [[:space]] \\ | \s " )
( not ( looking-back " \\ (?:[[:space]] \\ | \s \\ ) \\ (?:_ \\ | \\ * \\ ) "
( max ( - ( point ) 2 ) ( point-min ) ) ) ) )
( backward-delete-char 1 )
( insert " / " ) t ) )
( progn ( backward-delete-char 1 )
( insert " / " ) ) ) ) ) ) )
( buffer-string ) ) )
2023-03-08 00:52:48 -08:00
( defun gptel--playback ( buf content-str start-pt )
" Playback CONTENT-STR in BUF.
2023-03-05 16:59:44 -08:00
2023-03-08 00:52:48 -08:00
Begin at START-PT. "
( let ( ( handle ( gensym " gptel-change-group-handle-- " ) )
( playback-timer ( gensym " gptel--playback- " ) )
( content-length ( length content-str ) )
2023-03-10 22:27:31 -08:00
( idx 0 ) ( pt ( copy-marker start-pt t ) ) )
2023-03-08 00:52:48 -08:00
( setf ( symbol-value handle ) ( prepare-change-group buf ) )
( activate-change-group ( symbol-value handle ) )
( setf ( symbol-value playback-timer )
( run-at-time
0 0.15
( lambda ( )
( with-current-buffer buf
( if ( >= content-length idx )
( progn
( goto-char pt )
2023-03-10 22:27:31 -08:00
( insert
2023-03-18 08:41:25 +01:00
( seq-subseq
2023-03-08 00:52:48 -08:00
content-str idx
( min content-length ( + idx 16 ) ) ) )
( setq idx ( + idx 16 ) ) )
2023-03-10 22:27:31 -08:00
( when gptel-mode
( insert " \n \n " gptel-prompt-string )
( gptel--update-header-line " Ready " 'success ) )
( when start-pt ( goto-char ( marker-position start-pt ) ) )
2023-03-08 00:52:48 -08:00
( accept-change-group ( symbol-value handle ) )
( undo-amalgamate-change-group ( symbol-value handle ) )
( cancel-timer ( symbol-value playback-timer ) ) ) ) ) ) )
nil ) )
2023-03-05 16:59:44 -08:00
( provide 'gptel )
;;; gptel.el ends here