forked from joshcho/ChatGPT.el
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatgpt.el
423 lines (362 loc) · 16.6 KB
/
chatgpt.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
;;; chatgpt.el --- ChatGPT in Emacs
;; Copyright (C) 2011 Free Software Foundation, Inc.
;; Author: Jungmin "Josh" Cho <[email protected]>
;; Version: 0.1
;; Package-Requires: ((epc "0.1.1") (deferred "0.5.1"))
;; Keywords: ai
;; URL: https://github.com/joshcho/ChatGPT.el
;;; Commentary:
;; This package provides an interactive interface with ChatGPT API.
(require 'epc)
(require 'deferred)
(require 'python)
;;; Code:
(defgroup chatgpt nil
"Configuration for chatgpt."
:prefix "chatgpt-"
:group 'ai)
(defcustom chatgpt-query-format-string-map
'(("doc" . "Please write the documentation for the following function.\n\n%s")
("bug" . "There is a bug in the following function, please help me fix it.\n\n%s")
("understand" . "What is the following?\n\n%s")
("improve" . "Please improve the following.\n\n%s"))
"An association list that maps query types to their corresponding format strings."
:type '(alist :key-type (string :tag "Query Type")
:value-type (string :tag "Format String"))
:group 'chatgpt)
(defcustom chatgpt-enable-loading-ellipsis t
"Whether the ellipsis animation is displayed in *ChatGPT*."
:type 'boolean
:group 'chatgpt)
(defcustom chatgpt-display-on-query t
"Whether *ChatGPT* is displayed when a query is sent."
:type 'boolean
:group 'chatgpt)
(defcustom chatgpt-display-on-response t
"Whether *ChatGPT* is displayed when a response is received."
:type 'boolean
:group 'chatgpt)
(defcustom chatgpt-repo-path nil
"The path of ChatGPT.el repository."
:type 'string
:group 'chatgpt)
(defvar chatgpt-process nil
"The ChatGPT process.")
(defvar chatgpt-buffer-name "*ChatGPT*")
(defcustom chatgpt-record-path nil
"The path of ChatGPT.el conversation path "
:type 'string
:group 'chatgpt)
;;;###autoload
(defun chatgpt-login ()
"Log in to ChatGPT."
(interactive)
(shell-command "chatgpt install &"))
(defun chatgpt-converstaion-log-path ()
(let* ((monthly-folder-name (format "%s/%s" chatgpt-record-path (format-time-string "%Y-%m" (time-subtract (current-time) (seconds-to-time (* 3 60 60)))))))
(unless (file-directory-p monthly-folder-name)
(make-directory monthly-folder-name t))
(format "%s/chatgpt_record_%s.txt" monthly-folder-name (chatgpt-get-current-date-string))))
(defun chatgpt-get-filename-buffer ()
(or (and chatgpt-record-path (find-file-noselect (chatgpt-converstaion-log-path)))
(get-buffer-create chatgpt-buffer-name)))
(defun chatgpt-get-output-buffer-name ()
(or (and chatgpt-record-path (buffer-name (find-file-noselect (chatgpt-converstaion-log-path))))
chatgpt-buffer-name))
(defvar chatgpt-finish-response-notify-hook nil)
;;;###autoload
(defun chatgpt-init ()
"Initialize the ChatGPT server.
This function creates the ChatGPT process and starts it. It also
initializes the ChatGPT buffer, enabling visual line mode in it. A
message is displayed to indicate that the initialization was
successful.
If ChatGPT server is not initialized, 'chatgpt-query' calls this
function."
(interactive)
(when (equal (shell-command-to-string "pip list | grep chatGPT") "")
(shell-command "pip install git+https://github.com/mmabrouk/chatgpt-wrapper")
(message "chatgpt-wrapper installed through pip.")
(chatgpt-login))
(when (null chatgpt-repo-path)
(error "chatgpt-repo-path is nil. Please set chatgpt-repo-path as specified in joshcho/ChatGPT.el"))
(setq chatgpt-process (epc:start-epc python-interpreter (list (expand-file-name
(format "%schatgpt.py"
chatgpt-repo-path)))))
;; (with-current-buffer (chatgpt-get-filename-buffer)
;; (visual-line-mode 1))
(message "ChatGPT initialized.")
(if chatgpt-exist-chats
(chatgpt-select-exist-chat (lambda (select-chat)
(message "select-chat is:%s" select-chat)
(deferred:$
(epc:call-deferred chatgpt-process 'switch_to_chat (list select-chat))
(eval `(deferred:nextc it
(lambda (response)))))))))
(defvar chatgpt-wait-timers (make-hash-table)
"Timers to update the waiting message in the ChatGPT buffer.")
(defvar chatgpt-exist-chats nil)
(defun chatgpt-select-exist-chat (callback)
"choose an exist chat."
(let ((options chatgpt-exist-chats))
(ivy-read "Select a exist chat: " options
:action (lambda (x)
(let ((chosen-option (cdr x)))
(funcall callback chosen-option)))
:caller 'chatgpt-select-exist-chat)))
(defun chatgpt-get-current-date-string ()
"Return the current date string in the format year_month_weekofyear_day."
(format-time-string "%Y-%m-%d" (time-subtract (current-time) (seconds-to-time (* 3 60 60)))))
(defun chatgpt-write-string-to-file (filename string)
"Write STRING to FILENAME, creating the file if it doesn't exist, and appending to it if it does."
(with-temp-buffer
(insert string)
(when (file-exists-p filename)
(append-to-file (point-min) (point-max) filename))
(unless (file-exists-p filename)
(write-region (point-min) (point-max) filename))))
;;;###autoload
(defun chatgpt-stop ()
"Stops the ChatGPT server."
(interactive)
(dolist (id (hash-table-keys chatgpt-wait-timers))
(chatgpt--stop-wait id))
(epc:stop-epc chatgpt-process)
(setq chatgpt-process nil)
(message "Stop ChatGPT process."))
;;;###autoload
(defun chatgpt-reset ()
"Reset the ChatGPT server. The same session is maintained."
(interactive)
(chatgpt-stop)
(chatgpt-init))
(defun chatgpt-files-same-p (file1 file2)
"Return non-nil if FILE1 and FILE2 point to the same file."
(string= (file-truename file1)
(file-truename file2)))
(defun chatgpt-recenter-buffer (buffer-name)
"The function first attempts to obtain the buffer object associated with the given buffer name. If the buffer exists, the function switches to the buffer and moves the cursor to the end of the buffer using goto-char (point-max). The function then searches backwards in the buffer for two strings of equal signs, each of length 66. This is done to locate a marker in the buffer that indicates the start of the content that the user wants to see. Finally, the function re-centers the buffer so that the content starts at the top of the window."
(let ((my-buffer (get-buffer buffer-name)))
(when my-buffer
(switch-to-buffer my-buffer)
(goto-char (point-max))
(search-backward (make-string 66 ?=))
(search-backward (make-string 66 ?=))
(let* ((window-height (window-height))
(one-third-height (/ window-height 3)))
(recenter one-third-height))
(beginning-of-line))))
;;;###autoload
(defun chatgpt-display ()
"Displays *ChatGPT*."
(interactive)
(let ((output-buffer-name chatgpt-buffer-name))
(if (get-buffer output-buffer-name)
(progn
(if (not (chatgpt-files-same-p (buffer-file-name (buffer-base-buffer (get-buffer output-buffer-name))) (chatgpt-converstaion-log-path)))
(progn
(kill-buffer (get-buffer output-buffer-name))
(with-current-buffer (chatgpt-get-filename-buffer)
(let ((new-buffer (clone-indirect-buffer output-buffer-name nil)))
(switch-to-buffer new-buffer))))
(switch-to-buffer (chatgpt-get-filename-buffer))))
(progn
(with-current-buffer (chatgpt-get-filename-buffer)
(let ((new-buffer (clone-indirect-buffer output-buffer-name nil)))
(switch-to-buffer new-buffer)))))
(with-current-buffer (get-buffer output-buffer-name)
(setq-local buffer-read-only t))
(chatgpt-recenter-buffer output-buffer-name)
;; (goto-char (point-max))
;; (recenter-top-bottom 1)
(when-let ((saved-win (get-buffer-window (current-buffer)))
(win (get-buffer-window (chatgpt-get-output-buffer-name))))
(unless (equal (current-buffer) (get-buffer (chatgpt-get-output-buffer-name)))
(select-window win)
(goto-char (point-max))
(unless (pos-visible-in-window-p (point-max) win)
(goto-char (point-max))
(recenter -1))
(select-window saved-win)))
))
(defun chatgpt--clear-line ()
"Clear line in *ChatGPT*."
(cl-assert (equal (current-buffer) (get-buffer (chatgpt-get-output-buffer-name))))
(delete-region (save-excursion (beginning-of-line)
(point))
(save-excursion (end-of-line)
(point))))
(defun chatgpt--identifier-string (id)
"Identifier string corresponding to ID."
(format "cg?[%s]" id))
(defun chatgpt--regex-string (id)
"Regex corresponding to ID."
(format "cg\\?\\[%s\\]" id))
(defun chatgpt--goto-identifier (id)
"Go to response of ID."
(cl-assert (equal (current-buffer) (get-buffer (chatgpt-get-output-buffer-name))))
(goto-char (point-max))
(re-search-backward (chatgpt--regex-string id))
(forward-line))
(defun chatgpt--insert-query (query id)
"Insert QUERY with ID into *ChatGPT*."
(with-current-buffer (chatgpt-get-filename-buffer)
(save-excursion
(goto-char (point-max))
(auto-highlight-symbol-mode -1)
(with-silent-modifications
(insert (format "\n%s\n%s >>> %s\n%s\n%s\n%s"
(make-string 66 ?=)
(if (= (point-min) (point))
""
"\n")
(propertize query 'face 'bold)
(make-string 66 ?=)
(propertize
(chatgpt--identifier-string id)
'invisible t)
(if chatgpt-enable-loading-ellipsis
""
(concat "Waiting for ChatGPT..."))))))
(end-of-buffer)))
(defun chatgpt--insert-response (response id)
"Insert RESPONSE into *ChatGPT* for ID."
(with-current-buffer (chatgpt-get-filename-buffer)
(save-excursion
(chatgpt--goto-identifier id)
(chatgpt--clear-line)
(insert response))))
(defun chatgpt--insert-error (error-msg id)
"Insert ERROR-MSG into *ChatGPT* for ID."
(with-current-buffer (chatgpt-get-filename-buffer)
(save-excursion
(chatgpt--goto-identifier id)
(chatgpt--clear-line)
(insert (format "ERROR: %s" error-msg)))))
(defun chatgpt--add-timer (id)
"Add timer for ID to 'chatgpt-wait-timers'."
(cl-assert (null (gethash id chatgpt-wait-timers)))
(puthash id
(run-with-timer 0.5 0.5
(eval
`(lambda ()
(with-current-buffer (get-buffer chatgpt-buffer-name)
(save-excursion
(chatgpt--goto-identifier ,id)
(let ((line (thing-at-point 'line)))
(when (>= (+ (length line)
(if (eq (substring line -1) "\n")
0
1))
4)
(chatgpt--clear-line))
(insert ".")))))))
chatgpt-wait-timers))
(defun chatgpt--stop-wait (id)
"Stop waiting for a response from ID."
(when-let (timer (gethash id chatgpt-wait-timers))
(cancel-timer timer)
(remhash id chatgpt-wait-timers)))
(defvar chatgpt-id 0
"Tracks responses in the background.")
(defun chatgpt--query (query)
"Send QUERY to the ChatGPT process.
The query is inserted into the *ChatGPT* buffer with bold text,
and the response from the ChatGPT process is appended to the
buffer. If `chatgpt-enable-loading-ellipsis' is non-nil, a loading
ellipsis is displayed in the buffer while waiting for the
response.
This function is intended to be called internally by the
`chatgpt-query' function, and should not be called directly by
users."
(unless chatgpt-process
(chatgpt-init))
(let ((saved-id (cl-incf chatgpt-id)))
(chatgpt--insert-query query saved-id)
(when chatgpt-enable-loading-ellipsis
(chatgpt--add-timer saved-id))
(when chatgpt-display-on-query
(chatgpt-display))
(deferred:$
(deferred:$
(epc:call-deferred chatgpt-process 'query (list query))
(eval `(deferred:nextc it
(lambda (response)
(chatgpt--stop-wait ,saved-id)
(chatgpt--insert-response response ,saved-id)
(when chatgpt-display-on-response
(chatgpt-display)
(and chatgpt-finish-response-notify-hook (run-hooks 'chatgpt-finish-response-notify-hook)))))))
(eval
`(deferred:error it
(lambda (err)
(chatgpt--stop-wait ,saved-id)
(string-match "\"Error('\\(.*\\)')\"" (error-message-string err))
(let ((error-str (match-string 1 (error-message-string err))))
(chatgpt--insert-error error-str
,saved-id)
(when (yes-or-no-p (format "Error encountered. Reset chatgpt (If reset doesn't work, try \"\"pkill ms-playwright/firefox\"\" in the shell then reset)?" error-str))
(chatgpt-reset)))))))))
(defun chatgpt--query-by-type (query query-type)
"Query ChatGPT with a given QUERY and QUERY-TYPE.
QUERY is the text to be passed to ChatGPT.
QUERY-TYPE is the type of query, which determines the format string
used to generate the final query sent to ChatGPT. The format string
is looked up in 'chatgpt-query-format-string-map', which is an
alist of QUERY-TYPE and format string pairs. If no matching
format string is found, an error is raised.
The format string is expected to contain a %s placeholder, which
will be replaced with QUERY. The resulting string is then passed
to ChatGPT.
For example, if QUERY is \"(defun square (x) (* x x))\" and
QUERY-TYPE is \"doc\", the final query sent to ChatGPT would be
\"Please write the documentation for the following function.
\(defun square (x) (* x x))\""
(if (equal query-type "custom")
(chatgpt--query
(format "%s\n\n%s" (read-from-minibuffer "ChatGPT Custom Prompt: ") query))
(if-let (format-string (cdr (assoc query-type chatgpt-query-format-string-map)))
(chatgpt--query
(format format-string query))
(error "No format string associated with 'query-type' %s. Please customize 'chatgpt-query-format-string-map'" query-type))))
;;;###autoload
(defun chatgpt-query-by-type (query)
"Query ChatGPT with from QUERY and interactively chosen 'query-type'.
The function uses the 'completing-read' function to prompt the
user to select the type of query to use. The selected query type
is passed to the 'chatgpt--query-by-type' function along with the
'query' argument, which sends the query to the ChatGPT model and
returns the response."
(interactive (list (if (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(read-from-minibuffer "ChatGPT Query: "))))
(let* ((query-type (completing-read "Type of Query: " (cons "custom" (mapcar #'car chatgpt-query-format-string-map)))))
(if (or (assoc query-type chatgpt-query-format-string-map)
(equal query-type "custom"))
(chatgpt--query-by-type query query-type)
(chatgpt--query (format "%s\n\n%s" query-type query)))))
;;;###autoload
(defun chatgpt-query (query)
"Query ChatGPT with QUERY.
The user will be prompted to enter a query if none is provided. If
there is an active region, the user will be prompted to select the
type of query to perform.
Supported query types are:
* doc: Ask for documentation in query
* bug: Find bug in query
* improve: Suggestions for improving code
* understand: Query for understanding code or behavior"
(interactive (list (if (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(read-from-minibuffer "ChatGPT Query: "))))
;; (if chatgpt-waiting-dot-timer
;; (message "Already waiting on a ChatGPT query. If there was an error with your previous query, try M-x chatgpt-reset")
;; (if (region-active-p)
;; (chatgpt-query-by-type query)
;; (chatgpt--query query)))
(if (region-active-p)
(chatgpt-query-by-type query)
(chatgpt--query query)))
(require 'chatgpt_stream)
(provide 'chatgpt)
;;; chatgpt.el ends here