forked from karthink/gptel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gptel.el
1939 lines (1674 loc) · 74.9 KB
/
gptel.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
;;; gptel.el --- Interact with ChatGPT or other LLMs -*- lexical-binding: t; -*-
;; Copyright (C) 2023 Karthik Chikmagalur
;; Author: Karthik Chikmagalur <karthik.chikmagalur@gmail.com>
;; Version: 0.9.6
;; Package-Requires: ((emacs "27.1") (transient "0.4.0") (compat "29.1.4.1"))
;; Keywords: convenience
;; URL: https://github.com/karthink/gptel
;; SPDX-License-Identifier: GPL-3.0-or-later
;; 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/>.
;; This file is NOT part of GNU Emacs.
;;; Commentary:
;; gptel is a simple Large Language Model chat client, with support for multiple
;; models and backends.
;;
;; It works in the spirit of Emacs, available at any time and in any buffer.
;;
;; gptel supports
;;
;; - The services ChatGPT, Azure, Gemini, Anthropic AI, Anyscale, Together.ai,
;; Perplexity, Anyscale, OpenRouter, Groq, PrivateGPT, DeepSeek, Cerebras,
;; Github Models and Kagi (FastGPT & Summarizer)
;; - Local models via Ollama, Llama.cpp, Llamafiles or GPT4All
;;
;; Additionally, any LLM service (local or remote) that provides an
;; OpenAI-compatible API is supported.
;;
;; Features:
;; - It’s async and fast, streams responses.
;; - Interact with LLMs from anywhere in Emacs (any buffer, shell, minibuffer,
;; wherever)
;; - LLM responses are in Markdown or Org markup.
;; - Supports conversations and multiple independent sessions.
;; - Supports multi-modal models (send images, documents).
;; - Save chats as regular Markdown/Org/Text files and resume them later.
;; - You can go back and edit your previous prompts or LLM responses when
;; continuing a conversation. These will be fed back to the model.
;; - Redirect prompts and responses easily
;; - Rewrite, refactor or fill in regions in buffers
;; - Write your own commands for custom tasks with a simple API.
;;
;; Requirements for ChatGPT, Azure, Gemini or Kagi:
;;
;; - You need an appropriate API key. Set the variable `gptel-api-key' to the
;; key or to a function of no arguments that returns the key. (It tries to
;; use `auth-source' by default)
;;
;; ChatGPT is configured out of the box. For the other sources:
;;
;; - For Azure: define a gptel-backend with `gptel-make-azure', which see.
;; - For Gemini: define a gptel-backend with `gptel-make-gemini', which see.
;; - For Anthropic (Claude): define a gptel-backend with `gptel-make-anthropic',
;; which see
;; - For Together.ai, Anyscale, Perplexity, Groq, OpenRouter, DeepSeek, Cerebras or
;; Github Models: define a gptel-backend with `gptel-make-openai', which see.
;; - For PrivateGPT: define a backend with `gptel-make-privategpt', which see.
;; - For Kagi: define a gptel-backend with `gptel-make-kagi', which see.
;;
;; For local models using Ollama, Llama.cpp or GPT4All:
;;
;; - The model has to be running on an accessible address (or localhost)
;; - Define a gptel-backend with `gptel-make-ollama' or `gptel-make-gpt4all',
;; which see.
;; - Llama.cpp or Llamafiles: Define a gptel-backend with `gptel-make-openai',
;;
;; Consult the package README for examples and more help with configuring
;; backends.
;;
;; Usage:
;;
;; gptel can be used in any buffer or in a dedicated chat buffer. The
;; interaction model is simple: Type in a query and the response will be
;; inserted below. You can continue the conversation by typing below the
;; response.
;;
;; To use this in any buffer:
;;
;; - Call `gptel-send' to send the buffer's text up to the cursor. Select a
;; region to send only the region.
;;
;; - You can select previous prompts and responses to continue the conversation.
;;
;; - Call `gptel-send' with a prefix argument to access a menu where you can set
;; your backend, model and other parameters, or to redirect the
;; prompt/response.
;;
;; To use this in a dedicated buffer:
;;
;; - M-x gptel: Start a chat session
;;
;; - In the chat session: Press `C-c RET' (`gptel-send') to send your prompt.
;; Use a prefix argument (`C-u C-c RET') to access a menu. In this menu you
;; can set chat parameters like the system directives, active backend or
;; model, or choose to redirect the input or output elsewhere (such as to the
;; kill ring).
;;
;; - You can save this buffer to a file. When opening this file, turn on
;; `gptel-mode' before editing it to restore the conversation state and
;; continue chatting.
;;
;; - To include media files with your request, you can add them to the context
;; (described next), or include them as links in Org or Markdown mode chat
;; buffers. Sending media is disabled by default, you can turn it on globally
;; via `gptel-track-media', or locally in a chat buffer via the header line.
;;
;; Include more context with requests:
;;
;; If you want to provide the LLM with more context, you can add arbitrary
;; regions, buffers or files to the query with `gptel-add'. To add text or
;; media files, call `gptel-add' in Dired or use the dedicated `gptel-add-file'.
;;
;; You can also add context from gptel's menu instead (gptel-send with a prefix
;; arg), as well as examine or modify context.
;;
;; When context is available, gptel will include it with each LLM query.
;;
;; Rewrite/refactor interface
;;
;; In any buffer: with a region selected, you can rewrite prose, refactor code
;; or fill in the region. Use gptel's menu (C-u M-x `gptel-send') to access
;; this feature.
;;
;; gptel in Org mode:
;;
;; gptel offers a few extra conveniences in Org mode.
;; - You can limit the conversation context to an Org heading with
;; `gptel-org-set-topic'.
;;
;; - You can have branching conversations in Org mode, where each hierarchical
;; outline path through the document is a separate conversation branch.
;; See the variable `gptel-org-branching-context'.
;;
;; - You can declare the gptel model, backend, temperature, system message and
;; other parameters as Org properties with the command
;; `gptel-org-set-properties'. gptel queries under the corresponding heading
;; will always use these settings, allowing you to create mostly reproducible
;; LLM chat notebooks.
;;
;; Finally, gptel offers a general purpose API for writing LLM ineractions
;; that suit your workflow, see `gptel-request'.
;;; Code:
(declare-function markdown-mode "markdown-mode")
(declare-function gptel-curl-get-response "gptel-curl")
(declare-function gptel-menu "gptel-transient")
(declare-function gptel-system-prompt "gptel-transient")
(declare-function pulse-momentary-highlight-region "pulse")
(declare-function ediff-make-cloned-buffer "ediff-util")
(declare-function ediff-regions-internal "ediff")
(declare-function gptel-org--create-prompt "gptel-org")
(declare-function gptel-org-set-topic "gptel-org")
(declare-function gptel-org--save-state "gptel-org")
(declare-function gptel-org--restore-state "gptel-org")
(declare-function gptel--stream-convert-markdown->org "gptel-org")
(declare-function gptel--convert-markdown->org "gptel-org")
(define-obsolete-function-alias
'gptel-set-topic 'gptel-org-set-topic "0.7.5")
(eval-when-compile
(require 'subr-x)
(require 'cl-lib))
(require 'compat nil t)
(require 'url)
(require 'map)
(require 'text-property-search)
(require 'cl-generic)
(require 'gptel-openai)
(with-eval-after-load 'org
(require 'gptel-org))
;;; User options
(defgroup gptel nil
"Interact with LLMs from anywhere in Emacs."
:group 'hypermedia)
;; (defcustom gptel-host "api.openai.com"
;; "The API host queried by gptel."
;; :group 'gptel
;; :type 'string)
(make-obsolete-variable
'gptel-host
"Use `gptel-make-openai' instead."
"0.5.0")
(defcustom gptel-proxy ""
"Path to a proxy to use for gptel interactions.
Passed to curl via --proxy arg, for example \"proxy.yourorg.com:80\"
Leave it empty if you don't use a proxy."
:type 'string)
(defcustom gptel-api-key #'gptel-api-key-from-auth-source
"An API key (string) for the default LLM backend.
OpenAI by default.
Can also be a function of no arguments that returns an API
key (more secure) for the active backend."
:type '(choice
(string :tag "API key")
(function :tag "Function that returns the API key")))
(defcustom gptel-stream t
"Stream responses from the LLM as they are received.
This option is ignored unless
- the LLM backend supports streaming, and
- Curl is in use (see `gptel-use-curl')
When set to nil, Emacs waits for the full response and inserts it
all at once. This wait is asynchronous.
\='tis a bit silly."
:type 'boolean)
(make-obsolete-variable 'gptel-playback 'gptel-stream "0.3.0")
(defcustom gptel-use-curl (and (executable-find "curl") t)
"Whether gptel should prefer Curl when available."
:type 'boolean)
(defcustom gptel-curl-file-size-threshold 130000
"Size threshold for using file input with Curl.
Specifies the size threshold for when to use a temporary file to pass data to
Curl in GPTel queries. If the size of the data to be sent exceeds this
threshold, the data is written to a temporary file and passed to Curl using the
`--data-binary' option with a file reference. Otherwise, the data is passed
directly as a command-line argument.
The value is an integer representing the number of bytes.
Adjusting this value may be necessary depending on the environment
and the typical size of the data being sent in GPTel queries.
A larger value may improve performance by avoiding the overhead of creating
temporary files for small data payloads, while a smaller value may be needed
if the command-line argument size is limited by the operating system."
:type 'natnum)
(defcustom gptel-response-filter-functions
(list #'gptel--convert-org)
"Abnormal hook for transforming the response from an LLM.
This is used to format the response in some way, such as filling
paragraphs, adding annotations or recording information in the
response like links.
Each function in this hook receives two arguments, the response
string to transform and the LLM interaction buffer. It
should return the transformed string.
NOTE: This is only used for non-streaming responses. To
transform streaming responses, use `gptel-post-stream-hook' and
`gptel-post-response-functions'."
:type 'hook)
(defcustom gptel-pre-response-hook nil
"Hook run before inserting the LLM response into the current buffer.
This hook is called in the buffer where the LLM response will be
inserted.
Note: this hook only runs if the request succeeds."
:type 'hook)
(define-obsolete-variable-alias
'gptel-post-response-hook 'gptel-post-response-functions
"0.6.0"
"Post-response functions are now called with two arguments: the
start and end buffer positions of the response.")
(defcustom gptel-post-response-functions nil
"Abnormal hook run after inserting the LLM response into the current buffer.
This hook is called in the buffer to which the LLM response is
sent, and after the full response has been inserted. Each
function is called with two arguments: the response beginning and
end positions.
Note: this hook runs even if the request fails. In this case the
response beginning and end positions are both the cursor position
at the time of the request."
:type 'hook)
;; (defcustom gptel-pre-stream-insert-hook nil
;; "Hook run before each insertion of the LLM's streaming response.
;; This hook is called in the buffer from which the prompt was sent
;; to the LLM, immediately before text insertion."
;; :group 'gptel
;; :type 'hook)
(defcustom gptel-post-stream-hook nil
"Hook run after each insertion of the LLM's streaming response.
This hook is called in the buffer from which the prompt was sent
to the LLM, and after a text insertion."
:type 'hook)
(defcustom gptel-save-state-hook nil
"Hook run before gptel saves model parameters to a file.
You can use this hook to store additional conversation state or
model parameters to the chat buffer, or to modify the buffer in
some other way."
:type 'hook)
(defcustom gptel-default-mode (if (fboundp 'markdown-mode)
'markdown-mode
'text-mode)
"The default major mode for dedicated chat buffers.
If `markdown-mode' is available, it is used. Otherwise gptel
defaults to `text-mode'."
:type 'function)
;; TODO: Handle `prog-mode' using the `comment-start' variable
(defcustom gptel-prompt-prefix-alist
'((markdown-mode . "### ")
(org-mode . "*** ")
(text-mode . "### "))
"String used as a prefix to the query being sent to the LLM.
This is meant for the user to distinguish between queries and
responses, and is removed from the query before it is sent.
This is an alist mapping major modes to the prefix strings. This
is only inserted in dedicated gptel buffers."
:type '(alist :key-type symbol :value-type string))
(defcustom gptel-response-prefix-alist
'((markdown-mode . "")
(org-mode . "")
(text-mode . ""))
"String inserted before the response from the LLM.
This is meant for the user to distinguish between queries and
responses.
This is an alist mapping major modes to the reply prefix strings. This
is only inserted in dedicated gptel buffers before the AI's response."
:type '(alist :key-type symbol :value-type string))
(defcustom gptel-highlight-assistant-responses nil
"Whether or not the assistant responses should be highlighted.
Applies only to the dedicated gptel chat buffer."
:type 'boolean
:set (lambda (symbol value)
(set-default symbol value)
(when (bound-and-true-p gptel-mode)
(if value
(progn
(font-lock-add-keywords
nil '((gptel--response-text-search 0 'gptel-response-highlight-face prepend)) t)
(font-lock-flush))
(font-lock-remove-keywords
nil '((gptel--response-text-search 0 'gptel-response-highlight-face prepend)))
(font-lock-flush)))))
(defcustom gptel-use-header-line t
"Whether `gptel-mode' should use header-line for status information.
When set to nil, use the mode line for (minimal) status
information and the echo area for messages."
:type 'boolean)
(defcustom gptel-display-buffer-action '(pop-to-buffer)
"The action used to display gptel chat buffers.
The gptel buffer is displayed in a window using
(display-buffer BUFFER gptel-display-buffer-action)
The value of this option has the form (FUNCTION . ALIST),
where FUNCTION is a function or a list of functions. Each such
function should accept two arguments: a buffer to display and an
alist of the same form as ALIST. See info node `(elisp)Choosing
Window' for details."
:type display-buffer--action-custom-type)
(defcustom gptel-crowdsourced-prompts-file
(let ((cache-dir (or (eval-when-compile
(require 'xdg)
(xdg-cache-home))
user-emacs-directory)))
(expand-file-name "gptel-crowdsourced-prompts.csv" cache-dir))
"File used to store crowdsourced system prompts.
These are prompts cached from an online source (see
`gptel--crowdsourced-prompts-url'), and can be set from the
transient menu interface provided by `gptel-menu'."
:type 'file)
;; Model and interaction parameters
(defcustom gptel-directives
'((default . "You are a large language model living in Emacs and a helpful assistant. Respond concisely.")
(programming . "You are a large language model and a careful programmer. Provide code and only code as output without any additional text, prompt or note.")
(writing . "You are a large language model and a writing assistant. Respond concisely.")
(chat . "You are a large language model and a conversation partner. Respond concisely."))
"System prompts (directives) for the LLM.
These are system instructions sent at the beginning of each
request to the LLM.
Each entry in this alist maps a symbol naming the directive to
the string that is sent. To set the directive for a chat session
interactively call `gptel-send' with a prefix argument."
:safe #'always
:type '(alist :key-type symbol :value-type string))
(defvar gptel--system-message (alist-get 'default gptel-directives)
"The system message used by gptel.")
(put 'gptel--system-message 'safe-local-variable #'always)
(defcustom gptel-max-tokens nil
"Max tokens per response.
This is roughly the number of words in the response. 100-300 is a
reasonable range for short answers, 400 or more for longer
responses.
To set the target token count for a chat session interactively
call `gptel-send' with a prefix argument."
:safe #'always
:type '(choice (natnum :tag "Specify Token count")
(const :tag "Default" nil)))
(defcustom gptel-model 'gpt-4o-mini
"GPT Model for chat.
The name of the model, as a symbol. This is the name as expected
by the LLM provider's API.
The current options for ChatGPT are
- `gpt-3.5-turbo'
- `gpt-3.5-turbo-16k'
- `gpt-4o-mini'
- `gpt-4'
- `gpt-4o'
- `gpt-4-turbo'
- `gpt-4-turbo-preview'
- `gpt-4-32k'
- `gpt-4-1106-preview'
To set the model for a chat session interactively call
`gptel-send' with a prefix argument."
:safe #'always
:type '(choice
(symbol :tag "Specify model name")
(const :tag "GPT 4 omni mini" gpt-4o-mini)
(const :tag "GPT 3.5 turbo" gpt-3.5-turbo)
(const :tag "GPT 3.5 turbo 16k" gpt-3.5-turbo-16k)
(const :tag "GPT 4" gpt-4)
(const :tag "GPT 4 omni" gpt-4o)
(const :tag "GPT 4 turbo" gpt-4-turbo)
(const :tag "GPT 4 turbo (preview)" gpt-4-turbo-preview)
(const :tag "GPT 4 32k" gpt-4-32k)
(const :tag "GPT 4 1106 (preview)" gpt-4-1106-preview)))
(defcustom gptel-temperature 1.0
"\"Temperature\" of the LLM response.
This is a number between 0.0 and 2.0 that controls the randomness
of the response, with 2.0 being the most random.
To set the temperature for a chat session interactively call
`gptel-send' with a prefix argument."
:safe #'always
:type 'number)
(defvar gptel--known-backends)
(defconst gptel--openai-models
'((gpt-4o
:description "Advanced model for complex tasks; cheaper & faster than GPT-Turbo"
:capabilities (media tool json url)
:mime-types ("image/jpeg" "image/png" "image/gif" "image/webp")
:context-window 128
:input-cost 2.50
:output-cost 10
:cutoff-date "2023-10")
(gpt-4o-mini
:description "Cheap model for fast tasks; cheaper & more capable than GPT-3.5 Turbo"
:capabilities (media tool json url)
:mime-types ("image/jpeg" "image/png" "image/gif" "image/webp")
:context-window 128
:input-cost 0.15
:output-cost 0.60
:cutoff-date "2023-10")
(gpt-4-turbo
:description "Previous high-intelligence model"
:capabilities (media tool url)
:mime-types ("image/jpeg" "image/png" "image/gif" "image/webp")
:context-window 128
:input-cost 10
:output-cost 30
:cutoff-date "2023-12")
;; points to gpt-4-0613
(gpt-4
:description "GPT-4 snapshot from June 2023 with improved function calling support"
:context-window 8.192
:input-cost 30
:output-cost 60
:cutoff-date "2023-09")
(gpt-4-turbo-preview
:description "Points to gpt-4-0125-preview"
:context-window 128
:input-cost 10
:output-cost 30
:cutoff-date "2023-12")
(gpt-4-0125-preview
:description "GPT-4 Turbo preview model intended to reduce cases of “laziness”"
:context-window 128
:input-cost 10
:output-cost 30
:cutoff-date "2023-12")
;; limited information available
(gpt-4-32k
:input-cost 60
:output-cost 120)
(gpt-4-1106-preview
:description "Preview model with improved function calling support"
:context-window 128
:input-cost 10
:output-cost 30
:cutoff-date "2023-04")
(gpt-3.5-turbo
:description "More expensive & less capable than GPT-4o-mini; use that instead"
:capabilities (tool)
:mime-types ("image/jpeg" "image/png" "image/gif" "image/webp")
:context-window 16.358
:input-cost 0.50
:output-cost 1.50
:cutoff-date "2021-09")
(gpt-3.5-turbo-16k
:description "More expensive & less capable than GPT-4o-mini; use that instead"
:mime-types ("image/jpeg" "image/png" "image/gif" "image/webp")
:context-window 16.385
:input-cost 3
:output-cost 4
:cutoff-date "2021-09"))
"List of available OpenAI models and associated properties.
Keys:
- `:description': a brief description of the model.
- `:capabilities': a list of capabilities supported by the model.
- `:mime-types': a list of supported MIME types for media files.
- `:context-window': the context window size, in thousands of tokens.
- `:input-cost': the input cost, in US dollars per million tokens.
- `:output-cost': the output cost, in US dollars per million tokens.
- `:cutoff-date': the knowledge cutoff date.
Information about the OpenAI models was obtained from the following
sources:
- <https://openai.com/pricing>
- <https://platform.openai.com/docs/models>")
(defvar gptel--openai
(gptel-make-openai
"ChatGPT"
:key 'gptel-api-key
:stream t
:models gptel--openai-models))
(defcustom gptel-backend gptel--openai
"LLM backend to use.
This is the default \"backend\", an object of type
`gptel-backend' containing connection, authentication and model
information.
A backend for ChatGPT is pre-defined by gptel. Backends for
other LLM providers (local or remote) may be constructed using
one of the available backend creation functions:
- `gptel-make-openai'
- `gptel-make-azure'
- `gptel-make-ollama'
- `gptel-make-gpt4all'
- `gptel-make-gemini'
See their documentation for more information and the package
README for examples."
:safe #'always
:type `(choice
(const :tag "ChatGPT" ,gptel--openai)
(restricted-sexp :match-alternatives (gptel-backend-p 'nil)
:tag "Other backend")))
(defvar gptel-expert-commands nil
"Whether experimental gptel options should be enabled.
This opens up advanced options in `gptel-menu'.")
(defvar-local gptel--bounds nil)
(put 'gptel--bounds 'safe-local-variable #'always)
(defvar gptel--num-messages-to-send nil)
(put 'gptel--num-messages-to-send 'safe-local-variable #'always)
(defcustom gptel-log-level nil
"Logging level for gptel.
This is one of nil or the symbols info and debug:
nil: Don't log responses
info: Log request and response bodies
debug: Log request/response bodies, headers and all other
connection settings.
When non-nil, information is logged to `gptel--log-buffer-name',
which see."
:type '(choice
(const :tag "No logging" nil)
(const :tag "Limited" info)
(const :tag "Full" debug)))
(make-obsolete-variable
'gptel--debug 'gptel-log-level "0.6.5")
(defcustom gptel-track-response t
"Distinguish between user messages and LLM responses.
When creating a prompt to send to the LLM, gptel distinguishes
between text entered by the user and past LLM responses. This
distinction is necessary for back-and-forth conversation with an
LLM.
In regular Emacs buffers you can turn this behavior off by
setting `gptel-track-response' to nil. All text, including
past LLM responses, is then treated as user input when sending
queries.
This variable has no effect in dedicated chat buffers (buffers
with `gptel-mode' enabled), where user prompts and responses are
always handled separately."
:type 'boolean)
(defcustom gptel-track-media nil
"Whether supported media in chat buffers should be sent.
When the active `gptel-model' supports it, gptel can send images
or other media from links in chat buffers to the LLM. To use
this, the following steps are required.
1. `gptel-track-media' (this variable) should be non-nil
2. The LLM should provide vision or document support. Currently,
only the OpenAI, Anthropic and Ollama APIs are supported. See
the documentation of `gptel-make-openai', `gptel-make-anthropic'
and `gptel-make-ollama' resp. for details on how to specify media
support for models.
3. Only \"standalone\" links in chat buffers are considered.
These are links on their own line with no surrounding text.
Further:
- In Org mode, only files or URLs of the form
[[/path/to/media][bracket links]] and <angle/link/path>
are sent.
- In Markdown mode, only files or URLS of the form
[bracket link](/path/to/media) and <angle/link/path>
are sent.
This option has no effect in non-chat buffers. To include
media (including images) more generally, use `gptel-add'."
:type 'boolean)
(defcustom gptel-use-context 'system
"Where in the request to inject gptel's additional context.
gptel always includes the active region or the buffer up to the
cursor in the request to the LLM. Additionally, you can add
other buffers or their regions to the context with
`gptel-add-context', or from gptel's menu. This data will be
sent with every request.
This option controls whether and where this additional context is
included in the request.
Currently supported options are:
nil - Do not use the context.
system - Include the context with the system message.
user - Include the context with the user prompt."
:group 'gptel
:type '(choice
(const :tag "Don't include context" nil)
(const :tag "With system message" system)
(const :tag "With user prompt" user)))
(defvar-local gptel--old-header-line nil)
(defvar gptel-context--alist nil
"List of gptel's context sources.
Each entry is of the form
(buffer . (overlay1 overlay2 ...))
or
(\"path/to/file\").")
;;; Utility functions
(defun gptel-api-key-from-auth-source (&optional host user)
"Lookup api key in the auth source.
By default, the LLM host for the active backend is used as HOST,
and \"apikey\" as USER."
(if-let ((secret
(plist-get
(car (auth-source-search
:host (or host (gptel-backend-host gptel-backend))
:user (or user "apikey")
:require '(:secret)))
:secret)))
(if (functionp secret)
(encode-coding-string (funcall secret) 'utf-8)
secret)
(user-error "No `gptel-api-key' found in the auth source")))
;; FIXME Should we utf-8 encode the api-key here?
(defun gptel--get-api-key (&optional key)
"Get api key from KEY, or from `gptel-api-key'."
(when-let ((key-sym (or key (gptel-backend-key gptel-backend))))
(cl-typecase key-sym
(function (funcall key-sym))
(string key-sym)
(symbol (if-let ((val (symbol-value key-sym)))
(gptel--get-api-key
(symbol-value key-sym))
(error "`gptel-api-key' is not valid")))
(t (error "`gptel-api-key' is not valid")))))
(defsubst gptel--to-number (val)
"Ensure VAL is a number."
(cond
((numberp val) val)
((stringp val) (string-to-number val))
((error "%S cannot be converted to a number" val))))
(defsubst gptel--to-string (s)
"Convert S to a string, if possible."
(cl-etypecase s
(symbol (symbol-name s))
(string s)
(number (number-to-string s))))
(defsubst gptel--intern (s)
"Intern S, if possible."
(cl-etypecase s
(symbol s)
(string (intern s))))
(defun gptel-auto-scroll ()
"Scroll window if LLM response continues below viewport.
Note: This will move the cursor."
(when-let ((win (get-buffer-window (current-buffer) 'visible))
((not (pos-visible-in-window-p (point) win)))
(scroll-error-top-bottom t))
(condition-case nil
(with-selected-window win
(scroll-up-command))
(error nil))))
(defun gptel-beginning-of-response (&optional _ _ arg)
"Move point to the beginning of the LLM response ARG times."
(interactive "p")
;; FIXME: Only works for arg == 1
(gptel-end-of-response nil nil (- (or arg 1))))
(defun gptel-end-of-response (&optional _ _ arg)
"Move point to the end of the LLM response ARG times."
(interactive (list nil nil
(prefix-numeric-value current-prefix-arg)))
(unless arg (setq arg 1))
(let ((search (if (> arg 0)
#'text-property-search-forward
#'text-property-search-backward)))
(dotimes (_ (abs arg))
(funcall search 'gptel 'response t)
(if (> arg 0)
(when (looking-at (concat "\n\\{1,2\\}"
(regexp-quote
(gptel-prompt-prefix-string))
"?"))
(goto-char (match-end 0)))
(when (looking-back (concat (regexp-quote
(gptel-response-prefix-string))
"?")
(point-min))
(goto-char (match-beginning 0)))))))
(defmacro gptel--at-word-end (&rest body)
"Execute BODY at end of the current word or punctuation."
`(save-excursion
(skip-syntax-forward "w.")
,(macroexp-progn body)))
(defun gptel-prompt-prefix-string ()
"Prefix before user prompts in `gptel-mode'."
(or (alist-get major-mode gptel-prompt-prefix-alist) ""))
(defun gptel-response-prefix-string ()
"Prefix before LLM responses in `gptel-mode'."
(or (alist-get major-mode gptel-response-prefix-alist) ""))
(defsubst gptel--trim-prefixes (s)
"Remove prompt/response prefixes from string S."
(string-trim s
(format "[\t\r\n ]*\\(?:%s\\)?[\t\r\n ]*"
(regexp-quote (gptel-prompt-prefix-string)))
(format "[\t\r\n ]*\\(?:%s\\)?[\t\r\n ]*"
(regexp-quote (gptel-response-prefix-string)))))
(defsubst gptel--link-standalone-p (beg end)
"Return non-nil if positions BEG and END are isolated.
This means the extent from BEG to END is the only non-whitespace
content on this line."
(save-excursion
(and (= beg (progn (goto-char beg) (beginning-of-line)
(skip-chars-forward "\t ")
(point)))
(= end (progn (goto-char end) (end-of-line)
(skip-chars-backward "\t ")
(point))))))
(defvar-local gptel--backend-name nil
"Store to persist backend name across Emacs sessions.
Note: Changing this variable does not affect gptel\\='s behavior
in any way.")
(put 'gptel--backend-name 'safe-local-variable #'always)
;;;; Model interface
;; NOTE: This interface would be simpler to implement as a defstruct. But then
;; users cannot set `gptel-model' to a symbol/string directly, or we'd need
;; another map from these symbols to the actual model structs.
(defsubst gptel--model-name (model)
"Get name of gptel MODEL."
(gptel--to-string model))
(defsubst gptel--model-capabilities (model)
"Get MODEL capabilities."
(get model :capabilities))
(defsubst gptel--model-mimes (model)
"Get supported mime-types for MODEL."
(get model :mime-types))
(defsubst gptel--model-capable-p (cap &optional model)
"Return non-nil if MODEL supports capability CAP."
(memq cap (gptel--model-capabilities
(or model gptel-model))))
;; TODO Handle model mime specifications like "image/*"
(defsubst gptel--model-mime-capable-p (mime &optional model)
"Return non nil if MODEL can understand MIME type."
(car-safe (member mime (gptel--model-mimes
(or model gptel-model)))))
;;;; File handling
(defun gptel--base64-encode (file)
"Encode FILE as a base64 string.
FILE is assumed to exist and be a regular file."
(with-temp-buffer
(insert-file-contents-literally file)
(base64-encode-region (point-min) (point-max)
:no-line-break)
(buffer-string)))
;;;; Response text recognition
(defun gptel--get-buffer-bounds ()
"Return the gptel response boundaries in the buffer as an alist."
(save-excursion
(save-restriction
(widen)
(goto-char (point-max))
(let ((prop) (bounds))
(while (setq prop (text-property-search-backward
'gptel 'response t))
(push (cons (prop-match-beginning prop)
(prop-match-end prop))
bounds))
bounds))))
(defun gptel--get-bounds ()
"Return the gptel response boundaries around point."
(let (prop)
(save-excursion
(when (text-property-search-backward
'gptel 'response t)
(when (setq prop (text-property-search-forward
'gptel 'response t))
(cons (prop-match-beginning prop)
(prop-match-end prop)))))))
(defun gptel--in-response-p (&optional pt)
"Check if position PT is inside a gptel response."
(get-char-property (or pt (point)) 'gptel))
(defun gptel--at-response-history-p (&optional pt)
"Check if gptel response at position PT has variants."
(get-char-property (or pt (point)) 'gptel-history))
(defvar gptel--mode-description-alist
'((js2-mode . "Javascript")
(sh-mode . "Shell")
(enh-ruby-mode . "Ruby")
(yaml-mode . "Yaml")
(yaml-ts-mode . "Yaml")
(rustic-mode . "Rust"))
"Mapping from unconventionally named major modes to languages.
This is used when generating system prompts for rewriting and
when including context from these major modes.")
(defun gptel--strip-mode-suffix (mode-sym)
"Remove the -mode suffix from MODE-SYM.
MODE-SYM is typically a major-mode symbol."
(or (alist-get mode-sym gptel--mode-description-alist)
(let ((mode-name (thread-last
(symbol-name mode-sym)
(string-remove-suffix "-mode")
(string-remove-suffix "-ts"))))
(if (provided-mode-derived-p
mode-sym 'prog-mode 'text-mode 'tex-mode)
mode-name ""))))
;;; Logging
(defconst gptel--log-buffer-name "*gptel-log*"
"Log buffer for gptel.")
(declare-function json-pretty-print "json")
(defun gptel--log (data &optional type no-json)
"Log DATA to `gptel--log-buffer-name'.
TYPE is a label for data being logged. DATA is assumed to be
Valid JSON unless NO-JSON is t."
(with-current-buffer (get-buffer-create gptel--log-buffer-name)
(let ((p (goto-char (point-max))))
(unless (bobp) (insert "\n"))
(insert (format "{\"gptel\": \"%s\", " (or type "none"))
(format-time-string "\"timestamp\": \"%Y-%m-%d %H:%M:%S\"}\n")
data)
(unless no-json (ignore-errors (json-pretty-print p (point)))))))
;;; Saving and restoring state
(defun gptel--restore-state ()
"Restore gptel state when turning on `gptel-mode'."
(when (buffer-file-name)
(if (derived-mode-p 'org-mode)
(progn
(require 'gptel-org)
(gptel-org--restore-state))
(when gptel--bounds
(mapc (pcase-lambda (`(,beg . ,end))
(put-text-property beg end 'gptel 'response))
gptel--bounds)
(message "gptel chat restored."))
(when gptel--backend-name
(if-let ((backend (alist-get
gptel--backend-name gptel--known-backends
nil nil #'equal)))