From 20af9a8b99c57bc22b8af1e0baa8784b0b521813 Mon Sep 17 00:00:00 2001 From: Palace Date: Mon, 5 Jun 2023 23:17:55 -0500 Subject: [PATCH] gptel: curl proxy support (#69) * gptel.el (gptel-proxy): Support a proxy when interacting with openai endpoint. In many organizations the openai api can only be accessed via proxy. This is easily supported by curl. gptel-curl.el (gptel-curl--get-args): tidy up `gptel-curl--get-args'. --------- Co-authored-by: PalaceChan --- gptel-curl.el | 28 ++++++++++++++++------------ gptel.el | 7 +++++++ 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/gptel-curl.el b/gptel-curl.el index 1eb927c..0d6733f 100644 --- a/gptel-curl.el +++ b/gptel-curl.el @@ -29,6 +29,7 @@ (require 'gptel) (eval-when-compile + (require 'cl-lib) (require 'subr-x)) (require 'map) (require 'json) @@ -40,24 +41,27 @@ "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 (format "https://%s/v1/chat/completions" gptel-host)) + (let* ((url (format "https://%s/v1/chat/completions" gptel-host)) (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)))) + (append + (list "--location" "--silent" "--compressed" "--disable" + (format "-X%s" "POST") + (format "-w(%s . %%{size_header})" token) + (format "-m%s" 60) + "-D-" + (format "-d%s" data)) + (when (not (string-empty-p gptel-proxy)) + (list "--proxy" gptel-proxy + "--proxy-negotiate" + "--proxy-user" ":")) + (cl-loop for (key . val) in headers + collect (format "-H%s: %s" key val)) + (list url)))) ;;TODO: The :transformer argument here is an alternate implementation of ;;`gptel-response-filter-functions'. The two need to be unified. diff --git a/gptel.el b/gptel.el index 862eb14..f0807f9 100644 --- a/gptel.el +++ b/gptel.el @@ -74,6 +74,13 @@ :group 'gptel :type 'string) +(defcustom gptel-proxy "" + "Path to a proxy to use for gptel interactions. +Passed to curl via --proxy arg, for example \"proxy.yourorg.com:80\" +Leave it empty if you don't use a proxy." + :group 'gptel + :type 'string) + (defcustom gptel-api-key #'gptel-api-key-from-auth-source "An OpenAI API key (string).