gptel: Add introspection commands

* gptel.el (gptel--inspect-query): Add a function to inspect the
query that will be sent.  This is useful to ensure that (only and
all of) what you expect to be sent is being sent.

* gptel-transient.el (gptel-menu): Allow the query in progress to
be inspected from `gptel-menu` as an elisp or JSON object.
This commit is contained in:
Karthik Chikmagalur 2024-03-13 21:58:24 -07:00
parent 260be9d8d4
commit dade9ec8e1
2 changed files with 39 additions and 1 deletions

View file

@ -174,7 +174,20 @@ which see."
:if gptel--at-response-history-p
:transient t)
("E" "Ediff previous" gptel--ediff
:if gptel--at-response-history-p)]]
:if gptel--at-response-history-p)]
["Inspect"
("I" "Query as Lisp"
(lambda ()
"Inspect the query that will be sent as a lisp object."
(interactive)
(gptel--sanitize-model)
(gptel--inspect-query)))
("J" "Query as JSON"
(lambda ()
"Inspect the query that will be sent as a JSON object."
(interactive)
(gptel--sanitize-model)
(gptel--inspect-query 'json)))]]
(interactive)
(gptel--sanitize-model)
(transient-setup 'gptel-menu))

View file

@ -955,6 +955,31 @@ waiting for the response."
(gptel-request nil :stream gptel-stream)
(gptel--update-status " Waiting..." 'warning)))
(declare-function json-pretty-print-buffer "json")
(defun gptel--inspect-query (&optional arg)
"Show the full LLM query to be sent in a new buffer.
This functions as a dry run of `gptel-send'. If prefix ARG is
the symbol json, show the encoded JSON query instead of the lisp
structure gptel uses."
(let* ((request-data
(gptel-request nil :stream gptel-stream :dry-run t)))
(with-current-buffer (get-buffer-create "*gptel-query*")
(let ((standard-output (current-buffer))
(inhibit-read-only t))
(buffer-disable-undo)
(erase-buffer)
(if (eq arg 'json)
(progn (fundamental-mode)
(insert (gptel--json-encode request-data))
(json-pretty-print-buffer))
(lisp-data-mode)
(prin1 request-data)
(pp-buffer))
(goto-char (point-min))
(view-mode 1)
(display-buffer (current-buffer) gptel-display-buffer-action)))))
(defun gptel--insert-response (response info)
"Insert the LLM RESPONSE into the gptel buffer.