-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathchatgpt-shell-openai.el
324 lines (280 loc) · 12.3 KB
/
chatgpt-shell-openai.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
;;; chatgpt-shell-openai.el --- OpenAI-specific logic -*- lexical-binding: t -*-
;; Copyright (C) 2023 Alvaro Ramirez
;; Author: Alvaro Ramirez https://xenodium.com
;; URL: https://github.com/xenodium/chatgpt-shell
;; Package-Requires: ((emacs "28.1") (shell-maker "0.72.1"))
;; This package 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, or (at your option)
;; any later version.
;; This package 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 GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Adds OpenAI specifics for `chatgpt-shell'.
;;; Code:
(eval-when-compile
(require 'cl-lib))
(require 'map)
(require 'shell-maker)
(declare-function chatgpt-shell-crop-context "chatgpt-shell")
(declare-function chatgpt-shell--make-chatgpt-url "chatgpt-shell")
(declare-function chatgpt-shell-validate-no-system-prompt "chatgpt-shell")
(cl-defun chatgpt-shell-openai-make-model (&key version short-version token-width context-window validate-command (headers #'chatgpt-shell-openai--make-headers) (key chatgpt-shell-openai-key) (url-base 'chatgpt-shell-api-url-base) (path "/v1/chat/completions") (provider "OpenAI") (label "ChatGPT") (handler #'chatgpt-shell-openai--handle-chatgpt-command) (filter #'chatgpt-shell-openai--filter-output) other-params)
"Create an OpenAI model.
Set VERSION, SHORT-VERSION, TOKEN-WIDTH, CONTEXT-WINDOW,
VALIDATE-COMMAND, HEADERS, KEY, URL-BASE, PATH, PROVIDER, LABEL,
HANDLER, FILTER and OTHER-PARAMS."
(unless version
(error "Missing mandatory :version param"))
(unless token-width
(error "Missing mandatory :token-width param for %s" version))
(unless context-window
(error "Missing mandatory :context-window param for %s" version))
(unless (integerp token-width)
(error ":token-width must be an integer"))
(unless (integerp context-window)
(error ":context-window must be an integer"))
`((:version . ,version)
(:short-version . ,short-version)
(:label . ,label)
(:provider . ,provider)
(:path . ,path)
(:token-width . ,token-width)
(:context-window . ,context-window)
(:handler . ,handler)
(:filter . ,filter)
(:payload . chatgpt-shell-openai--make-payload)
(:headers . ,headers)
(:url . chatgpt-shell-openai--make-url)
(:key . ,key)
(:url-base . ,url-base)
(:validate-command . ,(or validate-command 'chatgpt-shell-openai--validate-command))
(:other-params . ,other-params)))
(defun chatgpt-shell-openai-models ()
"Build a list of all OpenAI LLM models available."
;; Context windows have been verified as of 11/26/2024.
(list (chatgpt-shell-openai-make-model
:version "chatgpt-4o-latest"
:token-width 3
;; https://platform.openai.com/docs/models/gpt-4o
:context-window 128000)
(chatgpt-shell-openai-make-model
:version "o1-preview"
:token-width 3
;; https://platform.openai.com/docs/models/gpt-01
:context-window 128000
:validate-command #'chatgpt-shell-validate-no-system-prompt)
(chatgpt-shell-openai-make-model
:version "o1-mini"
:token-width 3
;; https://platform.openai.com/docs/models/gpt-01-mini
:context-window 128000
:validate-command
;; TODO: Standardize whether or not a model supports system prompts.
(lambda (command model settings)
(or (chatgpt-shell-openai--validate-command command model settings)
(when (map-elt settings :system-prompt)
(format "Model \"%s\" does not support system prompts. Please unset via \"M-x chatgpt-shell-swap-system-prompt\" by selecting None."
(map-elt model :version))))))
(chatgpt-shell-openai-make-model
:version "gpt-4o"
:token-width 3
;; https://platform.openai.com/docs/models/gpt-40
:context-window 128000)
(chatgpt-shell-openai-make-model
:version "gpt-3.5-turbo"
:token-width 4
;; https://platform.openai.com/docs/models/gpt-3.5-turbo#gpt-3-5-turbo
:context-window 16385)))
(defcustom chatgpt-shell-api-url-base "https://api.openai.com"
"OpenAI API's base URL.
API url = base + path.
If you use ChatGPT through a proxy service, change the URL base."
:type 'string
:safe #'stringp
:group 'chatgpt-shell)
(defcustom chatgpt-shell-openai-key nil
"OpenAI key as a string or a function that loads and returns it."
:type '(choice (function :tag "Function")
(string :tag "String"))
:group 'chatgpt-shell)
(cl-defun chatgpt-shell-openai--make-chatgpt-messages (&key model system-prompt prompt prompt-url context)
"Create ChatGPT messages using MODEL.
SYSTEM-PROMPT: string.
PROMPT: string.
PROMPT-URL: string.
CONTEXT: Excludes PROMPT."
(when prompt-url
(setq prompt-url (chatgpt-shell--make-chatgpt-url prompt-url)))
(vconcat
(when system-prompt
`(((role . "system")
(content . ,system-prompt))))
(when context
(chatgpt-shell-openai--user-assistant-messages
(if model
(chatgpt-shell-crop-context
:model model
:command prompt
:context context)
context)))
(when (or prompt
prompt-url)
`(((role . "user")
(content . ,(vconcat
(append
(when prompt
`(((type . "text")
(text . ,prompt))))
(when prompt-url
`(((type . "image_url")
(image_url . ,prompt-url))))))))))))
(defun chatgpt-shell-openai-key ()
"Get the ChatGPT key."
(cond ((stringp chatgpt-shell-openai-key)
chatgpt-shell-openai-key)
((functionp chatgpt-shell-openai-key)
(condition-case _err
(funcall chatgpt-shell-openai-key)
(error
"KEY-NOT-FOUND")))
(t
nil)))
(cl-defun chatgpt-shell-openai-make-chatgpt-request-data (&key system-prompt prompt prompt-url context version temperature streaming other-params)
"Make request data with MESSAGES.
Optionally set PROMPT, VERSION, TEMPERATURE, STREAMING, SYSTEM-PROMPT,
and OTHER-PARAMS (list)."
(unless version
(error "Missing mandatory :version param"))
(append
`((model . ,version)
(messages . ,(vconcat (chatgpt-shell-openai--make-chatgpt-messages
:system-prompt system-prompt
:prompt prompt
:prompt-url prompt-url
:context context))))
(when temperature
`((temperature . ,temperature)))
(when streaming
`((stream . t)))
other-params))
(defun chatgpt-shell-openai--filter-output (raw-response)
"Extract ChatGPT response from RAW-RESPONSE.
When ChatGPT responses are streamed, they arrive in the form:
data: {...json...}
data: {...jdon...}
Otherwise:
{...json...}."
(if-let* ((whole (shell-maker--json-parse-string raw-response))
(response (or (let-alist whole
.error.message)
(let-alist whole
(mapconcat (lambda (choice)
(let-alist choice
(or .delta.content
.message.content)))
.choices "")))))
response
(when-let ((chunks (shell-maker--split-text raw-response)))
(let ((response)
(pending)
(result))
(mapc (lambda (chunk)
;; Response chunks come in the form:
;; data: {...}
;; data: {...}
(if-let* ((is-data (equal (map-elt chunk :key) "data:"))
(obj (shell-maker--json-parse-string (map-elt chunk :value)))
(text (or
;; .choices[i].message.content
;; .choices[i].delta.content
(let-alist obj
(mapconcat (lambda (choice)
(let-alist choice
(or .delta.content
.message.content)))
.choices "")))))
(unless (string-empty-p text)
(setq response (concat response text)))
(setq pending (concat pending
(or (map-elt chunk :key) "")
(map-elt chunk :value)))))
chunks)
(setq result
(list (cons :filtered (unless (string-empty-p response)
response))
(cons :pending pending)))
result))))
(cl-defun chatgpt-shell-openai--make-url (&key _command model _settings)
"Create the API URL using MODEL."
(concat (symbol-value (or (map-elt model :url-base)
(error "Model :url-base not found")))
(or (map-elt model :path)
(error "Model :path not found"))))
(cl-defun chatgpt-shell-openai--make-headers (&key _model _settings (key #'chatgpt-shell-openai-key))
"Create the API headers using KEY as the API KEY."
(list "Content-Type: application/json; charset=utf-8"
(format "Authorization: Bearer %s" (funcall key))))
(defun chatgpt-shell-openai--validate-command (_command _model _settings)
"Return error string if command/setup isn't valid."
(unless chatgpt-shell-openai-key
"Variable `chatgpt-shell-openai-key' needs to be set to your key.
Try M-x set-variable chatgpt-shell-openai-key
or
(setq chatgpt-shell-openai-key \"my-key\")"))
(cl-defun chatgpt-shell-openai--make-payload (&key model context settings)
"Create the API payload using MODEL CONTEXT and SETTINGS."
(funcall
#'chatgpt-shell-openai-make-chatgpt-request-data
:system-prompt (map-elt settings :system-prompt)
:context context
:version (map-elt model :version)
:temperature (map-elt settings :temperature)
:streaming (map-elt settings :streaming)
:other-params (map-elt model :other-params)))
(cl-defun chatgpt-shell-openai--handle-chatgpt-command (&key model command context shell settings (key #'chatgpt-shell-openai-key) (filter #'chatgpt-shell-openai--filter-output) (missing-key-msg "Your chatgpt-shell-openai-key is missing"))
"Handle ChatGPT COMMAND (prompt) using MODEL, CONTEXT, SHELL, and SETTINGS."
(unless (funcall key)
(funcall (map-elt shell :write-output) missing-key-msg)
(funcall (map-elt shell :finish-output) nil))
(shell-maker-make-http-request
:async t
:url (chatgpt-shell-openai--make-url :model model)
:proxy chatgpt-shell-proxy
:data (chatgpt-shell-openai-make-chatgpt-request-data
:prompt command
:system-prompt (map-elt settings :system-prompt)
:context context
:version (map-elt model :version)
:temperature (map-elt settings :temperature)
:streaming (map-elt settings :streaming)
:other-params (map-elt model :other-params))
:headers (list "Content-Type: application/json; charset=utf-8"
(format "Authorization: Bearer %s" (funcall key)))
:filter filter
:shell shell))
(defun chatgpt-shell-openai--user-assistant-messages (history)
"Convert HISTORY to ChatGPT format.
Sequence must be a vector for json serialization.
For example:
[
((role . \"user\") (content . \"hello\"))
((role . \"assistant\") (content . \"world\"))
]"
(let ((result))
(mapc
(lambda (item)
(when (car item)
(push (list (cons 'role "user")
(cons 'content (car item))) result))
(when (cdr item)
(push (list (cons 'role "assistant")
(cons 'content (cdr item))) result)))
history)
(nreverse result)))
(provide 'chatgpt-shell-openai)
;;; chatgpt-shell-openai.el ends here