From 28ac88cada410a0f261a42fdbc3d8d34e6a39fa8 Mon Sep 17 00:00:00 2001 From: Karthik Chikmagalur Date: Sun, 3 Mar 2024 20:28:21 -0800 Subject: [PATCH] gptel-org: Read config from Org properties (#141) * gptel.el: Load gptel-org after Org is loaded. * gptel-org.el (gptel-org--send-with-props): Advise `gptel-send` and `gptel--suffix-send` to use gptel's local config (stored under the current Org heading) when applicable. Advice is a hacky way to do it, but this is the simplest option without explicit indirection via `derived-mode-p`-based dispatch code in many more places in gptel. --- gptel-org.el | 25 +++++++++++++++++++++++++ gptel.el | 3 +++ 2 files changed, 28 insertions(+) diff --git a/gptel-org.el b/gptel-org.el index aca0433..ce8fef5 100644 --- a/gptel-org.el +++ b/gptel-org.el @@ -174,6 +174,31 @@ value of `gptel-org-branching-context', which see." ;; Create prompt the usual way (gptel--parse-buffer gptel-backend max-entries)))) +(defun gptel-org--send-with-props (send-fun &rest args) + "Conditionally modify SEND-FUN's calling environment. + +If in an Org buffer under a heading containing a stored gptel +configuration, use that for requests instead. This includes the +system message, model and provider (backend), among other +parameters." + (if (derived-mode-p 'org-mode) + (pcase-let ((`(,gptel--system-message ,gptel-backend ,gptel-model + ,gptel-temperature ,gptel-max-tokens) + (seq-mapn (lambda (a b) (or a b)) + (gptel-org--entry-properties) + (list gptel--system-message gptel-backend gptel-model + gptel-temperature gptel-max-tokens)))) + (apply send-fun args)) + (apply send-fun args))) + +(advice-add 'gptel-send :around #'gptel-org--send-with-props) +(advice-add 'gptel--suffix-send :around #'gptel-org--send-with-props) + +;; ;; NOTE: Basic uses in org-mode are covered by advising gptel-send and +;; ;; gptel--suffix-send. For custom commands it might be necessary to advise +;; ;; gptel-request instead. +;; (advice-add 'gptel-request :around #'gptel-org--send-with-props) + ;;; Saving and restoring state (defun gptel-org--entry-properties (&optional pt) diff --git a/gptel.el b/gptel.el index 6b721ac..160601d 100644 --- a/gptel.el +++ b/gptel.el @@ -133,6 +133,9 @@ (require 'cl-generic) (require 'gptel-openai) +(with-eval-after-load 'org + (require 'gptel-org)) + ;; User options