-
Notifications
You must be signed in to change notification settings - Fork 3
/
org-assistant.el
1458 lines (1313 loc) · 60.6 KB
/
org-assistant.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; org-assistant.el --- Org babel extension for Chat Assistant APIs -*- lexical-binding: t -*-
;; Author: Tyler Dodge (tyler@tdodge.consulting)
;; Version: 1.5
;; Keywords: convenience
;; Package-Requires: ((emacs "28.1") (uuidgen "1.2") (deferred "0.5.1") (s "1.12.0") (dash "2.19.1") (ht "0.9"))
;; URL: https://github.com/tyler-dodge/org-assistant
;; Git-Repository: git://github.com/tyler-dodge/org-assistant.git
;; This program 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 of the License, or
;; (at your option) any later version.
;; This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
;;;
;;;
;;; Commentary:
;; org-assistant provides support for accessing chat APIs such as
;; ChatGPT in the context of an org notebook.
;;
;; <img src="screenshots/example.gif" alt="example" width="400" />
;;
;; ## Installation
;;
;; Org-assistant is available on [MELPA](http://stable.melpa.org/#/org-assistant)
;;
;; <kbd>M-x</kbd> `package-install` <kbd>[RET]</kbd> `org-assistant` <kbd>[RET]</kbd>
;;
;; ## Usage
;;
;; It provides a function named org-assistant that serves as
;; entrypoint for displaying an org assistant buffer. Also, it can be
;; used in any org file by using a src block like #+BEGIN_SRC
;; assistant or #+BEGIN_SRC ?.
;;
;; The API Key is looked up via org-assistant-auth-function, which has
;; meen tested using the MacOS Keychain. Alternatively,
;; org-assistant-auth-function can be a string and directly set to
;; your API key.
;; <example>
;; (setq org-assistant-auth-function "<YOUR_API_KEY>")
;; </example>
;; Calling `org-assistant' interactively will generate an org-assistant buffer for you.
;; It can be set to a keybinding for quick use like below:
;; <example>
;; (global-set-key (kbd "C-x C-o") #'org-assistant)
;; </example>
;;
;; ### Conversation Evaluation Rules
;; - The org tree is traversed up in order to generate the message
;; list when sending information to the chat endpoint.
;; - It will only use messages from the branch of the tree that the block that
;; initiated the request is in.
;; - It does not include example blocks or source blocks that appear later in
;; the org buffer than the initiating block.
;; - noweb support is enabled for all blocks in the conversation based on the
;; initiating block having the :noweb flag set.
;; - Example blocks are treated as being responses from the assistant by default
;; if they occur after user messages.
;; - If the example block is before any user source block, they are
;; treated as system messages to the assistant instead.
;;
;; See [org-babel-execute:assistant](https://github.com/tyler-dodge/org-assistant#org-babel-executeassistant)
;; for more details.
;;
;; ### Example
;; <example>
;; * Chat User Question
;; #+BEGIN_SRC ?
;; Hi
;; #+END_SRC
;;
;; AI Response
;; #+BEGIN_SRC assistant :sender assistant
;; Hello! How can I assist you today?
;; #+END_SRC
;; </example>
;;
;; When the output is set to png file, the image generation APIs are
;; called instead.
;; <example>
;; * Image Generation User Question
;; #+BEGIN_SRC ? :file sphere.png
;; Generate a sphere
;; #+END_SRC
;;
;; AI Response
;; #+RESULTS:
;; file:sphere.png
;; </example>
;;
;; You can introspect the sent conversation using the :echo flag.
;; <example>
;; * Branching Echo
;; #+BEGIN_SRC ?
;; This is the user. Repeat verbatim only: "This is the system"
;; #+END_SRC
;;
;; #+RESULTS:
;; #+BEGIN_SRC assistant :sender assistant
;; "This is the system"
;; #+END_SRC
;;
;; ** Branch A
;; #+BEGIN_SRC ? :echo
;; Response A
;; #+END_SRC
;;
;; #+RESULTS:
;; #+BEGIN_SRC assistant :sender assistant
;; (user . "This is the user. Repeat verbatim only: \"This is the system\"")
;; (assistant . "\"This is the system\"")
;; (user . "Response A")
;; #+END_SRC
;;
;; ** Branch B
;; #+BEGIN_SRC ? :echo
;; Response B
;; #+END_SRC
;;
;; #+RESULTS:
;; #+BEGIN_SRC assistant :sender assistant
;; (user . "This is the user. Repeat verbatim only: \"This is the system\"")
;; (assistant . "\"This is the system\"")
;; (user . "Response B")
;; #+END_SRC
;; </example>
;;
;; ## Comparison With Other AI Packages
;; ### [org-assistant.el](https://github.com/tyler-dodge/org-assistant) and [org-ai.el](https://github.com/rksm/org-ai)
;; - [org-ai.el](https://github.com/rksm/org-ai) is focused more on runtime interaction with AI
;; - [org-assistant.el](https://github.com/tyler-dodge/org-assistant) is focused more on reproducible sessions
;; via org babel
;; - [org-assistant.el](https://github.com/tyler-dodge/org-assistant) supports branching conversations
;; - [org-assistant.el](https://github.com/tyler-dodge/org-assistant) is not meant to be used downstream
;; as a library for AI endpoint interactions.
;; - In [org-assistant.el](https://github.com/tyler-dodge/org-assistant), all interaction is async using org-babel, which allows
;; for notebook style prompt development
;; - In [org-ai.el](https://github.com/rksm/org-ai), interaction is synchronous and inline,
;; which is better for in-editor use cases
;; - [org-ai.el](https://github.com/rksm/org-ai) supports a lot of other AI use cases like text to speech
;;
;; ### [org-assistant.el](https://github.com/tyler-dodge/org-assistant) and [gptel](https://github.com/karthink/gptel)
;; - Most of the same differences and similarities apply from
;; [org-assistant.el](https://github.com/tyler-dodge/org-assistant) and [org-ai.el](https://github.com/rksm/org-ai)
;;
;; ### Feel free to add a pull request detailing the differences if there is a package I missed
;;
;;; Code:
(require 'org)
(require 'org-element)
(require 'deferred)
(require 's)
(require 'uuidgen)
(require 'dash)
(require 'url)
(require 'ob-core)
(require 'url-vars)
(require 'auth-source)
(require 'simple)
(require 'evil nil t)
(require 'ht)
(defgroup org-assistant nil "Customization settings for `org-assistant'."
:group 'org)
(defcustom org-assistant-auth-function #'org-assistant-auth-source-search
"Function used to get the secret key.
Optionally can be set directly to a string, in which case it will be
used as the OpenAI key."
:group 'org-assistant
:type '(string function))
(defcustom org-assistant-mode-visual-line-enabled t
"When non-nil, `visual-line-mode' is enabled with `org-assistant-mode'."
:group 'org-assistant
:type '(boolean))
(defcustom org-assistant-buffer-name "*org-assistant*"
"The buffer name used for the `org-assistant' buffer."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-mode-line-format
`("***"
mode-line-buffer-identification " " mode-line-position
,(when (boundp 'evil-mode-line-tag) 'evil-mode-line-tag)
" " mode-line-modes mode-line-misc-info
(:eval (concat "[" (s-join "," (--map (substring it 0 4) org-assistant--inflight-request)) "]") )
mode-line-end-spaces)
"The `mode-line-format' used by the `org-assistant' buffer.
Set to nil to use `mode-line-format' instead."
:group 'org-assistant
:type '(list))
(defcustom org-assistant-model "gpt-3.5-turbo"
"The model used for the assistant."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-curl-command "curl"
"The path to the curl command used to run requests."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-endpoint "https://api.openai.com"
"The endpoint used for the assistant.
`org-assistant-endpoint-path-chat' and `org-assistant-endpoint-path-image'
contain the paths for the respective APIs."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-endpoint-path-chat "/v1/chat/completions"
"The path used for the chat API.
See `org-assistant-endpoint' for the domain."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-endpoint-path-models "/v1/models"
"The path used for the list models API.
See `org-assistant-endpoint' for the domain."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-endpoint-path-image "/v1/images/generations"
"The endpoint used for the assistant."
:group 'org-assistant
:type '(string))
(defcustom org-assistant-response-completed-hook nil
"The hook called whenever a `org-assistant' request finishes executing.
Called with the arguments: Stream-Id and Message
Where:
Stream-Id is the stream-id of the request
Message is the full contents of the response from the endpoint.
The buffer and point are set to the the end of the response."
:group 'org-assistant
:type 'hook)
(defcustom org-assistant-parallelism 1
"The max inflight requests to send with `org-assistant' at once."
:group 'org-assistant
:type '(number))
(defcustom org-assistant-logging nil
"Enable `org-assistant' logging when set to non-nil."
:group 'org-assistant
:type '(boolean))
(defcustom org-assistant-chat-extra-parameters-alist
nil
"Extra parameters to be sent with a chat request.
Known keys are:
temperature
top_p
n
stream
stop
max-tokens
presence-penalty
frequency-penalty
logit-bias
user
Should be a alist like '((max_tokens . 10) (user . \"emacs\")).
This can be overriden on a per-src block basis by specifying the
:params argument.
See https://platform.openai.com/docs/api-reference/chat/create
for reference.
<example>
#+BEGIN_SRC assistant :params '((max_tokens . 10) (user . \"emacs\"))
Hi
#+END_SRC
</example>"
:group 'org-assistant
:type '(alist))
(defcustom org-assistant-image-extra-parameters-alist
nil
"Extra parameters to be sent with an image request.
Known allowed keys are:
size
user
Should be a alist like '((size . \"1024x1024\") (user . \"emacs\")).
This can be overriden on a per-src block basis by specifying the
:params argument.
See https://platform.openai.com/docs/api-reference/chat/create
for reference.
<example>
#+BEGIN_SRC assistant :params '((max_tokens . 10) (user . \"emacs\"))
Hi
#+END_SRC
</example>"
:group 'org-assistant
:type '(alist))
(defcustom org-assistant-execute-curl-process-function
#'org-assistant--execute-curl-shell-command-request
"Function used to execute the shell command for `org-assistant'.
See `org-assistant--execute-curl-shell-command-request' for expected arguments."
:group 'org-assistant
:type '(function))
(defvar org-babel-default-header-args:assistant
(list (cons :results "raw") (cons :exports "both") (cons :eval "no-export"))
"Extra args so that org babel renders the results correctly.
This should match `org-babel-default-header-args:?'")
(defvar org-babel-default-header-args:?
org-babel-default-header-args:assistant
"Extra args so that org babel renders the results correctly.
This should match `org-babel-default-header-args:assistant'")
(defvar org-assistant--streaming-overlays (make-hash-table :test #'equal)
"Hash table that contains the mapping of request ids to overlays.")
(defvar-local org-assistant--process-json-read-pt nil
"Marker that represents the end of the last read output.
For org-assisant process buffers.")
(defvar-local org-assistant--buffer-requests nil
"Buffer local list that keeps track of `org-assistant' requests.")
(defvar org-assistant-history nil
"History variable for `org-assistant'.")
(defvar org-assistant-logging-buffer "*org-asssistant-log*"
"Buffer used for logging `org-assistant'.
See `org-assistant-logging'.")
(defun org-assistant-with-initial-message (message)
"Create and display a buffer named `org-assistant-buffer-name'.
The buffer contains the response from the assistant given the prompt
contained in MESSAGE."
(let ((buffer (get-buffer-create "*org-assistant*")))
(with-current-buffer buffer
(org-mode)
(org-assistant-mode 1)
(display-line-numbers-mode -1)
(goto-char (point-max))
(insert "\n* Question\n#+BEGIN_SRC ?\n")
(insert message)
(let ((pt (point)))
(save-excursion
(insert "\n#+END_SRC\n"))
(run-at-time nil nil
(lambda ()
(with-current-buffer buffer
(goto-char (point-max))
(forward-line -1)
(cl-loop for window in (get-buffer-window-list buffer)
do (set-window-point window pt))
(org-ctrl-c-ctrl-c))))
(set-window-point
(select-window (display-buffer buffer))
pt)))))
(defvar org-assistant-mode-map (make-sparse-keymap)
"Keymap for `org-assistant-mode' buffers.")
(defconst org-assistant--begin-src-regexp
(rx line-start (* whitespace) "#+BEGIN_SRC"
(+ whitespace)
(or "assistant" "?"))
"Regexp for finding #+BEGIN_SRC ? blocks.")
(defconst org-assistant--end-src-regexp
(rx line-start (* whitespace) "#+END_SRC")
"Regexp for finding #+END_SRC blocks.")
(defconst org-assistant--results-regexp
(rx line-start (* whitespace) "#+RESULTS:")
"Regexp for finding #+RESULTS blocks.")
(defconst org-assistant--begin-example-regexp
(rx "#+BEGIN_EXAMPLE")
"Regexp for finding #+BEGIN_EXAMPLE blocks.")
(define-minor-mode org-assistant-mode "Mode for org assistant buffers."
:init-value nil
:keymap org-assistant-mode-map
(add-hook 'kill-buffer-hook #'org-assistant-kill-buffer-requests nil t)
(when org-assistant-mode-visual-line-enabled
(visual-line-mode org-assistant-mode))
(when org-assistant-mode-line-format
(setq-local mode-line-format org-assistant-mode-line-format)))
(defvar org-assistant--request-queue nil
"Request queue used by `org-assistant' to limit parallelism of requests.")
(defvar org-assistant--inflight-request nil
"Tracks inflight requests for `org-assistant'.")
(defvar org-assistant--request-queue-active-p nil
"Tracks when the request queue is active.
This is used to avoid automatically adjusting the
prompt when multiple are inflight.")
;;;###autoload
(defun org-assistant-setup ()
"Set up optional libraries like `markdown-mode' to work with `org-assistant'.
If `markdown-mode' is available, it will be used."
(when (require 'markdown-mode nil t)
(add-to-list 'org-src-lang-modes '("?" . markdown))
(add-to-list 'org-src-lang-modes '("assistant" . markdown))))
;;;###autoload
(defun org-assistant ()
"Prompt the user for an initial prompt for the assistant.
Then display a window with the buffer containing the response."
(interactive)
(let ((message (read-from-minibuffer "Chat:" nil nil nil org-assistant-history)))
(org-assistant-with-initial-message message)))
(defun org-assistant-auth-source-search ()
"Example auth source function for use with `org-assistant-auth-function'.
This has been tested with the `macos-keychain-generic' auth-source
where openai-key is an application password with the name openai-key."
(-some-->
(auth-source-search
:user "openai-key")
(car it)
(plist-get it :secret)
(aref it 2)
(aref it 0)))
(defun org-assistant--deferred-decode-response (deferred)
"After DEFERRED completes, decode the http response in BUFFER."
(deferred:$
deferred
(deferred:nextc
it
(lambda (text)
(or
(condition-case _
(--doto (org-assistant--json-decode text)
(-let [(&alist 'error (&alist 'message error-message 'type error-type)) it]
(when error-type
(error "%s: %s" error-type error-message))))
(json-readtable-error (error "Unexpected output from server.
%s" text)))
(error "Response was unexpectedly nil %S" (buffer-string)))))))
(defvar org-assistant--request-id nil
"Request ID for `org-assistant'.
Set specially by the macro `org-assistant-org-babel-async-response'.")
(defvar org-assistant--request-processes-ht (make-hash-table :test #'equal)
"Hash table mapping request id to active process.")
;;;###autoload
(defmacro org-assistant-org-babel-async-response (streaming &rest prog)
"Macro for handling asynchronous responses with `org-mode'.
When STREAMING is set to non-nil, expect a streaming response for the endpoint.
Provides a function called `babel-response' that can be called in PROG to
substitute the response value in the org buffer that initiated this call.
Returns a UUID placeholder that `org-mode' emits into the buffer, which is
later substituted by `org-assistant'."
(declare
(debug t)
(indent 0))
(let ((buffer-var (make-symbol "buffer"))
(start-pt-var (make-symbol "start-pt"))
(in-src-block-var (make-symbol "in-src-block"))
(pt-temp-var (make-symbol "temp-pt"))
(insert-prompt-var (make-symbol "insert-prompt"))
(error-var (make-symbol "error"))
(has-output-var (make-symbol "has-output"))
(replacement-var (make-symbol "replacement")))
`(let* ((,buffer-var (current-buffer))
(,replacement-var (org-assistant--generate-replacement-string))
(,start-pt-var (point))
(,has-output-var (cons nil nil))
(org-assistant--request-id ,replacement-var))
(cl-flet ((babel-output-empty-p () (not (car ,has-output-var)))
(babel-response (message &optional response-type streaming)
(setcar ,has-output-var t)
(run-at-time
nil nil
(lambda ()
(let ((inhibit-message t)
(,replacement-var ,replacement-var))
(unless streaming
(setq org-assistant--buffer-requests
(--filter (not (string= it ,replacement-var)) org-assistant--buffer-requests))
(setq org-assistant--inflight-request
(--filter (not (string= it ,replacement-var)) org-assistant--inflight-request)))
(when (buffer-live-p ,buffer-var)
(with-current-buffer ,buffer-var
(let ((,pt-temp-var (point)))
(-some-->
(save-mark-and-excursion
(goto-char (point-min))
(if-let ((overlay (gethash ,replacement-var org-assistant--streaming-overlays)))
(progn
(overlay-put overlay 'before-string (concat (overlay-get overlay 'before-string)
message))
(unless (or
(not streaming)
(save-match-data
(save-excursion
(goto-char (overlay-start overlay))
(org-assistant--in-src-block-p))))
(org-assistant--kill-request (overlay-get overlay 'stream-id)))
(when (not streaming)
(let ((text (overlay-get overlay 'before-string))
(pt (overlay-start overlay)))
(remhash ,replacement-var org-assistant--streaming-overlays)
(delete-overlay overlay)
(when pt
(save-match-data
(save-excursion
(goto-char pt)
(let ((end-block
(save-excursion
(when
(re-search-forward org-assistant--end-src-regexp nil t))
(forward-line -1)
(end-of-line)
(point))))
(when (and end-block
(save-match-data
(save-excursion
(org-assistant--in-src-block-p))))
(insert (org-escape-code-in-string text))
(run-hook-with-args
'org-assistant-response-completed-hook
,replacement-var
(buffer-substring-no-properties
(save-excursion
(re-search-backward org-assistant--begin-src-regexp)
(forward-line 1)
(point))
end-block)))))))))
nil)
(when (re-search-forward (rx (literal ,replacement-var)) nil t)
(pcase response-type
('file-list
(replace-match
(string-join (--map (format "%s" it) message) "\n")
nil t)
(goto-char (match-end 0))
(forward-line 0)
(cl-loop with first = t
while (looking-at (rx (literal (car message)) line-end))
do
(if first
(progn
(forward-line 1)
(setq first nil))
(replace-match ""))))
(_
(let* ((,in-src-block-var (save-match-data
(save-excursion
(org-assistant--in-src-block-p))))
(,insert-prompt-var
(and
(not ,in-src-block-var)
(not org-assistant--request-queue-active-p)
(eq ,pt-temp-var ,start-pt-var)
(not
(save-match-data
(save-mark-and-excursion
(and
(re-search-forward org-assistant--begin-src-regexp nil t))))))))
(progn
(save-excursion
(goto-char (match-beginning 0))
(when (not streaming) (replace-match ""))
(delete-region (match-beginning 0) (match-end 0))
(insert "#+BEGIN_SRC assistant :sender assistant"
"\n")
(if streaming
(--doto (make-overlay (point) (point))
(overlay-put it 'stream-id ,replacement-var)
(overlay-put it 'after-string " _")
(overlay-put it 'before-string message)
(puthash ,replacement-var it org-assistant--streaming-overlays))
(insert message))
(insert
"
#+END_SRC"
(if (and ,insert-prompt-var) "\n\n#+BEGIN_SRC ?\n\n#+END_SRC\n" "")))
(when ,insert-prompt-var
(re-search-forward org-assistant--begin-src-regexp nil t)
(re-search-forward org-assistant--begin-src-regexp nil t)
(forward-line 1)
(point)))))))))
(progn
(unless org-assistant--request-queue-active-p
(goto-char it)
(cl-loop for window in (get-buffer-window-list (current-buffer))
do (set-window-point window it))))))
(unless (or org-assistant--request-queue
org-assistant--inflight-request)
(setq org-assistant--request-queue-active-p nil)))))))))
(deferred:$
(condition-case ,error-var
(progn ,@prog)
(error (prog1 nil (babel-response ,error-var)))
(user-error (prog1 nil (babel-response ,error-var))))
(when (and it (or (deferred-p it)
(error "Provided an unexpected type, expected deferred: %S" it)))
(deferred:error it (lambda (error) (format "%S" error))))
(when it
(deferred:nextc it (lambda (response)
(pcase (car-safe response)
('file-list
(babel-response (cdr response) (car response)))
(_
(babel-response (if (stringp response)
response
(if (not (consp (car-safe response)))
(s-join "" response)
(org-assistant--json-encode-pretty-print response))))))))))
(when ,streaming (run-at-time nil nil (lambda () (babel-response "" nil t)))))
(when (buffer-live-p ,buffer-var) (with-current-buffer ,buffer-var (force-mode-line-update)))
(with-current-buffer ,buffer-var
(push ,replacement-var org-assistant--inflight-request))
,replacement-var)))
(cl-defun org-assistant--execute-curl-shell-command-request (&key url method request-id buffer headers body)
"Execute a curl shell command for `org-assistant'.
URL is the endpoint called from `org-assistant'.
METHOD is the Http method used in the request.
REQUEST-ID is the request id, used for debugging purposes.
BUFFER is the buffer that the process should output to
HEADERS are the headers to send in the request
BODY is a JSON object encoded as a string."
(start-process-shell-command
(concat "curl " request-id)
buffer
(s-join " "
(->>
(append
(list org-assistant-curl-command url)
(list "--no-buffer")
(cl-loop for (header . value) in headers
append (list "-H" (concat header ":" (shell-quote-argument value))))
(list "-X" (shell-quote-argument method))
body
nil)))))
(defmacro org-assistant--request-lambda (&rest args)
"Macro for generating a queueable request lambda.
Intended for use with `org-assistant--queue-request'.
ARGS is expected to be a plist with the following keys:
:url The endpoint
:method The HTTP Method
:headers Defaults to (org-assistant--default-headers) if not set
:json See `org-assistant--json-encode'."
(-let [(&plist :url :stream :method :headers :request-id :json) args]
(or url (error "Url must be set %S" args))
(or method (error "Method must be set %S" args))
(let ((request-id-var (make-symbol "request-id"))
(start-marker-var (make-symbol "start-marker"))
(temp-file-var (make-symbol "temp-file"))
(stream-var (make-symbol "stream")))
`(let ((,start-marker-var (--doto (make-marker) (set-marker it (point) (current-buffer))))
(,temp-file-var (make-temp-file "json")))
(lambda ()
(let* ((promise (deferred:new))
(,stream-var ,stream)
(,request-id-var ,request-id)
(,temp-file-var ,temp-file-var)
(shell-buffer (generate-new-buffer " *org-assistant-request*"))
(callback
(lambda ()
(let ((process
(funcall org-assistant-execute-curl-process-function
:url ,url
:method ,method
:request-id ,request-id-var
:buffer shell-buffer
:headers (or ,headers (org-assistant--default-headers))
:body
(-some-->
(with-current-buffer (marker-buffer ,start-marker-var)
(save-excursion
(goto-char ,start-marker-var)
(set-marker ,start-marker-var nil)
(funcall ,json)))
(org-assistant--dedupe-alist it)
(progn ,temp-file-var
(with-temp-file ,temp-file-var
(insert (org-assistant--json-encode it)))
(--doto
(list "--data" (concat "@" ,temp-file-var))
(org-assistant-log "Request Body: %S" it)))))))
(puthash ,request-id-var process org-assistant--request-processes-ht)
(push ,request-id-var org-assistant--buffer-requests)
(set-process-filter
process
(lambda (process text)
(prog1 (internal-default-process-filter process text)
(with-current-buffer (process-buffer process)
(save-match-data
(save-excursion
(unless org-assistant--process-json-read-pt
(setq-local org-assistant--process-json-read-pt (point-min)))
(goto-char org-assistant--process-json-read-pt)
(let* ((json-objects (org-assistant--parse-stream-json-after-point))
(end-of-parse-pt (point)))
(condition-case err
(cl-loop for json in json-objects
do
(progn
(org-assistant-log "Response: %S" json)
(funcall ,stream-var json)))
(user-error
(org-assistant-log "Response Error: %S" err)
(message "Failed to stream object %S" err))
(error
(org-assistant-log "Response Error: %S" err)
(message "Failed to stream object %S" err)))
(when json-objects
(setq-local org-assistant--process-json-read-pt end-of-parse-pt)))))))))
(let ((original-sentinel (process-sentinel process)))
(set-process-sentinel
process
(lambda (process status)
(run-at-time
nil nil
(lambda ()
(cond
((not (string= (string-trim status) "finished"))
(org-assistant-log "Unexpected status %S" status)
(deferred:errorback-post promise (concat (with-current-buffer shell-buffer (buffer-string)) "\n" status))
t)
((not (buffer-live-p shell-buffer))
(org-assistant-log "Buffer unexpectedly not live")
(deferred:errorback-post promise (concat "Buffer not live" (buffer-name shell-buffer)))
t)
(t
(with-current-buffer shell-buffer
(org-assistant-log "Response Complete Success: %S" (buffer-string))
(deferred:callback-post promise
(buffer-string)))))
(remhash ,request-id-var org-assistant--request-processes-ht)
(when (functionp original-sentinel)
(funcall original-sentinel process status))
(kill-buffer shell-buffer)))
(if (file-exists-p ,temp-file-var)
(progn
(delete-file ,temp-file-var)
(org-assistant-log "Deleted %S" ,temp-file-var))
(org-assistant-log "Could not find temp file to delete %S" ,temp-file-var)))))))))
(run-at-time nil nil (lambda ()
(condition-case err
(funcall callback)
(error (deferred:errorback-post promise err))
(user-error (deferred:errorback-post promise err)))))
(deferred:$
promise
(deferred:nextc
it
(lambda (response)
(set-marker ,start-marker-var nil)
response))
(deferred:error
it
(lambda (error)
(set-marker ,start-marker-var nil)
(error (error-message-string error)))))))))))
(defmacro org-assistant--join-endpoint (domain path)
"Validate and return joined DOMAIN and PATH."
`(prog1 (concat ,domain ,path)
(when (string-suffix-p "/" ,domain)
(user-error "`%s' must not end with /. Actual: %s" (quote ,domain) ,domain))
(unless (string-prefix-p "/" ,path)
(user-error "`%s' must start with with /. Actual: %s" (quote ,path) ,path))))
;;;###autoload
(defun org-babel-execute:assistant (text params)
"Execute an `org-assistant' in an org-babel context.
PARAMS is used to enable noweb mode.
If :echo is set, return the conversation that would be sent to the endpoint
instead of evaluating.
If :list-models is set, the `org-assistant-models-endpoint'
will be called instead.
:params can be set to a list like
'((max_tokens . 1)
(stop . \"stop\")).
See https://platform.openai.com/docs/api-reference/chat/create
for parameters.
TEXT must be empty if :list-models is set.
This is intended to be called via org babel in a src block with Ctrl-C
Ctrl-C like:
<example>
#+BEGIN_SRC assistant
Hi
#+END_SRC
</example>
The response from the assistant will be in the example block
following:
<example>
#+BEGIN_SRC assistant :sender assistant
Response
#+END_SRC
</example>
All of the messages that are in the same branch of the org tree are
included in the request to the assistant.
<example>
* Question
#+BEGIN_SRC assistant
Hi
#+END_SRC
#+BEGIN_SRC assistant :sender assistant
Response
#+END_SRC
#+BEGIN_SRC assistant
What's up?
#+END_SRC
</example>
Running babel on the second assistant block will send the
conversation:
<example>
User: Hi
Assistant: Response
User: What's up?
</example>
Running babel on the first assistant block will only include the
messages before it:
<example>
User: Hi
</example>
Only messages in the same branch will be included:
<example>
* Question
#+BEGIN_SRC assistant
Hi
#+END_SRC
#+BEGIN_SRC assistant :sender assistant
Response
#+END_SRC
** Branch A
#+BEGIN_SRC assistant
Branch A
#+END_SRC
#+BEGIN_SRC assistant :sender assistant
Branch A Response
#+END_SRC
** Branch B
#+BEGIN_SRC assistant
Branch B
#+END_SRC
#+BEGIN_SRC assistant :sender assistant
Branch B Response
#+END_SRC
</example>
If you ran Ctrl-C Ctrl-C on Branch B's src block the conversation sent
to the endpoint would be:
<example>
User: Hi
Assistant: Response
User: Branch B
Assistant: Branch B Response
</example>
`org-assistant' also supports image generation.
If the :file attribute is set, the image API will be used.
The following is an example of using the image endpoint:
<example>
#+BEGIN_SRC assistant :file output.png
An image of the GNU mascot
#+END_SRC
</example>"
(org-assistant-cancel-block-at-point)
(unless (> org-assistant-parallelism 0)
(user-error "`org-assistant-parallelism' set to an invalid value. Must be greater than 0"))
(cond
((assoc :list-models params)
(unless (string-blank-p (string-trim text)) (user-error "Cannot use :list-models if body is not empty"))
(org-assistant-org-babel-async-response nil
(deferred:$
(org-assistant--queue-list-models-request org-assistant--request-id))))
(t
(let* ((blocks (lambda () (org-assistant--org-blocks (org-babel-noweb-p params :eval)))))
(cond
((assoc :echo params)
(concat
"#+BEGIN_EXAMPLE
"
(s-join "\n" (--map (format "%S" it) (funcall blocks)))
"
#+END_EXAMPLE
"))
((assoc :file params)
(let ((files (--> (alist-get :file params) (if (listp it) it (list it)))))
(--each files (when (not (string-suffix-p ".png" it))
(user-error "Only .png output files are supported %s" it)))
(org-assistant-org-babel-async-response nil
(deferred:$
(org-assistant--queue-image-request org-assistant--request-id
(lambda (json) (babel-response json nil t))
(alist-get :params params)
blocks)
(deferred:nextc it (lambda (response) (org-assistant--json-decode response)))
(deferred:nextc
it
(lambda (response)
(cons
'file-list
(cl-loop for data across (alist-get 'data response)
collect
(let ((file (or (pop files) (user-error "More files returned than expected"))))
(prog1 (concat "file:" file)
(with-temp-file file
(insert
(base64-decode-string (alist-get 'b64_json data))))))))))))))
(t (org-assistant-org-babel-async-response t
(deferred:$
(org-assistant--queue-chat-request org-assistant--request-id
(lambda (json) (babel-response json nil t))
(alist-get :params params) blocks)
(deferred:nextc it (lambda (response)
(cond ((listp response) (format "%S" response))
((babel-output-empty-p) response)
(t ""))))))))))))
(defun org-assistant-yank-block ()
"Add the current block at point to the kill ring."
(interactive)
(let ((block (org-assistant--block-contents)))
(unless block (user-error "Not in block"))
(kill-new block)))
(defun org-assistant--block-contents ()
"Return the contents of the src block at location."
(when (org-assistant--in-src-block-p)
(save-excursion
(end-of-line)
(unless (re-search-backward org-assistant--begin-src-regexp nil t)
(user-error "Not at src block"))
(forward-line 1)
(let ((start-pt (point)))
(or (-some--> (--first (overlay-get it 'stream-id) (overlays-in start-pt start-pt))
(overlay-get it 'before-string))
(progn
(when (re-search-forward org-assistant--end-src-regexp nil t)
(forward-line -1))
(end-of-line)
(buffer-substring-no-properties start-pt (point))))))))
;;;###autoload
(defun org-babel-execute:? (&rest args)