-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminuet.el
1195 lines (1072 loc) · 51.6 KB
/
minuet.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
;;; minuet.el --- Code completion using LLM -*- lexical-binding: t; -*-
;; Author: Milan Glacier <[email protected]>
;; Maintainer: Milan Glacier <[email protected]>
;; Version: 0.3
;; URL: https://github.com/milanglacier/minuet-ai.el
;; Package-Requires: ((emacs "29") (plz "0.9") (dash "2.19.1"))
;;; This file is NOT part of GNU Emacs
;;; License
;;
;; 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, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;; AI-powered code completion with dual modes:
;;
;; - Specialized prompts and various enhancements for chat-based LLMs
;; on code completion tasks.
;; - Fill-in-the-middle (FIM) completion for compatible models
;; (DeepSeek, Codestral, and some Ollama models).
;;
;; Minuet supports multiple AI providers (OpenAI, Claude, Gemini,
;; Codestral, Ollama, and OpenAI-compatible providers)
;;
;; You can use it with overlay-based popup via
;; `minuet-show-suggestion' or selecting the candidates via
;; `minuet-complete-with-minibuffer'. You can toggle automatic
;; suggestion popup with `minuet-auto-suggestion-mode'.
;;; Code:
(require 'plz)
(require 'dash)
(require 'cl-lib)
(defgroup minuet nil
"Minuet group."
:group 'applications)
(declare-function evil-emacs-state-p "evil-states")
(declare-function evil-insert-state-p "evil-states")
(declare-function consult--read "consult")
(declare-function consult--insertion-preview "consult")
(defcustom minuet-auto-suggestion-debounce-delay 0.4
"Debounce delay in seconds for auto-suggestions."
:type 'number
:group 'minuet)
(defcustom minuet-auto-suggestion-block-functions '(minuet-evil-not-insert-state-p)
"List of functions to determine whether auto-suggestions should be blocked.
Each function should return non-nil if auto-suggestions should be
blocked. If any function in this list returns non-nil,
auto-suggestions will not be shown."
:type '(repeat function)
:group 'minuet)
(defcustom minuet-auto-suggestion-throttle-delay 1.0
"Minimum time in seconds between auto-suggestions."
:type 'number
:group 'minuet)
(defface minuet-suggestion-face
'((t :inherit shadow))
"Face used for displaying inline suggestions.")
(defvar-local minuet--current-overlay nil
"Overlay used for displaying the current suggestion.")
(defvar-local minuet--last-point nil
"Last known cursor position for suggestion overlay.")
(defvar-local minuet--auto-last-point nil
"Last known cursor position for auto-suggestion.")
(defvar-local minuet--current-suggestions nil
"List of current completion suggestions.")
(defvar-local minuet--current-suggestion-index 0
"Index of currently displayed suggestion.")
(defvar-local minuet--current-requests nil
"List of current active request processes for this buffer.")
(defvar-local minuet--last-auto-suggestion-time nil
"Timestamp of last auto-suggestion.")
(defvar-local minuet--debounce-timer nil
"Timer for debouncing auto-suggestions.")
(defvar minuet-buffer-name "*minuet*" "The basename for minuet buffers.")
(defcustom minuet-provider 'openai-fim-compatible
"The provider to use for code completion.
Must be one of the supported providers: codestral, openai, claude, etc."
:type '(choice (const :tag "Codestral" codestral)
(const :tag "OpenAI" openai)
(const :tag "Claude" claude)
(const :tag "OpenAI Compatible" openai-compatible)
(const :tag "OpenAI FIM Compatible" openai-fim-compatible)
(const :tag "Gemini" gemini))
:group 'minuet)
(defcustom minuet-context-window 16000
"The maximum total characters of the context before and after cursor.
This limits how much surrounding code is sent to the LLM for context.
The default is 16000 characters which would roughly equate 4000
tokens."
:type 'integer
:group 'minuet)
(defcustom minuet-context-ratio 0.75
"Ratio of context before cursor vs after cursor.
When the total characters exceed the context window, this ratio
determines how much context to keep before vs after the cursor. A
larger ratio means more context before the cursor will be used."
:type 'float
:group 'minuet)
(defcustom minuet-request-timeout 3
"Maximum timeout in seconds for sending completion requests."
:type 'integer
:group 'minuet)
(defcustom minuet-add-single-line-entry t
"Whether to create additional single-line completion items.
When non-nil and a completion item has multiple lines, create another
completion item containing only its first line."
:type 'boolean
:group 'minuet)
(defcustom minuet-after-cursor-filter-length 15
"Length of context after cursor used to filter completion text.
Defines the length of non-whitespace context after the cursor used to
filter completion text. Set to 0 to disable filtering.
Example: With after_cursor_filter_length = 3 and context: \"def
fib(n):\\n|\\n\\nfib(5)\" (where | represents cursor position), if the
completion text contains \"fib\", then \"fib\" and subsequent text
will be removed. This setting filters repeated text generated by the
LLM. A large value (e.g., 15) is recommended to avoid false
positives."
:type 'integer
:group 'minuet)
(defcustom minuet-n-completions 3
"Number of completion items.
For FIM model, this is the number of requests to send. For chat LLM ,
this is the number of completions encoded as part of the prompt. Note
that when `minuet-add-single-line-entry` is true, the actual number of
returned items may exceed this value. Additionally, the LLM cannot
guarantee the exact number of completion items specified, as this
parameter serves only as a prompt guideline. The default is `3`."
:type 'integer
:group 'minuet)
(defvar minuet-default-prompt
"You are the backend of an AI-powered code completion engine. Your task is to
provide code suggestions based on the user's input. The user's code will be
enclosed in markers:
- `<contextAfterCursor>`: Code context after the cursor
- `<cursorPosition>`: Current cursor location
- `<contextBeforeCursor>`: Code context before the cursor
Note that the user's code will be prompted in reverse order: first the code
after the cursor, then the code before the cursor.
"
"The default prompt for minuet completion.")
(defvar minuet-default-guidelines
"Guidelines:
1. Offer completions after the `<cursorPosition>` marker.
2. Make sure you have maintained the user's existing whitespace and indentation.
This is REALLY IMPORTANT!
3. Provide multiple completion options when possible.
4. Return completions separated by the marker <endCompletion>.
5. The returned message will be further parsed and processed. DO NOT include
additional comments or markdown code block fences. Return the result directly.
6. Keep each completion option concise, limiting it to a single line or a few lines.
7. Create entirely new code completion that DO NOT REPEAT OR COPY any user's existing code around <cursorPosition>."
"The default guidelines for minuet completion.")
(defvar minuet-default-n-completion-template
"8. Provide at most %d completion items."
"The default prompt for minuet for number of completions request.")
(defvar minuet-default-system-template
"{{{:prompt}}}\n{{{:guidelines}}}\n{{{:n-completions-template}}}"
"The default template for minuet system template.")
(defvar minuet-default-chat-input-template
"{{{:language-and-tab}}}
<contextAfterCursor>
{{{:context-after-cursor}}}
<contextBeforeCursor>
{{{:context-before-cursor}}}<cursorPosition>"
"The default template for minuet chat input.")
(defvar minuet-default-fewshots
`((:role "user"
:content "# language: python
<contextAfterCursor>
fib(5)
<contextBeforeCursor>
def fibonacci(n):
<cursorPosition>")
(:role "assistant"
:content " '''
Recursive Fibonacci implementation
'''
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
<endCompletion>
'''
Iterative Fibonacci implementation
'''
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
<endCompletion>
")))
(defvar minuet-claude-options
`(:model "claude-3-5-sonnet-20241022"
:max_tokens 512
:api-key "ANTHROPIC_API_KEY"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots
:chat-input
(:template minuet-default-chat-input-template
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:optional nil)
"Config options for Minuet Claude provider.")
(defvar minuet-openai-options
`(:model "gpt-4o-mini"
:api-key "OPENAI_API_KEY"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots
:chat-input
(:template minuet-default-chat-input-template
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:optional nil)
"Config options for Minuet OpenAI provider.")
(defvar minuet-codestral-options
'(:model "codestral-latest"
:end-point "https://codestral.mistral.ai/v1/fim/completions"
:api-key "CODESTRAL_API_KEY"
:template (:prompt minuet--default-fim-prompt-function
:suffix minuet--default-fim-suffix-function)
:optional nil)
"Config options for Minuet Codestral provider.")
(defvar minuet-openai-compatible-options
`(:end-point "https://api.groq.com/openai/v1/chat/completions"
:api-key "GROQ_API_KEY"
:model "llama-3.3-70b-versatile"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots
:chat-input
(:template minuet-default-chat-input-template
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:optional nil)
"Config options for Minuet OpenAI compatible provider.")
(defvar minuet-openai-fim-compatible-options
'(:model "deepseek-chat"
:end-point "https://api.deepseek.com/beta/completions"
:api-key "DEEPSEEK_API_KEY"
:name "Deepseek"
:template (:prompt minuet--default-fim-prompt-function
:suffix minuet--default-fim-suffix-function)
:optional nil)
"Config options for Minuet OpenAI FIM compatible provider.")
(defvar minuet-gemini-options
`(:model "gemini-1.5-flash-latest"
:api-key "GEMINI_API_KEY"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots
:chat-input
(:template minuet-default-chat-input-template
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:optional nil)
"Config options for Minuet Gemini provider.")
(defun minuet-evil-not-insert-state-p ()
"Return non-nil if evil is loaded and not in insert or Emacs state."
(and (bound-and-true-p evil-local-mode)
(not (or (evil-insert-state-p)
(evil-emacs-state-p)))))
(defun minuet-set-optional-options (options key val &optional field)
"Set the value of KEY in the FIELD of OPTIONS to VAL.
If FIELD is not provided, it defaults to :optional. If VAL is nil,
then remove KEY from OPTIONS. This helper function simplifies setting
values in a two-level nested plist structure."
(let ((field (or field :optional)))
(if val
(setf (plist-get options field)
(plist-put (plist-get options field) key val))
(setf (plist-get options field)
(map-delete (plist-get options field) key)))))
(defun minuet--eval-value (value)
"Eval a VALUE for minuet.
If value is a function (either lambda or a callable symbol), eval the
function (with no argument) and return the result. Else if value is a
symbol, return its value. Else return itself."
(cond ((functionp value) (funcall value))
((and (symbolp value) (boundp value)) (symbol-value value))
(t value)))
(defun minuet--cancel-requests ()
"Cancel all current minuet requests for this buffer."
(when minuet--current-requests
(dolist (proc minuet--current-requests)
(when (process-live-p proc)
(minuet--log (format "%s process killed" (prin1-to-string proc)))
(delete-process proc)))
(setq minuet--current-requests nil)))
(defun minuet--cleanup-suggestion (&optional no-cancel)
"Remove the current suggestion overlay.
Also cancel any pending requests unless NO-CANCEL is t."
(unless no-cancel
(minuet--cancel-requests))
(when minuet--current-overlay
(delete-overlay minuet--current-overlay)
(setq minuet--current-overlay nil)
(minuet-active-mode -1))
(remove-hook 'post-command-hook #'minuet--on-cursor-moved t)
(setq minuet--last-point nil))
(defun minuet--cursor-moved-p ()
"Check if cursor moved from last suggestion position."
(and minuet--last-point
(not (eq minuet--last-point (point)))))
(defun minuet--on-cursor-moved ()
"Minuet event on cursor moved."
(when (minuet--cursor-moved-p)
(minuet--cleanup-suggestion)))
(defun minuet--display-suggestion (suggestions &optional index)
"Display suggestion from SUGGESTIONS at INDEX using an overlay at point."
;; we only cancel requests when cursor is moved. Because the
;; completion items may be accumulated during multiple concurrent
;; curl requests.
(minuet--cleanup-suggestion t)
(add-hook 'post-command-hook #'minuet--on-cursor-moved nil t)
(when-let* ((suggestions suggestions)
(cursor-not-moved (not (minuet--cursor-moved-p)))
(index (or index 0))
(total (length suggestions))
(suggestion (nth index suggestions))
(ov (make-overlay (point) (point))))
(setq minuet--current-suggestions suggestions
minuet--current-suggestion-index index
minuet--last-point (point))
(overlay-put ov 'after-string
(propertize
(format "%s%s"
suggestion
(if (= total minuet-n-completions 1) ""
(format " (%d/%d)" (1+ index) total)))
'face 'minuet-suggestion-face))
(overlay-put ov 'minuet t)
(setq minuet--current-overlay ov)
(minuet-active-mode 1)))
;;;###autoload
(defun minuet-next-suggestion ()
"Cycle to next suggestion."
(interactive)
(if (and minuet--current-suggestions
minuet--current-overlay)
(let ((next-index (mod (1+ minuet--current-suggestion-index)
(length minuet--current-suggestions))))
(minuet--display-suggestion minuet--current-suggestions next-index))
(minuet-show-suggestion)))
;;;###autoload
(defun minuet-previous-suggestion ()
"Cycle to previous suggestion."
(interactive)
(if (and minuet--current-suggestions
minuet--current-overlay)
(let ((prev-index (mod (1- minuet--current-suggestion-index)
(length minuet--current-suggestions))))
(minuet--display-suggestion minuet--current-suggestions prev-index))
(minuet-show-suggestion)))
;;;###autoload
(defun minuet-show-suggestion ()
"Show code suggestion using overlay at point."
(interactive)
(minuet--cleanup-suggestion)
(setq minuet--last-point (point))
(let ((current-buffer (current-buffer))
(available-p-fn (intern (format "minuet--%s-available-p" minuet-provider)))
(complete-fn (intern (format "minuet--%s-complete" minuet-provider)))
(context (minuet--get-context)))
(unless (funcall available-p-fn)
(minuet--log (format "Minuet provider %s is not available" minuet-provider))
(error "Minuet provider %s is not available" minuet-provider))
(funcall complete-fn
context
(lambda (items)
(setq items (-distinct items))
(with-current-buffer current-buffer
(when (and items (not (minuet--cursor-moved-p)))
(minuet--display-suggestion items 0)))))))
(defun minuet--log (message &optional message-p)
"Log minuet messages into `minuet-buffer-name'.
Also print the MESSAGE when MESSAGE-P is t."
(with-current-buffer (get-buffer-create minuet-buffer-name)
(goto-char (point-max))
(insert (format "%s %s\n" message (format-time-string "%Y-%02m-%02d %02H:%02M:%02S")))
(when message-p
(message "%s" message))))
(defun minuet--add-tab-comment ()
"Add comment string for tab use into the prompt."
(if-let* ((language-p (derived-mode-p 'prog-mode 'text-mode 'conf-mode))
(commentstring (format "%s %%s%s"
(or (replace-regexp-in-string "^%" "%%" comment-start) "#")
(or comment-end ""))))
(if indent-tabs-mode
(format commentstring "indentation: use \t for a tab")
(format commentstring (format "indentation: use %d spaces for a tab" tab-width)))
""))
(defun minuet--add-language-comment ()
"Add comment string for language use into the prompt."
(if-let* ((language-p (derived-mode-p 'prog-mode 'text-mode 'conf-mode))
(mode (symbol-name major-mode))
(mode (replace-regexp-in-string "-ts-mode" "" mode))
(mode (replace-regexp-in-string "-mode" "" mode))
(commentstring (format "%s %%s%s"
(or (replace-regexp-in-string "^%" "%%" comment-start) "#")
(or comment-end ""))))
(format commentstring (concat "language: " mode))
""))
(defun minuet--add-single-line-entry (data)
"Add single line entry into the DATA."
(cl-loop
for item in data
when (stringp item)
append (list (car (split-string item "\n"))
item)))
(defun minuet--remove-spaces (items)
"Remove trailing and leading spaces in each item in ITEMS."
;; emacs use \\` and \\' to match the beginning/end of the string,
;; ^ and $ are used to match bol or eol
(setq items (mapcar (lambda (x)
(if (or (equal x "")
(string-match "\\`[\s\t\n]+\\'" x))
nil
(setq x (replace-regexp-in-string "[\s\t\n]+\\'" "" x)
x (replace-regexp-in-string "\\`[\s\t\n]+" "" x))))
items)
items (seq-filter #'identity items))
items)
(defun minuet--get-context ()
"Get the context for minuet completion."
(let* ((point (point))
(n-chars-before point)
(point-max (point-max))
(n-chars-after (- point-max point))
(before-start (point-min))
(after-end point-max)
(is-incomplete-before nil)
(is-incomplete-after nil))
;; Calculate context window boundaries before extracting text
(when (>= (+ n-chars-before n-chars-after) minuet-context-window)
(cond ((< n-chars-before (* minuet-context-ratio minuet-context-window))
;; If context before cursor does not exceed context-window,
;; only limit after-cursor content
(setq after-end (+ point (- minuet-context-window n-chars-before))
is-incomplete-after t))
((< n-chars-after (* (- 1 minuet-context-ratio) minuet-context-window))
;; If context after cursor does not exceed context-window,
;; limit before-cursor content
(setq before-start (- point (- minuet-context-window n-chars-after))
is-incomplete-before t))
(t
;; At middle of file, use ratio to determine both boundaries
(setq is-incomplete-before t
is-incomplete-after t
after-end (+ point (floor (* minuet-context-window (- 1 minuet-context-ratio))))
before-start (+ (point-min)
(max 0 (- n-chars-before
(floor (* minuet-context-window minuet-context-ratio)))))))))
`(:before-cursor ,(buffer-substring-no-properties before-start point)
:after-cursor ,(buffer-substring-no-properties point after-end)
:language-and-tab ,(format "%s\n%s" (minuet--add-language-comment) (minuet--add-tab-comment))
:is-incomplete-before ,is-incomplete-before
:is-incomplete-after ,is-incomplete-after)))
(defun minuet--make-chat-llm-shot (context options)
"Build the final chat input for chat llm.
CONTEXT is read from current buffer content.
OPTIONS should be the provider options plist."
(let* ((chat-input (copy-tree (plist-get options :chat-input)))
(template (minuet--eval-value (plist-get chat-input :template)))
(parts nil))
;; Remove template from options to avoid infinite recursion
(setq chat-input (plist-put chat-input :template nil))
;; Use cl-loop for better control flow
(cl-loop with last-pos = 0
for match = (string-match "{{{\\(.+?\\)}}}" template last-pos)
until (not match)
for start-pos = (match-beginning 0)
for end-pos = (match-end 0)
for key = (match-string 1 template)
do
;; Add text before placeholder
(when (> start-pos last-pos)
(push (substring template last-pos start-pos) parts))
;; Get and add replacement value
(when-let* ((repl-fn (plist-get chat-input (intern key)))
(value (funcall repl-fn context)))
(push value parts))
(setq last-pos end-pos)
finally
;; Add remaining text after last match
(push (substring template last-pos) parts))
;; Join parts in reverse order
(apply #'concat (nreverse parts))))
(defun minuet--make-context-filter-sequence (context len)
"Create a filtering string based on CONTEXT with maximum length LEN."
(if-let* ((is-string (stringp context))
(is-positive (> len 0))
(context (replace-regexp-in-string "\\`[\s\t\n]+" "" context))
(should-filter (>= (length context) len))
(context (substring context 0 len))
(context (replace-regexp-in-string "[\s\t\n]+\\'" "" context)))
context
""))
(defun minuet--filter-text (text sequence)
"Remove the SEQUENCE and the rest part from TEXT."
(cond
((or (null sequence) (null text)) text)
((equal sequence "") text)
(t
(let ((start (string-match-p (regexp-quote sequence) text)))
(if start
(substring text 0 start)
text)))))
(defun minuet--filter-sequence-in-items (items sequence)
"For each item in ITEMS, apply `minuet--filter-text' with SEQUENCE."
(mapcar (lambda (x) (minuet--filter-text x sequence))
items))
(defun minuet--filter-context-sequence-in-items (items context)
"Apply the filter sequence in each item in ITEMS.
The filter sequence is obtained from CONTEXT."
(minuet--filter-sequence-in-items
items (minuet--make-context-filter-sequence
(plist-get context :after-cursor)
minuet-after-cursor-filter-length)))
(defun minuet--stream-decode (response get-text-fn)
"Decode the RESPONSE using GET-TEXT-FN."
(setq response (split-string response "[\r]?\n"))
(let (result)
(dolist (line response)
(if-let* ((json (condition-case _
(json-parse-string
(replace-regexp-in-string "^data: " "" line)
:object-type 'plist :array-type 'list)
(error nil)))
(text (condition-case _
(funcall get-text-fn json)
(error nil))))
(when (and (stringp text)
(not (equal text "")))
(setq result `(,@result ,text)))))
(setq result (apply #'concat result))
(if (equal result "")
(progn (minuet--log (format "Minuet returns no text for streaming: %s" response))
nil)
result)))
(defmacro minuet--make-process-stream-filter (response)
"Store the data into RESPONSE which is a plain list."
`(lambda (proc text)
(funcall #'internal-default-process-filter proc text)
;; (setq ,response (append ,response (list text)))
(push text ,response)))
(defun minuet--stream-decode-raw (response get-text-fn)
"Decode the raw stream used by minuet.
RESPONSE will be stored in the temp variable create by
`minuet--make-process-stream-filter' parsed by GET-TEXT-FN."
(when-let* ((response (nreverse response))
(response (apply #'concat response)))
(minuet--stream-decode response get-text-fn)))
(defun minuet--handle-chat-completion-timeout (context err response get-text-fn name callback)
"Handle the timeout error for chat completion.
This function will decode and send the partial complete response to
the callback, and log the error. CONTEXT, ERR, RESPONSE, GET-TEXT-FN,
NAME, CALLBACK are used to deliver partial completion items and log
the errors."
(if (equal (car (plz-error-curl-error err)) 28)
(progn
(minuet--log (format "%s Request timeout" name))
(when-let* ((result (minuet--stream-decode-raw response get-text-fn))
(completion-items (minuet--parse-completion-itmes-default result))
(completion-items (minuet--filter-context-sequence-in-items
completion-items
context))
(completion-items (minuet--remove-spaces completion-items)))
(funcall callback completion-items)))
(minuet--log (format "An error occured when sending request to %s" name))
(minuet--log err)))
(defmacro minuet--with-temp-response (&rest body)
"Execute BODY with a temporary response collection.
This macro creates a local variable `--response--' that can be used to
collect process output within the BODY. It's designed to work in
conjunction with `minuet--make-process-stream-filter'. The
`--response--' variable is initialized as an empty list and can be
used to accumulate text output from a process. After execution,
`--response--' will contain the collected responses in reverse order."
`(let (--response--) ,@body))
;;;###autoload
(defun minuet-accept-suggestion ()
"Accept the current overlay suggestion."
(interactive)
(when (and minuet--current-suggestions
minuet--current-overlay)
(let ((suggestion (nth minuet--current-suggestion-index
minuet--current-suggestions)))
(minuet--cleanup-suggestion)
(insert suggestion))))
;;;###autoload
(defun minuet-dismiss-suggestion ()
"Dismiss the current overlay suggestion."
(interactive)
(minuet--cleanup-suggestion))
;;;###autoload
(defun minuet-accept-suggestion-line (&optional n)
"Accept N lines of the current suggestion.
When called interactively with a numeric prefix argument, accept that
many lines. Without a prefix argument, accept only the first line."
(interactive "p")
(when (and minuet--current-suggestions
minuet--current-overlay)
(let* ((suggestion (nth minuet--current-suggestion-index
minuet--current-suggestions))
(lines (split-string suggestion "\n"))
(n (or n 1))
(selected-lines (seq-take lines n)))
(minuet--cleanup-suggestion)
(insert (string-join selected-lines "\n")))))
;;;###autoload
(defun minuet-complete-with-minibuffer ()
"Complete using minibuffer interface."
(interactive)
(let ((current-buffer (current-buffer))
(available-p-fn (intern (format "minuet--%s-available-p" minuet-provider)))
(complete-fn (intern (format "minuet--%s-complete" minuet-provider)))
(context (minuet--get-context))
(completing-read (lambda (items) (completing-read "Complete: " items nil t)))
(consult--read (lambda (items)
(consult--read
items
:prompt "Complete: "
:require-match t
:state (consult--insertion-preview (point) (point))))))
(unless (funcall available-p-fn)
(minuet--log (format "Minuet provider %s is not available" minuet-provider))
(error "Minuet provider %s is not available" minuet-provider))
(funcall complete-fn
context
(lambda (items)
(with-current-buffer current-buffer
(setq items (if minuet-add-single-line-entry
(minuet--add-single-line-entry items)
items)
items (-distinct items))
;; close current minibuffer session, if any
(when (active-minibuffer-window)
(abort-recursive-edit))
(when-let* ((items)
(selected (funcall
(if (require 'consult nil t) consult--read completing-read)
items)))
(unless (string-empty-p selected)
(insert selected))))))))
(defun minuet--get-api-key (api-key)
"Get the api-key from API-KEY.
API-KEY can be a string (as an environment variable) or a function.
Return nil if not exists or is an empty string."
(let ((key (if (stringp api-key)
(getenv api-key)
(when (functionp api-key)
(funcall api-key)))))
(when (or (null key)
(string-empty-p key))
(minuet--log
(if (stringp api-key)
(format "%s is not a valid environment variable.
If using ollama you can just set it to 'TERM'." api-key)
"The api-key function returns nil or returns an empty string")))
(and (not (equal key "")) key)))
(defun minuet--codestral-available-p ()
"Check if codestral if available."
(minuet--get-api-key (plist-get minuet-codestral-options :api-key)))
(defun minuet--openai-available-p ()
"Check if openai if available."
(minuet--get-api-key (plist-get minuet-openai-options :api-key)))
(defun minuet--claude-available-p ()
"Check if claude is available."
(minuet--get-api-key (plist-get minuet-claude-options :api-key)))
(defun minuet--openai-compatible-available-p ()
"Check if the specified openai-compatible service is available."
(when-let* ((options minuet-openai-compatible-options)
(env-var (plist-get options :api-key))
(end-point (plist-get options :end-point))
(model (plist-get options :model)))
(minuet--get-api-key env-var)))
(defun minuet--openai-fim-compatible-available-p ()
"Check if the specified openai-fim-compatible service is available."
(when-let* ((options minuet-openai-fim-compatible-options)
(env-var (plist-get options :api-key))
(name (plist-get options :name))
(end-point (plist-get options :end-point))
(model (plist-get options :model)))
(minuet--get-api-key env-var)))
(defun minuet--gemini-available-p ()
"Check if gemini is available."
(minuet--get-api-key (plist-get minuet-gemini-options :api-key)))
(defun minuet--parse-completion-itmes-default (items)
"Parse ITEMS into a list of completion entries."
(split-string items "<endCompletion>"))
(defun minuet--make-system-prompt (template &optional n-completions)
"Create system prompt used in chat LLM from TEMPLATE and N-COMPLETIONS."
(let* ((tmpl (plist-get template :template))
(tmpl (minuet--eval-value tmpl))
(n-completions (or n-completions minuet-n-completions 1))
(n-completions-template (plist-get template :n-completions-template))
(n-completions-template (minuet--eval-value n-completions-template))
(n-completions-template (if (stringp n-completions-template)
(format n-completions-template n-completions)
"")))
(setq tmpl (replace-regexp-in-string "{{{:n-completions-template}}}"
n-completions-template
tmpl))
(map-do
(lambda (k v)
(setq v (minuet--eval-value v))
(when (and (not (equal k :template))
(not (equal k :n-completions-template))
(stringp v))
(setq tmpl
(replace-regexp-in-string
(concat "{{{" (symbol-name k) "}}}")
v
tmpl))))
template)
;; replace placeholders that are not replaced
(setq tmpl (replace-regexp-in-string "{{{.*}}}"
""
tmpl))
tmpl))
(defun minuet--openai-fim-complete-base (options get-text-fn context callback)
"The base function to complete code with openai fim API.
OPTIONS are the provider options. GET-TEXT-FN are the function to get
the completion items from json. CONTEXT is to be used to build the
prompt. CALLBACK is the function to be called when completion items
arrive."
(let ((total-try (or minuet-n-completions 1))
(name (plist-get options :name))
(body (json-serialize
`(,@(plist-get options :optional)
:stream t
:model ,(plist-get options :model)
:prompt ,(funcall (--> options
(plist-get it :template)
(plist-get it :prompt))
context)
,@(when-let* ((suffix-fn (--> options
(plist-get it :template)
(plist-get it :suffix))))
(list :suffix (funcall suffix-fn context))))))
completion-items)
(dotimes (_ total-try)
(minuet--with-temp-response
(push
(plz 'post (plist-get options :end-point)
:headers `(("Content-Type" . "application/json")
("Accept" . "application/json")
("Authorization" . ,(concat "Bearer " (minuet--get-api-key (plist-get options :api-key)))))
:timeout minuet-request-timeout
:body body
:as 'string
:filter (minuet--make-process-stream-filter --response--)
:then
(lambda (json)
(when-let* ((result (minuet--stream-decode json get-text-fn)))
;; insert the current result into the completion items list
(push result completion-items))
(setq completion-items (minuet--filter-context-sequence-in-items
completion-items
context))
(setq completion-items (minuet--remove-spaces completion-items))
(funcall callback completion-items))
:else
(lambda (err)
(if (equal (car (plz-error-curl-error err)) 28)
(progn
(minuet--log (format "%s Request timeout" name))
(when-let* ((result (minuet--stream-decode-raw --response-- get-text-fn)))
(push result completion-items)))
(minuet--log (format "An error occured when sending request to %s" name))
(minuet--log err))
(setq completion-items
(minuet--filter-context-sequence-in-items
completion-items
context))
(setq completion-items (minuet--remove-spaces completion-items))
(funcall callback completion-items)))
minuet--current-requests)))))
(defun minuet--codestral-complete (context callback)
"Complete code with codestral.
CONTEXT and CALLBACK will be passed to the base function."
(minuet--openai-fim-complete-base
(plist-put (copy-tree minuet-codestral-options) :name "Codestral")
#'minuet--openai-get-text-fn
context
callback))
(defun minuet--openai-fim-compatible-complete (context callback)
"Complete code with openai fim API.
CONTEXT and CALLBACK will be passed to the base function."
(minuet--openai-fim-complete-base
(copy-tree minuet-openai-fim-compatible-options)
#'minuet--openai-fim-get-text-fn
context
callback))
(defun minuet--openai-fim-get-text-fn (json)
"Function to get the completion from a JSON object for openai-fim compatible."
(--> json
(plist-get it :choices)
car
(plist-get it :text)))
(defun minuet--openai-get-text-fn (json)
"Function to get the completion from a JSON object for openai compatible service."
(--> json
(plist-get it :choices)
car
(plist-get it :delta)
(plist-get it :content)))
(defun minuet--openai-complete-base (options context callback)
"The base function to complete code with openai API.
OPTIONS are the provider options. the completion items from json.
CONTEXT is to be used to build the prompt. CALLBACK is the function
to be called when completion items arrive."
(minuet--with-temp-response
(push
(plz 'post (plist-get options :end-point)
:headers
`(("Content-Type" . "application/json")
("Accept" . "application/json")
("Authorization" . ,(concat "Bearer " (minuet--get-api-key (plist-get options :api-key)))))
:timeout minuet-request-timeout
:body
(json-serialize
`(,@(plist-get options :optional)
:stream t
:model ,(plist-get options :model)
:messages ,(vconcat
`((:role "system"
:content ,(minuet--make-system-prompt (plist-get options :system)))
,@(minuet--eval-value (plist-get options :fewshots))
(:role "user"
:content ,(minuet--make-chat-llm-shot context options))))))
:as 'string
:filter (minuet--make-process-stream-filter --response--)
:then
(lambda (json)
(when-let* ((result (minuet--stream-decode json #'minuet--openai-get-text-fn))
(completion-items (minuet--parse-completion-itmes-default result))
(completion-items (minuet--filter-context-sequence-in-items
completion-items
context))
(completion-items (minuet--remove-spaces completion-items)))
;; insert the current result into the completion items list
(funcall callback completion-items)))
:else
(lambda (err)
(minuet--handle-chat-completion-timeout
context err --response-- #'minuet--openai-get-text-fn "OpenAI" callback)))
minuet--current-requests)))
(defun minuet--openai-complete (context callback)
"Complete code with OpenAI.
CONTEXT and CALLBACK will be passed to the base function."
(minuet--openai-complete-base
(--> (copy-tree minuet-openai-options)
(plist-put it :end-point "https://api.openai.com/v1/chat/completions"))
context callback))
(defun minuet--openai-compatible-complete (context callback)
"Complete code with OpenAI compatible service.
CONTEXT and CALLBACK will be passed to the base function."
(minuet--openai-complete-base
(copy-tree minuet-openai-compatible-options) context callback))
(defun minuet--claude-get-text-fn (json)
"Function to get the completion from a JSON object for claude."
(--> json
(plist-get it :delta)
(plist-get it :text)))
(defun minuet--claude-complete (context callback)
"Complete code with Claude.
CONTEXT is to be used to build the prompt. CALLBACK is the function
to be called when completion items arrive."