Skip to content

Commit 452773a

Browse files
committed
feat: Allow openai-key to be retrieved via a function
Enhance the handling of the openai-key variable. If it is a string it will be interpreted as the raw key. If it is a function then that function will be called to retrieve the key. This allows storing the key in some secure store (e.g. auth-source)
1 parent 5784e96 commit 452773a

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

openai-chat.el

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ STREAM, STOP, MAX-TOKENS, PRESENCE-PENALTY, FREQUENCY-PENALTY, and LOGIT-BIAS."
6060
(openai-request "https://api.openai.com/v1/chat/completions"
6161
:type "POST"
6262
:headers `(("Content-Type" . "application/json")
63-
("Authorization" . ,(concat "Bearer " key)))
63+
("Authorization" . ,(concat "Bearer " (openai--resolve-key key))))
6464
:data (openai--json-encode
6565
`(("model" . ,model)
6666
("messages" . ,messages)
@@ -92,6 +92,11 @@ STREAM, STOP, MAX-TOKENS, PRESENCE-PENALTY, FREQUENCY-PENALTY, and LOGIT-BIAS."
9292
:type 'number
9393
:group 'openai)
9494

95+
(defun openai--resolve-key (key)
96+
(if (functionp key)
97+
(funcall key)
98+
key))
99+
95100
;;;###autoload
96101
(defun openai-chat-say ()
97102
"Start making a conversation to OpenAI.

openai.el

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,36 @@
5757
(when openai--show-log
5858
(apply 'message fmt args)))
5959

60+
(defun openai-key--auth-source ()
61+
"Retrieve the OpenAI API key from auth-source."
62+
(let ((auth-info (auth-source-search :max 1
63+
:host "api.openai.com"
64+
:require '(:user :secret))))
65+
(if auth-info
66+
(funcall (plist-get (car auth-info) :secret))
67+
(error "OpenAI API key not found in auth-source"))))
68+
6069
;;
6170
;;; Request
6271

63-
(defvar openai-key ""
64-
"Generated API key.")
72+
73+
(defcustom openai-key ""
74+
"Variable storing the openai key or a function to retrieve it.
75+
76+
The function should take no arguments and return a string containing the key.
77+
78+
A function, `openai-key--auth-source', that retrieves the key from auth-source is provided for convenience.
79+
"
80+
:type '(choice string function)
81+
:set (lambda (option value)
82+
(cond ((stringp value)
83+
(set-default option value))
84+
((functionp value)
85+
(set-default option (symbol-name value)))
86+
(t
87+
(error "Invalid value for %s" option))))
88+
:group 'openai)
89+
6590

6691
(defvar openai-user ""
6792
"A unique identifier representing your end-user, which can help OpenAI to

0 commit comments

Comments
 (0)