* gptel.el (gptel--convert-playback-markdown->org): New converter for markdown->org that works on text chunks while maintaining the parse state until the text stream is finished. * gptel-curl.el (gptel--insert-response-stream, gptel-curl-get-response): When using `gptel-playback' and requesting ChatGPT's responses in org-mode, run the above converter on the received response. This works by storing the converter and associated state as a closure in the async info plist that is supplied along with the response, and running it repeatedly on each chunk of text in the response stream before it is inserted into the buffer. FIXME: Note that `gptel-response-filter-functions' is currently ignored if using `gptel-stream'.
272 lines
12 KiB
EmacsLisp
272 lines
12 KiB
EmacsLisp
;;; gptel-curl.el --- Curl support for GPTel -*- lexical-binding: t; -*-
|
|
|
|
;; Copyright (C) 2023 Karthik Chikmagalur
|
|
|
|
;; Author: Karthik Chikmagalur;; <karthikchikmagalur@gmail.com>
|
|
;; Keywords: convenience
|
|
|
|
;; SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
;; 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/>.
|
|
|
|
;;; Commentary:
|
|
|
|
;; Curl support for GPTel. Utility functions.
|
|
|
|
;;; Code:
|
|
|
|
(require 'gptel)
|
|
|
|
(eval-when-compile
|
|
(require 'subr-x))
|
|
(require 'map)
|
|
(require 'json)
|
|
|
|
(defvar gptel-curl--process-alist nil
|
|
"Alist of active GPTel curl requests.")
|
|
|
|
(defun gptel-curl--get-args (prompts token)
|
|
"Produce list of arguments for calling Curl.
|
|
|
|
PROMPTS is the data to send, TOKEN is a unique identifier."
|
|
(let* ((args
|
|
(list "--location" "--silent" "--compressed" "--disable"))
|
|
(url "https://api.openai.com/v1/chat/completions")
|
|
(data (encode-coding-string
|
|
(json-encode (gptel--request-data prompts))
|
|
'utf-8))
|
|
(headers
|
|
`(("Content-Type" . "application/json")
|
|
("Authorization" . ,(concat "Bearer " (gptel--api-key))))))
|
|
(push (format "-X%s" "POST") args)
|
|
(push (format "-w(%s . %%{size_header})" token) args)
|
|
;; (push (format "--keepalive-time %s" 240) args)
|
|
(push (format "-m%s" 60) args)
|
|
(push "-D-" args)
|
|
(pcase-dolist (`(,key . ,val) headers)
|
|
(push (format "-H%s: %s" key val) args))
|
|
(push (format "-d%s" data) args)
|
|
(nreverse (cons url args))))
|
|
|
|
;;TODO: The :transformer argument here is an alternate implementation of
|
|
;;`gptel-response-filter-functions'. The two need to be unified.
|
|
;;;###autoload
|
|
(defun gptel-curl-get-response (info &optional callback)
|
|
"Retrieve response to prompt in INFO.
|
|
|
|
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).
|
|
|
|
Call CALLBACK with the response and INFO afterwards. If omitted
|
|
the response is inserted into the current buffer after point."
|
|
(with-current-buffer (generate-new-buffer "*gptel-curl*")
|
|
(let* ((token (md5 (format "%s%s%s%s"
|
|
(random) (emacs-pid) (user-full-name)
|
|
(recent-keys))))
|
|
(args (gptel-curl--get-args (plist-get info :prompt) token))
|
|
(process (apply #'start-process "gptel-curl" (current-buffer)
|
|
"curl" args)))
|
|
(set-process-query-on-exit-flag process nil)
|
|
(setf (alist-get process gptel-curl--process-alist)
|
|
(nconc (list :token token
|
|
:callback (or callback
|
|
(if gptel-playback
|
|
#'gptel--insert-response-stream
|
|
#'gptel--insert-response))
|
|
:transformer (when (or (eq gptel-default-mode 'org-mode)
|
|
(eq (buffer-local-value
|
|
'major-mode
|
|
(plist-get info :gptel-buffer))
|
|
'org-mode))
|
|
(gptel--convert-playback-markdown->org)))
|
|
info))
|
|
(if gptel-playback
|
|
(progn (set-process-sentinel process #'gptel-curl--cleanup-stream)
|
|
(set-process-filter process #'gptel-curl--filter))
|
|
(set-process-sentinel process #'gptel-curl--sentinel)))))
|
|
|
|
(defun gptel-curl--cleanup-stream (process status)
|
|
"Process sentinel for GPTel curl requests.
|
|
|
|
PROCESS and STATUS are process parameters."
|
|
(let ((proc-buf (process-buffer process)))
|
|
(when gptel--debug
|
|
(with-current-buffer proc-buf
|
|
(clone-buffer "*gptel-error*" 'show)))
|
|
(let* ((info (alist-get process gptel-curl--process-alist))
|
|
(gptel-buffer (plist-get info :gptel-buffer))
|
|
(tracking-marker (plist-get info :tracking-marker))
|
|
(start-marker (plist-get info :insert-marker)))
|
|
(when start-marker (goto-char start-marker))
|
|
(pulse-momentary-highlight-region (+ start-marker 2) tracking-marker)
|
|
(when (equal (plist-get info :http-status) "200")
|
|
(with-current-buffer gptel-buffer
|
|
(gptel--update-header-line " Ready" 'success)
|
|
(when gptel-mode
|
|
(save-excursion (goto-char tracking-marker)
|
|
(insert "\n\n" (gptel-prompt-string)))))))
|
|
(setf (alist-get process gptel-curl--process-alist nil 'remove) nil)
|
|
(kill-buffer proc-buf)))
|
|
|
|
(defun gptel--insert-response-stream (response info)
|
|
"Insert streaming RESPONSE from ChatGPT into the gptel buffer.
|
|
|
|
INFO is a mutable 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))
|
|
(start-marker (plist-get info :insert-marker))
|
|
(tracking-marker (plist-get info :tracking-marker))
|
|
(transformer (plist-get info :transformer)))
|
|
(if content-str
|
|
(with-current-buffer gptel-buffer
|
|
(save-excursion
|
|
(unless tracking-marker
|
|
(gptel--update-header-line " Typing..." 'success)
|
|
(goto-char start-marker)
|
|
(insert "\n\n")
|
|
(setq tracking-marker (set-marker (make-marker) (point)))
|
|
(set-marker-insertion-type tracking-marker t)
|
|
(plist-put info :tracking-marker tracking-marker))
|
|
|
|
(when transformer
|
|
(setq content-str (funcall transformer content-str)))
|
|
|
|
(put-text-property 0 (length content-str) 'gptel 'response content-str)
|
|
(goto-char tracking-marker)
|
|
(insert content-str)))
|
|
(gptel--update-header-line
|
|
(format " Response Error: %s" status-str) 'error))))
|
|
|
|
(defun gptel-curl--filter (process output)
|
|
(let* ((content-strs)
|
|
(proc-info (alist-get process gptel-curl--process-alist)))
|
|
(with-current-buffer (process-buffer process)
|
|
;; Insert output
|
|
(save-excursion
|
|
(goto-char (process-mark process))
|
|
(insert output)
|
|
(set-marker (process-mark process) (point)))
|
|
|
|
;; Find HTTP status
|
|
(unless (plist-get proc-info :http-status)
|
|
(save-excursion
|
|
(goto-char (point-min))
|
|
(when-let* (((not (= (line-end-position) (point-max))))
|
|
(http-msg (buffer-substring (line-beginning-position)
|
|
(line-end-position)))
|
|
(http-status
|
|
(save-match-data
|
|
(and (string-match "HTTP/[.0-9]+ +\\([0-9]+\\)" http-msg)
|
|
(match-string 1 http-msg)))))
|
|
(plist-put proc-info :http-status http-status)
|
|
(plist-put proc-info :http-msg http-msg)
|
|
(unless (equal http-status "200")
|
|
(message "%s" (concat (string-trim http-msg) ": Could not parse HTTP response."))))))
|
|
|
|
(when-let ((http-msg (plist-get proc-info :http-msg))
|
|
(http-status (plist-get proc-info :http-status)))
|
|
;; Find data chunk(s) and run callback
|
|
(funcall (or (plist-get proc-info :callback)
|
|
#'gptel--insert-response-stream)
|
|
(if (equal http-status "200")
|
|
(let* ((json-object-type 'plist)
|
|
(response) (content-str))
|
|
(condition-case nil
|
|
(while (re-search-forward "^data:" nil t)
|
|
(save-match-data
|
|
(unless (looking-at " *\\[DONE\\]")
|
|
(when-let* ((response (json-read))
|
|
(delta (map-nested-elt
|
|
response '(:choices 0 :delta)))
|
|
(content (plist-get delta :content)))
|
|
(push content content-strs)))))
|
|
(error
|
|
(goto-char (match-beginning 0))))
|
|
(list :content (apply #'concat (nreverse content-strs)) :status http-msg))
|
|
(list :content nil :status http-msg))
|
|
proc-info)))))
|
|
|
|
(defun gptel-curl--sentinel (process status)
|
|
"Process sentinel for GPTel curl requests.
|
|
|
|
PROCESS and STATUS are process parameters."
|
|
(let ((proc-buf (process-buffer process)))
|
|
(when gptel--debug
|
|
(with-current-buffer proc-buf
|
|
(clone-buffer "*gptel-error*" 'show)))
|
|
(if-let* (((eq (process-status process) 'exit))
|
|
(proc-info (alist-get process gptel-curl--process-alist))
|
|
(proc-token (plist-get proc-info :token))
|
|
(proc-callback (plist-get proc-info :callback))
|
|
(response (gptel-curl--parse-response proc-buf proc-token)))
|
|
(funcall proc-callback response proc-info)
|
|
;; Failed
|
|
(funcall proc-callback (list :content nil :status status) proc-info))
|
|
(setf (alist-get process gptel-curl--process-alist nil 'remove) nil)
|
|
(kill-buffer proc-buf)))
|
|
|
|
(defun gptel-curl--parse-response (buf token)
|
|
"Parse the buffer BUF with curl's response.
|
|
|
|
TOKEN is used to disambiguate multiple requests in a single
|
|
buffer."
|
|
(with-current-buffer buf
|
|
(progn
|
|
(goto-char (point-max))
|
|
(search-backward token)
|
|
(backward-char)
|
|
(pcase-let* ((`(,_ . ,header-size) (read (current-buffer))))
|
|
;; (if (search-backward token nil t)
|
|
;; (search-forward ")" nil t)
|
|
;; (goto-char (point-min)))
|
|
(goto-char (point-min))
|
|
|
|
(if-let* ((http-msg (buffer-substring (line-beginning-position)
|
|
(line-end-position)))
|
|
(http-status
|
|
(save-match-data
|
|
(and (string-match "HTTP/[.0-9]+ +\\([0-9]+\\)" http-msg)
|
|
(match-string 1 http-msg))))
|
|
(json-object-type 'plist)
|
|
(response (progn (goto-char header-size)
|
|
(condition-case nil
|
|
(json-read)
|
|
(json-readtable-error 'json-read-error)))))
|
|
(cond
|
|
((equal http-status "200")
|
|
(list :content
|
|
(string-trim
|
|
(map-nested-elt response '(:choices 0 :message :content)))
|
|
:status http-msg))
|
|
((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 http-msg ": " 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 http-msg ": Could not parse HTTP response."))))
|
|
(message "ChatGPT error: Could not parse HTTP response.")
|
|
(list :content nil
|
|
:status (concat http-msg ": Could not parse HTTP response.")))))))
|
|
|
|
(provide 'gptel-curl)
|
|
;;; gptel-curl.el ends here
|