forked from joshcho/ChatGPT.el
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatgpt_stream.el
74 lines (68 loc) · 3.55 KB
/
chatgpt_stream.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
;;; --- Buffer for first time use code -*- lexical-binding: t; -*-
(defun chatgpt--query-stream (query &optional recursive)
(unless chatgpt-process
(chatgpt-init))
(let ((next-query query)
(saved-id (if recursive
chatgpt-id
(cl-incf chatgpt-id)))
(next-recursive recursive))
(if (not recursive)
(progn
(chatgpt--insert-query query saved-id)
(chatgpt-display)))
(deferred:$
(deferred:$
(epc:call-deferred chatgpt-process 'querystream (list query))
(deferred:nextc it
#'(lambda (response)
(with-current-buffer (chatgpt-get-filename-buffer)
(save-excursion
(if (numberp next-recursive)
(goto-char next-recursive)
(progn
(chatgpt--goto-identifier chatgpt-id)
(chatgpt--clear-line)))
(if (and (stringp response))
(progn
(with-silent-modifications
(insert response))
(chatgpt--query-stream next-query (point)))
(progn
(with-silent-modifications
(insert (format "\n\n%s END %s"
(make-string 30 ?=)
(make-string 30 ?=))))
(if (buffer-file-name)
(save-buffer))))))
(if (not (stringp response))
(if (not (string-equal (buffer-name) chatgpt-buffer-name))
(and chatgpt-finish-response-notify-hook (run-hooks 'chatgpt-finish-response-notify-hook)))))))
(deferred:error it
`(lambda (err)
(message "err is:%s" err))))))
(defun chatgpt--query-by-type-stream (query query-type)
(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-stream
(format format-string query))
(error "No format string associated with 'query-type' %s. Please customize 'chatgpt-query-format-string-map'" query-type))))
(defun chatgpt-query-by-type-stream (query)
(interactive (list (if (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(read-from-minibuffer "ChatGPT Stream Query: "))))
(let* ((query-type (completing-read "Type of Stream 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-stream query query-type)
(chatgpt--query-stream (format "%s\n\n%s" query-type query)))))
(defun chatgpt-query-stream (query)
(interactive (list (if (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(read-from-minibuffer "ChatGPT Stream Query: "))))
(if (region-active-p)
(chatgpt-query-by-type-stream query)
(chatgpt--query-stream query)))
(provide 'chatgpt_stream)