-
Notifications
You must be signed in to change notification settings - Fork 79
/
chatgpt-shell.el
3360 lines (3058 loc) · 138 KB
/
chatgpt-shell.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
;;; chatgpt-shell.el --- A multi-LLM shell (ChatGPT, Claude, Gemini, Kagi, Ollama, Perplexity) + editing integrations -*- lexical-binding: t -*-
;; Copyright (C) 2023 Alvaro Ramirez
;; Author: Alvaro Ramirez https://xenodium.com
;; URL: https://github.com/xenodium/chatgpt-shell
;; Version: 2.9.1
;; Package-Requires: ((emacs "28.1") (shell-maker "0.74.1"))
(defconst chatgpt-shell--version "2.9.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:
;; `chatgpt-shell' is a comint-based shell for multiple cloud or local
;; LLM services (ChatGPT, Claude, Gemini, Kagi, Ollama, Perplexity).
;;
;; This package also provides integrations like the following (amongst others):
;;
;; M-x `chatgpt-shell-quick-insert'
;; M-x `chatgpt-shell-proofread-region'
;; M-x `chatgpt-shell-prompt-compose'
;; M-x `chatgpt-shell-describe-image'
;; M-x `chatgpt-shell-japanese-lookup'
;;
;; You must set an API key for most cloud services. Check out:
;;
;; `chatgpt-shell-openai-key'.
;; `chatgpt-shell-anthropic-key'.
;; `chatgpt-shell-google-key'.
;; `chatgpt-shell-kagi-key'.
;; `chatgpt-shell-perplexity-key'.
;;
;; Alternatively, local services like Ollama do not require an API key.
;;
;; Run `chatgpt-shell' to open an LLM shell.
;;
;; Please report issues or send patches to
;; https://github.com/xenodium/chatgpt-shell
;;
;; Support the work https://github.com/sponsors/xenodium
;;; Code:
(eval-when-compile
(require 'cl-lib))
(require 'dired)
(require 'esh-mode)
(require 'em-prompt)
(require 'eshell)
(require 'find-func)
(require 'flymake)
(require 'ielm)
(require 'shell-maker)
(require 'smerge-mode)
(require 'ob-core)
(require 'color)
(require 'chatgpt-shell-prompt-compose)
(require 'chatgpt-shell-anthropic)
(require 'chatgpt-shell-google)
(require 'chatgpt-shell-kagi)
(require 'chatgpt-shell-ollama)
(require 'chatgpt-shell-openai)
(require 'chatgpt-shell-perplexity)
(defcustom chatgpt-shell-request-timeout 600
"How long to wait for a request to time out in seconds."
:type 'integer
:group 'chatgpt-shell)
(defcustom chatgpt-shell-default-prompts
'("Write a unit test for the following code:"
"Refactor the following code so that "
"Summarize the output of the following command:"
"What's wrong with this command?"
"Explain what the following code does:")
"List of default prompts to choose from."
:type '(repeat string)
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-describe-code
"What does the following code do?"
"Prompt header of `describe-code`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-write-git-commit
"Please help me write a git commit message for the following commit:"
"Prompt header of `git-commit`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-refactor-code
"Please help me refactor the following code.
Please reply with the refactoring explanation in English, refactored code, and diff between two versions.
Please ignore the comments and strings in the code during the refactoring.
If the code remains unchanged after refactoring, please say 'No need to refactor'."
"Prompt header of `refactor-code`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-generate-unit-test
"Please help me generate unit-test following function:"
"Prompt header of `generate-unit-test`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-proofread-region
"Please help me proofread the following English text and only reply with fixed text:"
"Prompt header used by `chatgpt-shell-proofread-region`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-whats-wrong-with-last-command
"What's wrong with this command execution?"
"Prompt header of `whats-wrong-with-last-command`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-eshell-summarize-last-command-output
"Summarize the output of the following command:"
"Prompt header of `eshell-summarize-last-command-output`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-query-response-style 'other-buffer
"Determines the prompt style when invoking from other buffers.
`'inline' inserts responses into current buffer.
`'other-buffer' inserts responses into a transient buffer.
`'shell' inserts responses and focuses the shell
Note: in all cases responses are written to the shell to keep context."
:type '(choice (const :tag "Inline" inline)
(const :tag "Other Buffer" other-buffer)
(const :tag "Shell" shell))
:group 'chatgpt)
(defcustom chatgpt-shell-after-command-functions nil
"Abnormal hook (i.e. with parameters) invoked after each command.
This is useful if you'd like to automatically handle or suggest things
post execution.
For example:
\(add-hook `chatgpt-shell-after-command-functions'
(lambda (command output success)
(message \"Command: %s\" command)
(message \"Output: %s\" output)))"
:type 'hook
:group 'shell-maker)
(defvaralias 'chatgpt-shell-swap-model-version 'chatgpt-shell-swap-model)
(defvaralias 'chatgpt-shell-display-function 'shell-maker-display-function)
(defvaralias 'chatgpt-shell-read-string-function 'shell-maker-read-string-function)
(defvaralias 'chatgpt-shell-logging 'shell-maker-logging)
(defvaralias 'chatgpt-shell-root-path 'shell-maker-root-path)
(defalias 'chatgpt-shell-save-session-transcript #'shell-maker-save-session-transcript)
(defvar chatgpt-shell--prompt-history nil)
(defcustom chatgpt-shell-language-mapping '(("elisp" . "emacs-lisp")
("objective-c" . "objc")
("objectivec" . "objc")
("cpp" . "c++"))
"Maps external language names to Emacs names.
Use only lower-case names.
For example:
lowercase Emacs mode (without -mode)
Objective-C -> (\"objective-c\" . \"objc\")"
:type '(alist :key-type (string :tag "Language Name/Alias")
:value-type (string :tag "Mode Name (without -mode)"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-babel-headers '(("dot" . ((:file . "<temp-file>.png")))
("plantuml" . ((:file . "<temp-file>.png")))
("ditaa" . ((:file . "<temp-file>.png")))
("objc" . ((:results . "output")))
("python" . ((:python . "python3")))
("swiftui" . ((:results . "file")))
("c++" . ((:results . "raw")))
("c" . ((:results . "raw"))))
"Additional headers to make babel blocks work.
Entries are of the form (language . headers). Headers should
conform to the types of `org-babel-default-header-args', which
see.
Please submit contributions so more things work out of the box."
:type '(alist :key-type (string :tag "Language")
:value-type (alist :key-type (restricted-sexp :match-alternatives (keywordp) :tag "Argument Name")
:value-type (string :tag "Value")))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-source-block-actions
nil
"Block actions for known languages.
Can be used compile or run source block at point."
:type '(alist :key-type (string :tag "Language")
:value-type (list (cons (const primary-action-confirmation) (string :tag "Confirmation Prompt:"))
(cons (const primary-action) (function :tag "Action:"))))
:group 'chatgpt-shell)
(defun chatgpt-shell--make-default-models ()
"Create a list of default models by combining models from different providers.
This function aggregates models from OpenAI, Anthropic, Google, and Ollama.
It returns a list containing all available models from these providers."
(append (chatgpt-shell-openai-models)
(chatgpt-shell-anthropic-models)
(chatgpt-shell-google-models)
(chatgpt-shell-kagi-models)
(chatgpt-shell-ollama-models)
(chatgpt-shell-perplexity-models)))
(defcustom chatgpt-shell-models
(chatgpt-shell--make-default-models)
"The list of supported models to swap from.
See `chatgpt-shell-openai-models',
`chatgpt-shell-anthropic-models'
`chatgpt-shell-ollama-models'
`chatgpt-shell-google-models' for details."
:type '(repeat (alist :key-type symbol :value-type sexp))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-version nil
"The active model version as either a string.
See `chatgpt-shell-models' for available model versions.
Swap using `chatgpt-shell-swap-model'."
:type '(choice (string :tag "String")
(integer :tag "Integer")
(const :tag "Nil" nil))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-temperature nil
"What sampling temperature to use, between 0 and 2, or nil.
Higher values like 0.8 will make the output more random, while
lower values like 0.2 will make it more focused and
deterministic. Value of nil will not pass this configuration to
the model.
See
https://platform.openai.com/docs/api-reference/completions\
/create#completions/create-temperature
for details."
:type '(choice (float :tag "Float")
(const :tag "Nil" nil))
:group 'chatgpt-shell)
(defun chatgpt-shell--append-system-info (text)
"Append system info to TEXT."
(cl-labels ((chatgpt-shell--get-system-info-command
()
(cond ((eq system-type 'darwin) "sw_vers")
((or (eq system-type 'gnu/linux)
(eq system-type 'gnu/kfreebsd)) "uname -a")
((eq system-type 'windows-nt) "ver")
(t (format "%s" system-type)))))
(let ((system-info (string-trim
(shell-command-to-string
(chatgpt-shell--get-system-info-command)))))
(concat text
"\n# System info\n"
"\n## OS details\n"
system-info
"\n## Editor\n"
(emacs-version)))))
(defcustom chatgpt-shell-system-prompts
`(("tl;dr" . "Be as succint but informative as possible and respond in tl;dr form to my queries")
("General" . "You use markdown liberally to structure responses. Always show code snippets in markdown blocks with language labels.")
;; Based on https://github.com/benjamin-asdf/dotfiles/blob/8fd18ff6bd2a1ed2379e53e26282f01dcc397e44/mememacs/.emacs-mememacs.d/init.el#L768
("Programming" . ,(chatgpt-shell--append-system-info
"The user is a programmer with very limited time.
You treat their time as precious. You do not repeat obvious things, including their query.
You are as concise as possible in responses.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses.
Always show code snippets in markdown blocks with language labels.
Don't explain code snippets.
Whenever you output updated code for the user, only show diffs, instead of entire snippets."))
("Mathematics" . "The user is a mathematician with very limited time.
You treat their time as precious. You do not repeat obvious things, including their query.
You are as concise as possible in responses.
You never apologize for confusions because it would waste their time.
All mathematical outputs must be in proper LaTeX format.
Use \\( and \\( for in-line equations, and \\[ and \\] for equation environments.
All mathematical delimiters must be on their own line.
All mathematical outputs are formally expressed in formal mathematical notation.
Don't give approximations or pronunciations for constants or variables.
You give formal definitions for all variables.
You keep your answers succinct and to-the-point.")
("Positive Programming" . ,(chatgpt-shell--append-system-info
"Your goal is to help the user become an amazing computer programmer.
You are positive and encouraging.
You love see them learn.
You do not repeat obvious things, including their query.
You are as concise in responses. You always guide the user go one level deeper and help them see patterns.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses. Always show code snippets in markdown blocks with language labels.
Don't explain code snippets. Whenever you output updated code for the user, only show diffs, instead of entire snippets."))
("Japanese" . ,(chatgpt-shell--append-system-info
"The user is a beginner Japanese language learner with very limited time.
You treat their time as precious. You do not repeat obvious things, including their query.
You are as concise as possible in responses.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses."))
("SwiftUI" . ,(chatgpt-shell--append-system-info
"You are a helpful assistant that generates concise, idiomatic SwiftUI views. Always follow these guidelines:
1. Generate a SwiftUI ContentView.
2. Never import SwiftUI.
3. Ensure code is compatible with devices running iOS 15 or later.
4. Use the `@State`, `@Binding`, or `@ObservedObject` property wrappers where applicable.
5. Assume that all Text should be scalable (e.g., `.font(.body)` or `.dynamicTypeSize(.large)`).
6. When creating custom views, ensure layout is responsive across screen sizes using `.frame`, `.padding()`, `.alignmentGuide()`, or `.geometryReader`.
7. Add a structured comment explaining the purpose of the view at the top.
8. Do not include ContentView_Previews or @main structs.
9. Label markdown source blocks as swiftui.
10. Omit all explanations and code comments.")))
"List of system prompts to choose from.
If prompt is a cons, its car will be used as a title to display.
For example:
\(\"Translating\" . \"You are a helpful English to Spanish assistant.\")\"
\(\"Programming\" . \"The user is a programmer with very limited time...\")"
:type '(alist :key-type (string :tag "Title")
:value-type (string :tag "Prompt value"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-system-prompt 1 ;; Concise
"The system prompt `chatgpt-shell-system-prompts' index.
Or nil if none."
:type '(choice (string :tag "String")
(integer :tag "Integer")
(const :tag "No Prompt" nil))
:group 'chatgpt-shell)
(defun chatgpt-shell-model-version ()
"Return active model version."
(when (boundp 'chatgpt-shell-model-versions)
(error (concat "\"chatgpt-shell-model-versions\" no longer supported. "
"Please unset or migrate to \"chatgpt-shell-models\".")))
(cond ((not chatgpt-shell-model-version)
;; No default model set, find one that's cleared for sending commands.
(if-let* ((cleared-model (seq-find (lambda (model)
(cond ((not (map-elt model :validate-command))
t)
((and (map-elt model :validate-command)
(not (funcall (map-elt model :validate-command)
"hello" model nil)))
t)
(t
nil)))
chatgpt-shell-models))
(model-version (map-elt cleared-model :version)))
model-version
(if (map-elt (seq-first chatgpt-shell-models) :version)
(map-elt (seq-first chatgpt-shell-models) :version)
(error "Could not find a model. Missing model setup?"))))
((stringp chatgpt-shell-model-version)
chatgpt-shell-model-version)
((integerp chatgpt-shell-model-version)
(let ((model (nth chatgpt-shell-model-version
chatgpt-shell-models)))
(cond ((stringp model)
model)
((stringp (map-elt model :version))
(map-elt model :version))
(t
(error "Don't know how to resolve model to version %s"
chatgpt-shell-model-version)))))
(t
(error "Could not find a model. Missing model setup?"))))
(defun chatgpt-shell-system-prompt ()
"Return active system prompt."
(cond ((stringp chatgpt-shell-system-prompt)
chatgpt-shell-system-prompt)
((integerp chatgpt-shell-system-prompt)
(let ((prompt (nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts)))
(if (consp prompt)
(cdr prompt)
prompt)))
(t
nil)))
(defun chatgpt-shell-duplicate-map-keys (map)
"Return duplicate keys in MAP."
(let ((keys (map-keys map))
(seen '())
(duplicates '()))
(dolist (key keys)
(if (member key seen)
(push key duplicates)
(push key seen)))
duplicates))
;;;###autoload
(defun chatgpt-shell-swap-system-prompt ()
"Swap system prompt from `chatgpt-shell-system-prompts'."
(interactive)
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(when-let ((duplicates (chatgpt-shell-duplicate-map-keys chatgpt-shell-system-prompts)))
(user-error "Duplicate prompt names found %s. Please remove" duplicates))
(let* ((choices (append (list "None")
(map-keys chatgpt-shell-system-prompts)))
(choice (completing-read "System prompt: " choices))
(choice-pos (seq-position choices choice)))
(if (or (string-equal choice "None")
(string-empty-p (string-trim choice))
(not choice-pos))
(setq-local chatgpt-shell-system-prompt nil)
(setq-local chatgpt-shell-system-prompt
;; -1 to disregard None
(1- (seq-position choices choice)))))
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil)
(chatgpt-shell--save-variables))
(defun chatgpt-shell--load-awesome-prompts-parse-alist ()
"Helper function for `claude-shell-load-awesome-prompts'.
Download awesome-prompts and parse into a list of label and
prompt cons."
(let ((url "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv")
(collector '()))
(with-current-buffer (url-retrieve-synchronously url)
(goto-char (if (boundp 'url-http-end-of-headers)
url-http-end-of-headers
(error "`url-http-end-of-headers' marker is not defined")))
(forward-line 2)
(while (not (eobp))
(let* ((line (buffer-substring-no-properties (line-beginning-position) (line-end-position)))
(split (split-string line "," 'nil "\""))
(head (car split))
(tail (apply #'concat (cdr split))))
(push (cons head tail) collector)
(forward-line 1))))
collector))
;;;###autoload
(defun chatgpt-shell-load-awesome-prompts ()
"Load `chatgpt-shell-system-prompts' from awesome-chatgpt-prompts.
Downloaded from https://github.com/f/awesome-chatgpt-prompts."
(interactive)
(let ((prompts (chatgpt-shell--load-awesome-prompts-parse-alist)))
(setq chatgpt-shell-system-prompts
(map-merge 'list
chatgpt-shell-system-prompts
(seq-sort (lambda (lhs rhs) (string-lessp (car lhs) (car rhs))) prompts)))
(message "Loaded awesome-chatgpt-prompts")
(setq chatgpt-shell-system-prompt nil)
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil)
(chatgpt-shell-swap-system-prompt)))
;;;###autoload
(defun chatgpt-shell-version ()
"Show `chatgpt-shell' mode version."
(interactive)
(message "chatgpt-shell v%s" chatgpt-shell--version))
(defun chatgpt-shell-reload-default-models ()
"Reload all available models."
(interactive)
(setq chatgpt-shell-models (chatgpt-shell--make-default-models))
(message "Reloaded %d models" (length chatgpt-shell-models)))
(defun chatgpt-shell-swap-model ()
"Swap model version from `chatgpt-shell-models'."
(interactive)
(if-let* ((last-label (chatgpt-shell--model-label))
(width (let ((width))
(mapc (lambda (model)
(unless width
(setq width 0))
(when-let ((provider (map-elt model :provider))
(provider-width (length (map-elt model :provider)))
(longer (> provider-width width)))
(setq width provider-width)))
chatgpt-shell-models)
width))
(models (seq-map (lambda (model)
(format (format "%%-%ds %%s" width)
(map-elt model :provider)
(map-elt model :version)))
chatgpt-shell-models))
(selection (nth 1 (split-string (completing-read "Model version: "
models nil t)))))
(progn
(when (derived-mode-p 'chatgpt-shell-mode)
(setq-local chatgpt-shell-model-version selection)
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil)
(unless (equal last-label (chatgpt-shell--model-label))
(chatgpt-shell-clear-buffer)))
(setq-default chatgpt-shell-model-version selection))
(error "No other providers found")))
(defcustom chatgpt-shell-streaming t
"Whether or not to stream ChatGPT responses (show chunks as they arrive)."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-proxy nil
"When non-nil, use as a proxy (for example http or socks5)."
:type 'string
:group 'chatgpt-shell)
(defun chatgpt-shell--model-settings ()
"Variable model settings.
See `chatgpt-shell-streaming'
`chatgpt-shell-model-temperature'
variable `chatgpt-shell-system-prompt'."
(list (cons :streaming chatgpt-shell-streaming)
(cons :temperature chatgpt-shell-model-temperature)
(cons :system-prompt (chatgpt-shell-system-prompt))))
(defcustom chatgpt-shell-highlight-blocks t
"Whether or not to highlight source blocks."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-render-latex t
"Whether or not to render LaTeX blocks (experimental).
Experimental. Please report issues."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-insert-dividers nil
"Whether or not to display a divider between requests and responses."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-transmitted-context-length
#'chatgpt-shell--approximate-context-length
"Controls the amount of context provided to chatGPT.
This context needs to be transmitted to the API on every request.
ChatGPT reads the provided context on every request, which will
consume more and more prompt tokens as your conversation grows.
Models do have a maximum token limit, however.
A value of nil will send full chat history (the full contents of
the comint buffer), to ChatGPT.
A value of 0 will not provide any context. This is the cheapest
option, but ChatGPT can't look back on your conversation.
A value of 1 will send only the latest prompt-completion pair as
context.
A Value > 1 will send that amount of prompt-completion pairs to
ChatGPT.
A function `(lambda (tokens-per-message tokens-per-name messages))'
returning length. Can use custom logic to enable a shifting context
window."
:type '(choice (integer :tag "Integer")
(const :tag "Not set" nil)
(function :tag "Function"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-welcome-function #'shell-maker-welcome-message
"Function returning welcome message or nil for no message.
See `shell-maker-welcome-message' as an example."
:type 'function
:group 'chatgpt-shell)
(defvar chatgpt-shell--config
(make-shell-maker-config
:name "ChatGPT"
:validate-command
(lambda (command)
(when-let* ((model (chatgpt-shell--resolved-model))
(settings (chatgpt-shell--model-settings))
(validate-command (map-elt model :validate-command)))
(funcall validate-command command model settings)))
:execute-command
(lambda (command shell)
(if-let* ((model (chatgpt-shell--resolved-model))
(handler (map-elt model :handler)))
(funcall handler
:model model
:command command
:context (chatgpt-shell-crop-context
:model model
:command command
:context (map-elt shell :history))
:shell shell
:settings (chatgpt-shell--model-settings))
(error "%s not found" (chatgpt-shell-model-version))))
:on-command-finished
(lambda (command output success)
(chatgpt-shell--put-source-block-overlays)
(run-hook-with-args 'chatgpt-shell-after-command-functions
command output success))
:redact-log-output
(lambda (output)
(if-let ((key (map-elt (chatgpt-shell--resolved-model) :key)))
(replace-regexp-in-string (regexp-quote (funcall key))
"SK-REDACTED-PROVIDER-KEY"
output)
output))))
(defalias 'chatgpt-shell-explain-code #'chatgpt-shell-describe-code)
;; Aliasing enables editing as text in babel.
(defalias 'chatgpt-shell-mode #'text-mode)
(shell-maker-define-major-mode chatgpt-shell--config)
;; Implementation generated by shell-maker
(declare-function chatgpt-shell-clear-buffer "chatgpt-shell")
(cl-defun chatgpt-shell--resolved-model (&key versioned)
"Resolve model VERSIONED name."
(seq-find (lambda (model)
(equal (map-elt model :version)
(or versioned (chatgpt-shell-model-version))))
chatgpt-shell-models))
(cl-defun chatgpt-shell--make-payload (&key version context streaming temperature system-prompt)
"Create a payload for model with VERSION.
Set CONTEXT, STREAMING, TEMPERATURE, and SYSTEM-PROMPT as usual."
(let* ((model (chatgpt-shell--resolved-model :versioned version))
(settings (list (cons :streaming streaming)
(cons :temperature temperature)
(cons :system-prompt system-prompt)))
(payload (or (map-elt model :payload)
(error "Model :payload not found"))))
(funcall payload
:model model
:context context
:settings settings)))
;;;###autoload
(defun chatgpt-shell (&optional new-session)
"Start a ChatGPT shell interactive command.
With NEW-SESSION, start a new session."
(interactive "P")
(chatgpt-shell-start nil new-session))
(defvar chatgpt-shell-mode-map (make-sparse-keymap)
"Keymap for `chatgpt-shell-mode'.")
(defun chatgpt-shell-start (&optional no-focus new-session ignore-as-primary model-version system-prompt)
"Start a ChatGPT shell programmatically.
Set NO-FOCUS to start in background.
Set NEW-SESSION to start a separate new session.
Set IGNORE-AS-PRIMARY to avoid making new buffer the primary one.
Set MODEL-VERSION to override variable `chatgpt-shell-model-version'.
Set SYSTEM-PROMPT to override variable `chatgpt-shell-system-prompt'"
(let* ((chatgpt-shell--config
(let ((config (copy-sequence chatgpt-shell--config))
(chatgpt-shell-model-version (or model-version chatgpt-shell-model-version))
(chatgpt-shell-system-prompt (or system-prompt chatgpt-shell-system-prompt)))
(setf (shell-maker-config-prompt config)
(car (chatgpt-shell--prompt-pair)))
(setf (shell-maker-config-prompt-regexp config)
(cdr (chatgpt-shell--prompt-pair)))
config))
(shell-buffer
(shell-maker-start chatgpt-shell--config
no-focus
chatgpt-shell-welcome-function
new-session
(if (and (chatgpt-shell--primary-buffer)
(not ignore-as-primary))
(buffer-name (chatgpt-shell--primary-buffer))
(chatgpt-shell--make-buffer-name))
"LLM")))
(when (and (not ignore-as-primary)
(not (chatgpt-shell--primary-buffer)))
(chatgpt-shell--set-primary-buffer shell-buffer))
(unless model-version
(setq model-version chatgpt-shell-model-version))
(unless system-prompt
(setq system-prompt chatgpt-shell-system-prompt))
(with-current-buffer shell-buffer
(setq-local chatgpt-shell-model-version model-version)
(setq-local chatgpt-shell-system-prompt system-prompt)
(chatgpt-shell--update-prompt t)
(chatgpt-shell--add-menus))
(define-key chatgpt-shell-mode-map (kbd "C-M-h")
#'chatgpt-shell-mark-at-point-dwim)
(define-key chatgpt-shell-mode-map (kbd "C-c C-c")
#'chatgpt-shell-ctrl-c-ctrl-c)
(define-key chatgpt-shell-mode-map (kbd "C-c C-v")
#'chatgpt-shell-swap-model)
(define-key chatgpt-shell-mode-map (kbd "C-c C-s")
#'chatgpt-shell-swap-system-prompt)
(define-key chatgpt-shell-mode-map (kbd "C-c C-p")
#'chatgpt-shell-previous-item)
(define-key chatgpt-shell-mode-map (kbd "<backtab>")
#'chatgpt-shell-previous-item)
(define-key chatgpt-shell-mode-map (kbd "C-c C-n")
#'chatgpt-shell-next-item)
(define-key chatgpt-shell-mode-map (kbd "<tab>")
#'chatgpt-shell-next-item)
(define-key chatgpt-shell-mode-map (kbd "C-c C-e")
#'chatgpt-shell-prompt-compose)
shell-buffer))
(defun chatgpt-shell--shrink-system-prompt (prompt)
"Shrink PROMPT."
(if (consp prompt)
(chatgpt-shell--shrink-system-prompt (car prompt))
(if (> (length (string-trim prompt)) 15)
(format "%s..."
(substring (string-trim prompt) 0 12))
(string-trim prompt))))
(defun chatgpt-shell--shell-info ()
"Generate shell info for display."
(concat
(chatgpt-shell--model-short-version)
(cond ((and (integerp chatgpt-shell-system-prompt)
(nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))
(concat "/" (chatgpt-shell--shrink-system-prompt (nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))))
((stringp chatgpt-shell-system-prompt)
(concat "/" (chatgpt-shell--shrink-system-prompt chatgpt-shell-system-prompt)))
(t
""))))
(defun chatgpt-shell--model-label ()
"Return the current model label."
(or (map-elt (chatgpt-shell--resolved-model) :label)
"Unknown"))
(defun chatgpt-shell--model-short-version ()
"Return the current model short version."
(or (map-elt (chatgpt-shell--resolved-model) :short-version)
(map-elt (chatgpt-shell--resolved-model) :version)
"unknown"))
(defun chatgpt-shell--prompt-pair ()
"Return a pair with prompt and prompt-regexp."
(let* ((label (chatgpt-shell--model-label)))
(cons
(format "%s(%s)> " label (chatgpt-shell--shell-info))
(chatgpt-shell--prompt-regexp))))
(defun chatgpt-shell--prompt-regexp ()
"Return a regexp to match any model prompt."
(rx bol
(one-or-more alphanumeric)
"("
(minimal-match (one-or-more not-newline))
")> "))
(defun chatgpt-shell--shell-buffers ()
"Return a list of all shell buffers."
(seq-filter
(lambda (buffer)
(eq (buffer-local-value 'major-mode buffer)
'chatgpt-shell-mode))
(buffer-list)))
(defun chatgpt-shell-set-as-primary-shell ()
"Set as primary shell when there are multiple sessions."
(interactive)
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(chatgpt-shell--set-primary-buffer (current-buffer)))
(defvar-local chatgpt-shell--is-primary-p nil
"Non-nil if shell buffer is considered primary.")
(defun chatgpt-shell--set-primary-buffer (primary-shell-buffer)
"Set PRIMARY-SHELL-BUFFER as primary buffer."
(unless primary-shell-buffer
(error "No primary shell available"))
(mapc (lambda (shell-buffer)
(with-current-buffer shell-buffer
(setq chatgpt-shell--is-primary-p nil)))
(chatgpt-shell--shell-buffers))
(with-current-buffer primary-shell-buffer
(setq chatgpt-shell--is-primary-p t)))
(defun chatgpt-shell--primary-buffer ()
"Return the primary shell buffer.
This is used for sending a prompt to in the background."
(let* ((shell-buffers (chatgpt-shell--shell-buffers))
(primary-shell-buffer (seq-find
(lambda (shell-buffer)
(with-current-buffer shell-buffer
chatgpt-shell--is-primary-p))
shell-buffers)))
(unless primary-shell-buffer
(setq primary-shell-buffer
(or (seq-first shell-buffers)
(shell-maker-start chatgpt-shell--config
t
chatgpt-shell-welcome-function
t
(chatgpt-shell--make-buffer-name)
"LLM")))
(chatgpt-shell--set-primary-buffer primary-shell-buffer))
primary-shell-buffer))
(defun chatgpt-shell--make-buffer-name ()
"Generate a buffer name using current shell config info."
(format "*%s llm* %s"
(downcase (chatgpt-shell--model-label))
(chatgpt-shell--shell-info)))
(defun chatgpt-shell--add-menus ()
"Add ChatGPT shell menu items."
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(when-let ((duplicates (chatgpt-shell-duplicate-map-keys chatgpt-shell-system-prompts)))
(user-error "Duplicate prompt names found %s. Please remove.?" duplicates))
(easy-menu-define chatgpt-shell-system-prompts-menu (current-local-map) "ChatGPT"
`("ChatGPT"
("Versions"
,@(mapcar (lambda (version)
`[,version
(lambda ()
(interactive)
(setq-local chatgpt-shell-model-version
(seq-position chatgpt-shell-models ,version))
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil))])
chatgpt-shell-models))
("Prompts"
,@(mapcar (lambda (prompt)
`[,(car prompt)
(lambda ()
(interactive)
(setq-local chatgpt-shell-system-prompt
(seq-position (map-keys chatgpt-shell-system-prompts) ,(car prompt)))
(chatgpt-shell--save-variables)
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil))])
chatgpt-shell-system-prompts))))
(easy-menu-add chatgpt-shell-system-prompts-menu))
(defun chatgpt-shell--update-prompt (rename-buffer)
"Update prompt and prompt regexp from `chatgpt-shell-models'.
Set RENAME-BUFFER to also rename the buffer accordingly."
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(shell-maker-set-prompt
(car (chatgpt-shell--prompt-pair))
(cdr (chatgpt-shell--prompt-pair)))
(when rename-buffer
(shell-maker-set-buffer-name
(current-buffer)
(chatgpt-shell--make-buffer-name))))
(defun chatgpt-shell-interrupt (ignore-item)
"Interrupt `chatgpt-shell' from any buffer.
With prefix IGNORE-ITEM, do not mark as failed."
(interactive "P")
(with-current-buffer
(cond
((derived-mode-p 'chatgpt-shell-mode)
(current-buffer))
(t
(shell-maker-buffer-name chatgpt-shell--config)))
(shell-maker-interrupt ignore-item)))
(defun chatgpt-shell-ctrl-c-ctrl-c (ignore-item)
"If point in source block, execute it. Otherwise interrupt.
With prefix IGNORE-ITEM, do not use interrupted item in context."
(interactive "P")
(cond ((chatgpt-shell-block-action-at-point)
(chatgpt-shell-execute-block-action-at-point))
((chatgpt-shell-markdown-block-at-point)
(user-error "No action available"))
((and shell-maker--busy
(eq (line-number-at-pos (point-max))
(line-number-at-pos (point))))
(shell-maker-interrupt ignore-item))
(t
(shell-maker-interrupt ignore-item))))
(defun chatgpt-shell-mark-at-point-dwim ()
"Mark source block if at point. Mark all output otherwise."
(interactive)
(if-let ((block (chatgpt-shell-markdown-block-at-point)))
(progn
(set-mark (map-elt block 'end))
(goto-char (map-elt block 'start)))
(shell-maker-mark-output)))
(defun chatgpt-shell-markdown-block-language (text)
"Get the language label of a Markdown TEXT code block."
(when (string-match (rx bol "```" (0+ space) (group (+ (not (any "\n"))))) text)
(match-string 1 text)))
(defun chatgpt-shell-markdown-block-at-point ()
"Markdown start/end cons if point at block. nil otherwise."
(save-excursion
(save-restriction
(when (derived-mode-p 'chatgpt-shell-mode)
(shell-maker-narrow-to-prompt))
;; Ensure point is within block if at bol in header.
(move-end-of-line 1)
(let* ((language)
(language-start)
(language-end)
(start (save-excursion
(when (re-search-backward "^[ \t]*```" nil t)
(setq language (chatgpt-shell-markdown-block-language (thing-at-point 'line)))
(save-excursion
(forward-char 3) ; ```
(setq language-start (point))
(end-of-line)
(setq language-end (point)))
language-end)))
(end (save-excursion
(when (re-search-forward "^[ \t]*```" nil t)
(forward-line 0)
(point)))))
(when (and start end
(>= (point) start)
(< (point) end))
(list (cons 'language language)
(cons 'language-start language-start)
(cons 'language-end language-end)
(cons 'start start)
(cons 'end end)))))))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-headers (&optional avoid-ranges)
"Extract markdown headers with AVOID-RANGES."
(let ((headers '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx bol (group (one-or-more "#"))
(one-or-more space)
(group (one-or-more (not (any "\n")))) eol)
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start begin
'end end
'level (cons (match-beginning 1) (match-end 1))