-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathgptel-request.el
More file actions
3085 lines (2633 loc) · 129 KB
/
gptel-request.el
File metadata and controls
3085 lines (2633 loc) · 129 KB
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-request.el --- LLM request library for gptel -*- lexical-binding: t; -*-
;; Copyright (C) 2023-2025 Karthik Chikmagalur
;; Author: Karthik Chikmagalur;; <karthikchikmagalur@gmail.com>
;; Keywords: convenience
;; 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/>.
;;; Commentary:
;; LLM querying library used by gptel. This file provides the basic data
;; structures (models, backends) and prompt construction functions used by
;; gptel, along with the `gptel-request' API.
;;
;; This is everything required to use `gptel-request' to write custom commands,
;; UIs or packages that use gptel to implement custom workflows. To use gptel's
;; LLM querying API, you can
;;
;; (require 'gptel-request)
;;
;; and make calls to `gptel-request'.
;;
;; Note that this file does not provide any of the UI components used by gptel
;; (chat buffers, tool use prompts, transient menus), nor does it provide the
;; default response callbacks used by `gptel-request'. You will need to provide
;; your own callback to `gptel-request' to act on the LLM response, or require
;; the larger `gptel' feature.
;;; Code:
(eval-when-compile (require 'subr-x))
(require 'compat nil t)
(require 'cl-lib)
(require 'url)
(require 'text-property-search)
(require 'cl-generic)
(require 'map)
(require 'mailcap) ;FIXME Avoid this somehow
(declare-function json-read "json" ())
(defvar json-object-type)
(declare-function gptel--stream-convert-markdown->org "gptel-org")
(declare-function gptel--convert-markdown->org "gptel-org")
(declare-function gptel-org--create-prompt-buffer "gptel-org")
(declare-function gptel-context--wrap "gptel-context")
(declare-function gptel--transform-apply-preset "gptel")
(declare-function gptel--insert-response "gptel")
(declare-function gptel-curl--stream-insert-response "gptel")
(declare-function gptel-make-openai "gptel-openai")
;;; User options
(defgroup gptel nil
"Interact with LLMs from anywhere in Emacs."
:group 'hypermedia)
(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)
(defcustom gptel-use-curl (and (executable-find "curl") t)
"Whether gptel should prefer Curl when available.
Can be set to t, nil, or a string path to the curl executable."
:type '(choice
(const :tag "Do not use Curl" nil)
(const :tag "Use Curl" t)
(string :tag "Specify path to the Curl executable")))
(defcustom gptel-org-convert-response t
"Whether gptel should convert Markdown responses to Org markup.
This only affects requests originating from Org mode buffers."
:type 'boolean)
(defcustom gptel-curl-file-size-threshold
(if (memq system-type '(windows-nt ms-dos)) #x6ffe 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.
The default of #x8000 for windows comes from Microsoft documentation
located here:
https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa
It is set to (#x8000 - #x1000 - 2) to account for other (non-data) Curl
command line arguments."
:type 'natnum)
(define-obsolete-variable-alias 'gptel-prompt-filter-hook
'gptel-prompt-transform-functions "0.9.9")
(defcustom gptel-prompt-transform-functions
'(gptel--transform-apply-preset gptel--transform-add-context)
"Handlers to augment or transform a query before sending it.
This hook is called in a temporary buffer containing the text to
be sent, with the cursor at the end of the prompt. You can use
it to modify the buffer or buffer-local variables as required.
Since these functions modify the prompt construction buffer, the order
in which they run is significant! In particular, you may want to add
your function before (the default) or after
`gptel--transform-add-context', which adds gptel's context (other
buffers, files etc) to this buffer.
Example: A typical use case might be to search for occurrences of $(cmd)
and replace it with the output of the shell command cmd, making it easy
to send the output of shell commands to the LLM.
Transform functions can be synchronous or asynchronous.
Synchronous hook functions must accept zero or one argument: the INFO
plist for the current request.
Asynchronous hook functions must accept two arguments: a callback to
call after the transformation is complete, and the INFO plist for the
current request.
Note that while this set of handlers can certainly be set with a global
value to be applied to all queries in all buffers, it meant to be set
locally for a specific buffer, or chat topic, or only the context of a
certain task."
:type 'hook)
(defcustom gptel-post-request-hook nil
"Hook run after sending a gptel request.
This runs (possibly) before any response is received."
:type 'hook)
;; TODO(v1.0): Remove this.
(defvar gptel-response-filter-functions nil)
(make-obsolete-variable
'gptel-response-filter-functions
"Response filtering is no longer supported in gptel. To toggle
markdown to Org conversion, see `gptel-org-convert-response'. To
filter LLM response text, either use `gptel-request' with a
custom callback, or use `gptel-post-response-functions'."
"0.9.7")
;; 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-response-separator "\n\n"
"String inserted before responses.
Also inserted before and after non-consecutive tool calls."
:type 'string)
;; 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 or directives for the LLM.
Each entry in this alist maps a symbol naming the directive to
the directive itself. By default, gptel uses the directive with
the key \\+`default'.
To set the directive for a chat session interactively call
`gptel-send' with a prefix argument, or call `gptel-menu'.
A \"directive\" is typically the system message (also called
system prompt or system instruction) sent at the beginning of
each request to the LLM. It is used to set general instructions,
expectations and the overall tone.
gptel's idea of the directive is more general. A directive in
`gptel-directives' can be
- A string, interpreted as the system message.
- A list of strings, whose first (possibly nil) element is
interpreted as the system message, and the remaining elements
as (possibly nil) alternating user prompts and LLM responses.
This can be used to template the initial part of a conversation.
- A function that returns a string or a list of strings,
interpreted as the above. This can be used to dynamically
generate a system message and/or conversation template based on
the current context. See the definition of
`gptel--rewrite-directive-default' for an example."
:safe #'always
:type '(alist :key-type symbol :value-type string))
(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-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 (lambda (v) (or (null v) (numberp v)))
:type '(choice (number :tag "Temperature value")
(const :tag "Use default" nil)))
(defcustom gptel-cache nil
"Whether the LLM should cache request content.
Some LLM backends can cache content sent to it by gptel, so that
only the newly included part of the text needs to be processed on
subsequent conversation turns. This results in faster and
significantly cheaper processing.
NOTE: Manual or client-configurable caching is currently
supported only by the Anthropic API and thus the
`gptel-anthropic' backend. This variable has no effect on the
behavior of other backends.
This variable controls which parts of the query will be cached,
and can be the symbols t or nil to cache everything or nothing
respectively. It can also be a list of symbols:
- message: Cache conversation messages
- system: Cache the system message
- tool: Cache tool definitions
Examples:
Setting it to (message system) will cache the system message and
the conversation text.
Setting it to (message system tool) will cache everything and is
the same as t."
:type '(choice
(const :tag "Cache everything" t)
(const :tag "Do not cache" nil)
(repeat symbol))
:group 'gptel)
(defvar gptel--known-backends nil
"Alist of LLM backends known to gptel.
This is an alist mapping user-provided names to backend structs,
see `gptel-backend'.
You can have more than one backend pointing to the same resource
with differing settings.")
(defvar gptel--openai nil)
(make-obsolete-variable 'gptel--openai "No longer used" "v0.9.9.5")
(defcustom gptel-backend nil
"LLM backend to use.
This is the default \"backend\" used by gptel, an object specifying
connection, authentication and model information required to send LLM
requests.
There are two ways to set `gptel-backend':
1. with `setopt' or the Customize interface,
2. and via constructors (such as `gptel-make-openai') in Elisp code.
When using `setopt' or the customize interface, a backend may be
specified in a list such as
(BACKEND-TYPE NAME . PLIST)
where:
BACKEND-TYPE is one of `gptel-openai' (all OpenAI-compatible
services), `gptel-anthropic', `gptel-gemini', `gptel-ollama',
`gptel-kagi', `gptel--gh' (GitHub Copilot), `gptel-bedrock' (AWS
Bedrock), `gptel-perplexity', `gptel-deepseek' or `gptel-privategpt'.
NAME is a string, any backend name of your choosing.
PLIST is an optional plist specifying connection and authentication
information, with keys
:protocol - \"http\" or \"https\"
:host - Host, such as \"api.openai.com\" or \"localhost:1616\"
:endpoint - connection endpoint, such as \"/v1/chat/completions\"
:header - HTTP header to inclue with the request, a string
or function
:key - API key, if required for authentication
String, symbol or function, see `gptel-api-key'
:models - List of supported models (symbols, see
`gptel--openai-models' for an example)
:stream - Whether to stream responses, boolean
:request-params - Additional parameters to send with backend queries, as
a plist. This plist is converted to JSON when sending.
This is meant for request parameters that gptel does not
provide user options for.
:curl-args - list of strings representing additional Curl arguments (if
`gptel-use-curl' is set)
When using the OpenAI, Anthropic, Gemini, Kagi, Github Copilot,
Perplexity or Deepseek backends, all plist keys are optional. For other
services, specifying some fields may be required. Examples:
(setopt gptel-backend \\='(gptel-openai \"OpenAI\"
:key gptel-api-key-from-auth-source
:stream t))
(setopt gptel-backend \\='(gptel-anthropic \"Claude\" :key \"sk-...\"))
(setopt gptel-backend \\='(gptel-ollama \"Ollama\"
:host \"localhost:11434\"
:models (qwen3:4b llama3.1:8b)
:stream t))
This list of keys is non-exhaustive. Some backends (such as
`gptel-bedrock') recognize or require additional keys. To see what
other keys are available, check the corresponding constructor (such as
`gptel-make-bedrock').
When not using `setopt', backends for LLM providers (local or remote)
may be constructed and registered using one of the available backend
constructor functions:
- `gptel-make-openai'
- `gptel-make-anthropic'
- `gptel-make-gemini'
- `gptel-make-ollama'
- `gptel-make-azure'
- `gptel-make-gpt4all'
- `gptel-make-kagi'
- `gptel-make-privategpt'
- `gptel-make-perplexity'
- `gptel-make-deepseek'
- `gptel-make-xai'
- `gptel-make-gh-copilot'
- `gptel-make-bedrock'
In addition, `gptel-backend' can be assigned to them. Examples:
(setq gptel-backend (gptel-make-openai \"llamacpp\"
:host \"localhost:8080\"
:protocol \"http\"
:models \\='(gpt-oss-120b glm-4.7-flash)))
(setq gptel-backend (gptel-make-gemini \"Gemini\"
:key gptel-api-key :stream t))
(setq gptel-backend (gptel-make-anthropic \"Claude-think\"
:key gptel-api-key
:request-params
\\='(:thinking (:type \"enabled\" :budget_tokens 1024)
:max_tokens 2048)))
See their documentation for more information and the package README for
examples. Once registered, backends may be retrieved using
`gptel-get-backend' or switched to interactively from gptel's menu (see
`gptel-menu')."
:safe #'always
:type
(let ((types '( choice :tag "Type"
(const :tag "OpenAI compatible" gptel-openai)
(const gptel-anthropic)
(const gptel-gemini)
(const gptel-ollama)
(const gptel-kagi)
(const :tag "GitHub Copilot" gptel-gh)
(const gptel-bedrock)
(const gptel-perplexity)
(const gptel-deepseek)
(const gptel-privategpt))))
`(choice
(restricted-sexp :match-alternatives (gptel-backend-p 'nil)
:tag "No backend")
(cons :tag "(BACKEND-TYPE NAME . PLIST)" ;accommodate (gptel-openai "chatgpt" . plist)
,types (cons string
(plist :value-type (choice string symbol function
(repeat symbol)))))
(cons :tag "(BACKEND-TYPE . PLIST)" ;accommodate (gptel-openai :name "chatgpt" . plist)
,types (plist :value-type (choice string symbol function
(repeat symbol))))))
:get
(lambda (sym)
(when-let* ((backend (default-toplevel-value sym))
(type (type-of backend))
(plist (list :protocol (gptel-backend-protocol backend)
:host (gptel-backend-host backend)
:endpoint (gptel-backend-endpoint backend)
:header (gptel-backend-header backend)
:key (gptel-backend-key backend)
:models (gptel-backend-models backend)
:stream (gptel-backend-stream backend)
:curl-args (gptel-backend-curl-args backend)
:request-params (gptel-backend-request-params backend))))
(apply #'list type (gptel-backend-name backend)
(cl-loop for (k v) on plist by #'cddr
if (and (readablep v) (not (null v)))
collect k and collect v))))
:set
(lambda (sym val)
(cond
((null val) (set-default-toplevel-value sym val))
((listp val)
(let* ((name (if (stringp (cadr val)) ;explicit and implicit :name specification
(cadr val) (plist-get (cdr val) :name)))
(args (if name (cddr val) (cdr val)))
type)
(cl-remf args :name)
(if (memq (car val) '(gptel-gh gptel--gh))
(setq type 'gptel-gh-copilot)
(setq type (car val)))
(set-default-toplevel-value
sym (apply (intern (concat "gptel-make-"
(substring (symbol-name type) 6)))
name args))))
((gptel-backend-p val) (set-default-toplevel-value sym val)))))
(defcustom gptel-model nil
(concat
"Model for gptel queries.
The name of the model, as a symbol. This is the name as expected
by the LLM provider's API.
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")
,@(cl-loop
for (_name . backend) in gptel--known-backends
append (mapcar
(lambda (model) (list 'const :tag (symbol-name model)
model))
(gptel-backend-models backend)))))
(defvar gptel-expert-commands nil
"Whether experimental gptel options should be enabled.
This opens up advanced options in `gptel-menu'.")
(defvar gptel--num-messages-to-send nil)
(put 'gptel--num-messages-to-send 'safe-local-variable #'integer-or-null-p)
(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)))
(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 links to supported media types should be followed.
When this is non-nil, gptel will send text, images or other media from
links in Org and Markdown buffers to the LLM.
Sending images or other binary media from links requires the
active `gptel-model' to support it. See `gptel-make-openai',
`gptel-make-anthropic', `gptel-make-ollama' or `gptel-make-gemini' for
details on how to specify media support for models.
To include media (including binary formats like images) more generally,
you can also use `gptel-add' or `gptel-add-file' instead."
: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)))
(defcustom gptel-include-reasoning 'ignore
"How to handle LLM reasoning or \"thinking\" text blocks.
Some LLMs include in their response a \"thinking\" section. This
text improves the quality of the LLM's final output, but may not
be interesting to you by itself.
Supported options are the symbols
ignore - Include in the response but ignore on subsequent
conversation turns (default)
t - Include in the response
nil - Do not include
It can also be a string naming a buffer, in which case the
reasoning text will be inserted at the end of that buffer."
:group 'gptel
:type '(choice
(const :tag "Include with response" t)
(const :tag "Don't include" nil)
(const :tag "Include but ignore" ignore)
(string :tag "Include in buffer")))
(define-obsolete-variable-alias 'gptel-context--alist 'gptel-context
"0.9.9.3")
(defcustom gptel-context nil
"List of gptel's context sources.
The items in this list (file names or buffers) are included with gptel
queries as additional context.
Each entry can be a file path (string) or a buffer (object, not buffer
name):
\\='(\"~/path/to/file1\"
\"./file2\"
#<buffer *scratch*>
...)
The above covers the most common cases. You can also specify context
sources in a more targeted way, with entries of the form
(<buffer> . spec)
(\"/path/to/file\" . spec)
where spec is a plist declaring specific parts of the buffer/file to
include instead of the entire text.
For buffers, you can specify regions to include using buffer spans and
line number ranges as conses, and overlays as a list:
(<buffer> :bounds ((start1 . end1) (start2 . end2) ...)
:lines ((from1 . to1) (from2 . end2) ...)
:overlays (ov1 ov2 ...))
For files, spec can include buffer spans and line number ranges, as well as
the MIME type of the file:
(\"/path/to/file\" :bounds ((start1 . end1) (start2 . end2) ...)
:lines ((from1 . to1) (from2 . end2) ...)
:mime \"image/png\")
gptel tries to guess file MIME types, but is not always successful, so
it is recommended to provide it with non-text files.
Usage of context commands (such as `gptel-add' and `gptel-add-file')
will modify this variable. You can also set this variable
buffer-locally, or let-bind it around calls to gptel queries, or via
gptel presets with the :context key."
:type '(repeat string))
(defcustom gptel-markdown-validate-link #'always
"Validate links to be sent as context with gptel queries.
When `gptel-track-media' is enabled, this option determines if a
supported link will be followed and its source included with gptel
queries from Markdown buffers. Currently only links to files are
supported (along with web URLs if the model supports them).
It should be a function that accepts a Markdown link and return non-nil
if the link should be followed. See `markdown-link-at-pos' for the
structure of a Markdown link object.
By default, all links are considered valid.
Set this to `gptel--link-standalone-p' to only follow links placed on a
line by themselves, separated from surrounding text."
:type '(choice
(const :tag "All links" always)
(const :tag "Standalone links" gptel--link-standalone-p)
(function :tag "Function"))
:group 'gptel)
(defvar gptel--request-alist nil
"Alist of active gptel requests.
Each entry has the form (PROCESS . (FSM ABORT-CLOSURE))
If the ABORT-CLOSURE is called, it must abort the PROCESS.")
(defvar gptel--request-params nil
"Extra parameters sent with each gptel request.
These parameters are combined with model-specific and backend-specific
:request-params before sending a request, which see. Warning: values
incompatible with the active backend can break gptel. Do not use this
variable unless you know what you're doing!")
(defconst gptel--ersatz-json-tool "response_json"
"Name of ersatz tool used to force JSON output.
Some APIs, like Anthropic, use a tool to produce structured JSON output.")
(defcustom gptel-curl-extra-args nil
"Extra arguments to pass to Curl when sending queries.
This should be a list of strings, each one a Curl command line
argument. Note that these should not conflict with the options
in `gptel-curl--common-args', which gptel requires for correct
functioning.
If you want to specify extra arguments only when using a specific
gptel backend, use the `:curl-args' slot of the backend instead.
See `gptel-backend'."
:group 'gptel
:type '(repeat string))
(defconst gptel-curl--common-args
(cond
((memq system-type '(windows-nt ms-dos))
'("--disable" "--location" "--silent" "-XPOST"
"-y7200" "-Y1" "-D-"))
((eq system-type 'darwin)
'("--disable" "--location" "--silent" "--compressed"
"-XPOST" "-y7200" "-Y1" "-N" "-D-"))
(t
'("--disable" "--location" "--silent" "--compressed"
"-XPOST" "-y7200" "-Y1" "-D-")))
"Arguments always passed to Curl for gptel queries.")
(defvar gptel--link-type-cache nil
"Cache of checks for binary files.
Each alist entry maps an absolute file path to a cons cell of the
form (t . binaryp), where binaryp is non-nil if the file is
binary-encoded.")
;; The following is derived from:
;;
;; (concat "\\(?:" markdown-regex-link-inline "\\|" markdown-regex-angle-uri "\\)")
;;
;; Since we want this known at compile time, when markdown-mode is not
;; guaranteed to be available, we have to hardcode it.
(defconst gptel-markdown--link-regex
"\\(?:\\(?1:!\\)?\\(?2:\\[\\)\\(?3:\\^?\\(?:\\\\\\]\\|[^]]\\)*\\|\\)\\(?4:\\]\\)\\(?5:(\\)\\s-*\\(?6:[^)]*?\\)\\(?:\\s-+\\(?7:\"[^\"]*\"\\)\\)?\\s-*\\(?8:)\\)\\|\\(<\\)\\([a-z][a-z0-9.+-]\\{1,31\\}:[^] \n<>,;()]+\\)\\(>\\)\\)"
"Link regex for `gptel-mode' in Markdown mode.")
(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")
(tuareg-mode . "OCaml"))
"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.")
;;; Utility functions
;;;; JSON parsing helpers
;; JSON conversion semantics used by gptel
;; empty object "{}" => empty list '() == nil
;; null => :null
;; false => :json-false
;; TODO(tool) Except when reading JSON from a string, where null => nil
(defmacro gptel--json-read ()
"Parse JSON at point in buffer."
(if (fboundp 'json-parse-buffer)
`(json-parse-buffer
:object-type 'plist
:null-object :null
:false-object :json-false)
(require 'json)
(defvar json-object-type)
(defvar json-null)
(declare-function json-read "json" ())
`(let ((json-object-type 'plist)
(json-null :null))
(json-read))))
(defmacro gptel--json-read-string (str)
"Pasre JSON string STR."
(if (fboundp 'json-parse-string)
`(json-parse-string ,str
:object-type 'plist
:null-object nil
:false-object :json-false)
(require 'json)
(defvar json-object-type)
(declare-function json-read-from-string "json" ())
`(let ((json-object-type 'plist))
(json-read-from-string ,str))))
(defmacro gptel--json-encode (object)
"Serialize OBJECT as JSON."
(if (fboundp 'json-serialize)
`(json-serialize ,object
:null-object :null
:false-object :json-false)
(require 'json)
(defvar json-false)
(defvar json-null)
(declare-function json-encode "json" (object))
`(let ((json-false :json-false)
(json-null :null))
(json-encode ,object))))
(defmacro gptel--maybe-funcall (func-or-sym &rest args)
"If FUNC-OR-SYM is a function, call it with ARGS.
Otherwise, evaluate it as a variable."
`(if (functionp ,func-or-sym)
;; TODO(v1.0) Remove this condition-case. This arity check is for
;; benefit of users who have personal customizations touching gptel's
;; internal API re: backend header and url functions.
(condition-case nil
(apply ,func-or-sym (list ,@args))
(wrong-number-of-arguments
(message "Displaying warning")
(display-warning
'gptel (format "%s should accept %d arguments, but accepts %d"
(if (symbolp ,func-or-sym) (format "Function %s" ,func-or-sym)
"gptel backend function")
(length ',args) (car (func-arity ,func-or-sym))))
(funcall ,func-or-sym)))
,func-or-sym))
(defun gptel--process-models (models)
"Convert items in MODELS to symbols with appropriate properties."
(let ((models-processed))
(dolist (model models)
(cl-etypecase model
(string (push (intern model) models-processed))
(symbol (push model models-processed))
(cons
(cl-destructuring-bind (name . props) model
(setf (symbol-plist name)
;; MAYBE: Merging existing symbol plists is safer, but makes it
;; difficult to reset a symbol plist, since removing keys from
;; it (as opposed to setting them to nil) is more work.
;;
;; (map-merge 'plist (symbol-plist name) props)
props)
(push name models-processed)))))
(nreverse models-processed)))
;;;; Backend interface
(defun gptel-get-backend (name)
"Return gptel backend with NAME.
Throw an error if there is no match."
(or (alist-get name gptel--known-backends nil nil #'equal)
(user-error "Backend %s is not known to be defined"
name)))
(gv-define-setter gptel-get-backend (val name)
`(setf (alist-get ,name gptel--known-backends
nil t #'equal)
,val))
(cl-defstruct
(gptel-backend (:constructor gptel--make-backend)
(:copier gptel--copy-backend))
name host header protocol stream
endpoint key models url request-params
curl-args
(coding-system
nil :documentation "Can be set to `binary' if the backend expects non UTF-8 output."))
;;;; Misc utilities
(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 (string-trim-right (funcall key-sym) "[\n\r]+"))
(string (string-trim-right key-sym "[\n\r]+"))
(symbol (if-let* ((val (symbol-value key-sym)))
(gptel--get-api-key val)
(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-typecase s
(symbol (symbol-name s))
(string s)
(otherwise (prin1-to-string s))))
(defsubst gptel--intern (s)
"Intern S, if possible."
(cl-etypecase s
(symbol s)
(string (intern s))))
(defun gptel--merge-plists (&rest plists)
"Merge PLISTS, altering the first one.
Later plists in the sequence take precedence over earlier ones."
(let (;; (rtn (copy-sequence (pop plists)))
(rtn (pop plists))
p v ls)
(while plists
(setq ls (pop plists))
(while ls
(setq p (pop ls) v (pop ls))
(setq rtn (plist-put rtn p v))))
rtn))
(defun gptel--file-binary-p (path)
"Check if file at PATH is readable and binary."
;; HACK Image files with ICC color profiles are characterized as ASCII
;; (#1223), so until we find a better solution we just match these files by
;; extension.
(or (string-match-p "\\.\\(jpe?g\\|png\\|gif\\|webp\\)\\'" path)
(condition-case nil
(with-temp-buffer
(insert-file-contents path nil 1 512 'replace)
(memq buffer-file-coding-system
'(no-conversion no-conversion-multibyte)))
(file-missing (message "File \"%s\" is not readable." path)
nil))))
(defun gptel--insert-file-string (path)
"Insert at point the contents of the file at PATH as context."
(insert (format "In file `%s`:" (abbreviate-file-name path))
"\n\n```\n")
(let ((pm (point-marker)))
(set-marker-insertion-type pm t)
(insert-file-contents path)
(goto-char pm))
(insert "\n```\n"))
(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"))))
;; NOTE: The advertised calling convention of provided-mode-derived-p
;; has changed in Emacs 30, this needs to be updated eventually
(if (provided-mode-derived-p
mode-sym 'prog-mode 'text-mode 'tex-mode)
mode-name ""))))
(defvar url-http-end-of-headers)
(defvar url-http-response-status)
(cl-defun gptel--url-retrieve (url &key method data headers)
"Retrieve URL synchronously with METHOD, DATA and HEADERS."
(declare (indent 1))
(let ((url-request-method (if (eq method 'post) "POST" "GET"))
(url-request-data (when (eq method 'post) (encode-coding-string (gptel--json-encode data) 'utf-8)))
(url-mime-accept-string "application/json")
(url-request-extra-headers
`(("content-type" . "application/json")
,@headers)))
(with-current-buffer (url-retrieve-synchronously url 'silent)
(goto-char url-http-end-of-headers)
(gptel--json-read))))