forked from s-kostyaev/ellama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathellama.el
2860 lines (2544 loc) · 98.2 KB
/
ellama.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
;;; ellama.el --- Tool for interacting with LLMs -*- lexical-binding: t -*-
;; Copyright (C) 2023-2025 Free Software Foundation, Inc.
;; Author: Sergey Kostyaev <[email protected]>
;; URL: http://github.com/s-kostyaev/ellama
;; Keywords: help local tools
;; Package-Requires: ((emacs "28.1") (llm "0.22.0") (spinner "1.7.4") (transient "0.7") (compat "29.1") (posframe "1.4.0"))
;; Version: 1.1.2
;; SPDX-License-Identifier: GPL-3.0-or-later
;; Created: 8th Oct 2023
;; This file 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 file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; Ellama is a tool for interacting with large language models from Emacs.
;; It allows you to ask questions and receive responses from the
;; LLMs. Ellama can perform various tasks such as translation, code
;; review, summarization, enhancing grammar/spelling or wording and
;; more through the Emacs interface. Ellama natively supports streaming
;; output, making it effortless to use with your preferred text editor.
;;
;;; Code:
(require 'eieio)
(require 'llm)
(require 'llm-provider-utils)
(require 'spinner)
(require 'transient)
(require 'compat)
(require 'posframe)
(eval-when-compile (require 'rx))
(defgroup ellama nil
"Tool for interacting with LLMs."
:group 'tools)
(defcustom ellama-user-nick "User"
"User nick in logs."
:group 'ellama
:type 'string)
(defcustom ellama-assistant-nick "Ellama"
"Assistant nick in logs."
:group 'ellama
:type 'string)
(defcustom ellama-nick-prefix-depth 2
"Prefix depth."
:group 'ellama
:type 'integer)
(defcustom ellama-language "English"
"Language for ellama translation."
:group 'ellama
:type 'string)
(defcustom ellama-provider
(progn
(declare-function make-llm-ollama "llm-ollama")
(require 'llm-ollama)
(make-llm-ollama
:chat-model "zephyr" :embedding-model "zephyr"))
"Backend LLM provider."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-session-remove-reasoning t
"Remove internal reasoning from the session after ellama provide an answer.
This can improve long-term communication with reasoning models."
:group 'ellama
:type 'boolean)
(defcustom ellama-output-remove-reasoning t
"Remove internal reasoning from ellama output.
Make reasoning models more useful for many cases."
:group 'ellama
:type 'boolean)
(defcustom ellama-session-hide-org-quotes t
"Hide org quotes in ellama session buffer."
:group 'ellama
:type 'boolean)
(defcustom ellama-chat-translation-enabled nil
"Enable chat translations."
:group 'ellama
:type 'boolean)
(defcustom ellama-translation-provider nil
"LLM provider for chat translation."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-summarization-provider nil
"LLM provider for summarization."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-coding-provider nil
"LLM provider for coding tasks."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-providers nil
"LLM provider list for fast switching."
:group 'ellama
:type '(alist :key-type string
:value-type (sexp :validate llm-standard-provider-p)))
(defcustom ellama-spinner-type 'progress-bar
"Spinner type for ellama."
:group 'ellama
:type `(choice ,@(mapcar
(lambda (type)
`(const ,(car type)))
spinner-types)))
(defcustom ellama-command-map
(let ((map (make-sparse-keymap)))
;; code
(define-key map (kbd "c c") 'ellama-code-complete)
(define-key map (kbd "c a") 'ellama-code-add)
(define-key map (kbd "c e") 'ellama-code-edit)
(define-key map (kbd "c i") 'ellama-code-improve)
(define-key map (kbd "c r") 'ellama-code-review)
(define-key map (kbd "c m") 'ellama-generate-commit-message)
;; summarize
(define-key map (kbd "s s") 'ellama-summarize)
(define-key map (kbd "s w") 'ellama-summarize-webpage)
(define-key map (kbd "s c") 'ellama-summarize-killring)
;; session
(define-key map (kbd "s l") 'ellama-load-session)
(define-key map (kbd "s r") 'ellama-session-rename)
(define-key map (kbd "s d") 'ellama-session-remove)
(define-key map (kbd "s a") 'ellama-session-switch)
;; improve
(define-key map (kbd "i w") 'ellama-improve-wording)
(define-key map (kbd "i g") 'ellama-improve-grammar)
(define-key map (kbd "i c") 'ellama-improve-conciseness)
(define-key map (kbd "P") 'ellama-proofread)
;; make
(define-key map (kbd "m l") 'ellama-make-list)
(define-key map (kbd "m t") 'ellama-make-table)
(define-key map (kbd "m f") 'ellama-make-format)
;; ask
(define-key map (kbd "a a") 'ellama-ask-about)
(define-key map (kbd "a i") 'ellama-chat)
(define-key map (kbd "a l") 'ellama-ask-line)
(define-key map (kbd "a s") 'ellama-ask-selection)
;; text
(define-key map (kbd "w") 'ellama-write)
(define-key map (kbd "t t") 'ellama-translate)
(define-key map (kbd "t b") 'ellama-translate-buffer)
(define-key map (kbd "t c") 'ellama-complete)
(define-key map (kbd "t e") 'ellama-chat-translation-enable)
(define-key map (kbd "t d") 'ellama-chat-translation-disable)
;; define
(define-key map (kbd "d w") 'ellama-define-word)
;; context
(define-key map (kbd "x b") 'ellama-context-add-buffer)
(define-key map (kbd "x f") 'ellama-context-add-file)
(define-key map (kbd "x s") 'ellama-context-add-selection)
(define-key map (kbd "x i") 'ellama-context-add-info-node)
(define-key map (kbd "x r") 'ellama-context-reset)
;; provider
(define-key map (kbd "p s") 'ellama-provider-select)
map)
"Keymap for ellama commands."
:group 'ellama
:type 'keymap)
(defun ellama-setup-keymap ()
"Set up the Ellama keymap and bindings."
(interactive)
(when (boundp 'ellama-keymap-prefix)
(defvar ellama-keymap (make-sparse-keymap)
"Keymap for Ellama Commands")
(when ellama-keymap-prefix
(define-key global-map (kbd ellama-keymap-prefix) ellama-command-map))))
(defcustom ellama-keymap-prefix nil
"Key sequence for Ellama Commands."
:type 'string
:set (lambda (symbol value)
(custom-set-default symbol value)
(when value
(ellama-setup-keymap)))
:group 'ellama)
(defcustom ellama-ollama-binary "ollama"
"Path to ollama binary."
:type 'string
:group 'ellama)
(defcustom ellama-auto-scroll nil
"If enabled ellama buffer will scroll automatically during generation."
:type 'boolean
:group 'ellama)
(defcustom ellama-fill-paragraphs '(text-mode)
"When to wrap paragraphs."
:group 'ellama
:type `(choice
(const :tag "Never fill paragraphs" nil)
(const :tag "Always fill paragraphs" t)
(function :tag "By predicate")
(repeat :tag "In specific modes" (symbol))))
(defcustom ellama-name-prompt-words-count 5
"Count of words in prompt to generate name."
:group 'ellama
:type 'integer)
(defcustom ellama-naming-scheme 'ellama-generate-name-by-words
"How to name sessions.
If you choose custom function, that function should accept PROVIDER, ACTION
and PROMPT arguments.
PROVIDER is an llm provider.
ACTION is a symbol, current command.
PROMPT is a prompt string."
:group 'ellama
:type `(choice
(const :tag "By first N words of prompt" ellama-generate-name-by-words)
(const :tag "By current time" ellama-generate-name-by-time)
(const :tag "By generating name with LLM based on prompt." ellama-generate-name-by-llm)
(const :tag "By generating name with reasoning LLM based on prompt." ellama-generate-name-by-reasoning-llm)
(function :tag "By custom function")))
(defcustom ellama-define-word-prompt-template "Define %s"
"Prompt template for `ellama-define-word'."
:group 'ellama
:type 'string)
(defcustom ellama-summarize-prompt-template "<INSTRUCTIONS>
You are a summarizer. You write a summary of the input **IN THE SAME
LANGUAGE AS ORIGINAL INPUT TEXT**. Summarize input text concisely and
comprehensively, ensuring all key details are included accurately.
Focus on clarity and maintain a straightforward presentation.
</INSTRUCTIONS>
<INPUT>
%s
</INPUT>"
"Prompt template for `ellama-summarize'."
:group 'ellama
:type 'string)
(defcustom ellama-code-review-prompt-template "You are professional software engineer. Review provided code and make concise suggestions."
"Prompt template for `ellama-code-review'."
:group 'ellama
:type 'string)
(defcustom ellama-change-prompt-template "Change the following text, %s, just output the final text without additional quotes around it:\n%s"
"Prompt template for `ellama-change'."
:group 'ellama
:type 'string)
(defcustom ellama-write-prompt-template "<SYSTEM>
Write text, based on provided context and instruction. Do not add any explanation or acknowledgement, just follow instruction.
</SYSTEM>
<INSTRUCTION>
%s
</INSTRUCTION>"
"Prompt template for `ellama-write'."
:group 'ellama
:type 'string)
(defcustom ellama-improve-grammar-prompt-template "improve grammar and spelling"
"Prompt template for `ellama-improve-grammar'."
:group 'ellama
:type 'string)
(defcustom ellama-improve-wording-prompt-template "use better wording"
"Prompt template for `ellama-improve-wording'."
:group 'ellama
:type 'string)
(defcustom ellama-proofread-prompt-template "proofread"
"Prompt template for `ellama-proofread'."
:group 'ellama
:type 'string)
(defcustom ellama-improve-conciseness-prompt-template "make it as simple and concise as possible"
"Prompt template for `ellama-improve-conciseness'."
:group 'ellama
:type 'string)
(defcustom ellama-code-edit-prompt-template "Regarding the following code, %s, only output the result code in format ```language\n...\n```:\n```\n%s\n```\nWrite all the code in single code block."
"Prompt template for `ellama-code-edit'."
:group 'ellama
:type 'string)
(defcustom ellama-code-improve-prompt-template "Enhance the following code, only output the result code in format ```language\n...\n```:\n```\n%s\n```\nWrite all the code in single code block."
"Prompt template for `ellama-code-improve'."
:group 'ellama
:type 'string)
(defcustom ellama-code-complete-prompt-template "Continue the following code, only write new code in format ```language\n...\n```:\n```\n%s\n```\nWrite all the code in single code block."
"Prompt template for `ellama-code-complete'."
:group 'ellama
:type 'string)
(defcustom ellama-code-add-prompt-template "Based on context, %s, only output the result in format ```\n...\n```\nWrite all the code in single code block."
"Prompt template for `ellama-code-add'."
:group 'ellama
:type 'string)
(defcustom ellama-generate-commit-message-template "<INSTRUCTIONS>
You are professional software developer.
Write concise commit message based on diff in the following format:
<FORMAT>
First line should contain short title described major change in functionality.
Then one empty line. Then detailed description of all changes.
</FORMAT>
<EXAMPLE>
Improve abc
Improved abc feature by adding new xyz module.
</EXAMPLE>
**Reply with commit message only without any quotes.**
</INSTRUCTIONS>
<DIFF>
%s
</DIFF>"
"Prompt template for `ellama-generate-commit-message'."
:group 'ellama
:type 'string)
(defcustom ellama-make-format-prompt-template "Render the following text as a %s:\n%s"
"Prompt template for `ellama-make-format'."
:group 'ellama
:type 'string)
(defcustom ellama-make-list-prompt-template "markdown list"
"Prompt template for `ellama-make-list'."
:group 'ellama
:type 'string)
(defcustom ellama-make-table-prompt-template "markdown table"
"Prompt template for `ellama-make-table'."
:group 'ellama
:type 'string)
(defcustom ellama-get-name-template "I will get you user query, you should return short topic only, what this conversation about. NEVER respond to query itself. Topic must be short and concise. Do not add additional words like 'the topic is', respond with topic only.
<example>
Query: Why is sky blue?
Topic: Blue sky
</example>
<query>
%s
</query>
Topic:
"
"Prompt template for `ellama-get-name'."
:group 'ellama
:type 'string)
(defcustom ellama-translation-template "<INSTRUCTIONS>
You are expert text translator. Translate input text to %s. Do
not explain what you are doing. Do not self reference. You are an
expert translator that will be tasked with translating and
improving the spelling/grammar/literary quality of a piece of
text. Please rewrite the translated text in your tone of voice
and writing style. Ensure that the meaning of the original text
is not changed.
</INSTRUCTIONS>
<INPUT>
%s
</INPUT>"
"Translation template."
:group 'ellama
:type 'string)
(defcustom ellama-extract-string-list-template "You are professional data extractor. Extract %s as json array of strings
<EXAMPLE>
{\"data\":[\"First element\", \"Second element\"]}
</EXAMPLE>"
"Extract string list template."
:group 'ellama
:type 'string)
(defcustom ellama-semantic-identity-template "Determine if two texts have the same meaning. If they are similar but differ in key aspects, they are not the same. Return the answer as a JSON object.
<TEXT_1>
%s
</TEXT_1>
<TEXT_2>
%s
</TEXT_2>
<EXAMPLE>
{\"same\": true}
</EXAMPLE>"
"Extract string list template."
:group 'ellama
:type 'string)
(defcustom ellama-semantic-identity-reasoning-template "Determine if two texts have the same meaning. If they are similar but differ in key aspects, they are not the same. Return the answer as a JSON object.
<CONTEXT>
%s
</CONTEXT>
<TEXT_1>
%s
</TEXT_1>
<TEXT_2>
%s
</TEXT_2>
<EXAMPLE>
{
\"think\": \"Think if texts have same meaning in provided context\",
\"same\": true
}
</EXAMPLE>"
"Extract string list template with context and reasoning."
:group 'ellama
:type 'string)
(defcustom ellama-extraction-provider nil
"LLM provider for data extraction."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-chat-done-callback nil
"Callback that will be called on ellama chat response generation done.
It should be a function with single argument generated text string."
:group 'ellama
:type 'function)
(defcustom ellama-major-mode 'org-mode
"Major mode for ellama commands."
:group 'ellama
:type 'symbol)
(defcustom ellama-long-lines-length 100
"Long lines length for fill paragraph call.
Too low value can break generated code by splitting long comment lines."
:group 'ellama
:type 'integer)
(defcustom ellama-translate-italic t
"Translate italic during markdown to org transformations."
:group 'ellama
:type 'boolean)
(defcustom ellama-session-auto-save t
"Automatically save ellama sessions if set."
:group 'ellama
:type 'boolean)
(defcustom ellama-show-quotes nil
"Show quotes in chat context."
:group 'ellama
:type 'boolean)
(defcustom ellama-chat-display-action-function nil
"Display action function for `ellama-chat'."
:group 'ellama
:type 'function)
(defcustom ellama-instant-display-action-function nil
"Display action function for `ellama-instant'."
:group 'ellama
:type 'function)
(define-minor-mode ellama-session-mode
"Minor mode for ellama session buffers."
:interactive nil
(if ellama-session-mode
(progn
(add-hook 'after-save-hook 'ellama--save-session nil t)
(add-hook 'kill-buffer-hook 'ellama--session-deactivate nil t))
(remove-hook 'kill-buffer-hook 'ellama--session-deactivate)
(remove-hook 'after-save-hook 'ellama--save-session)
(ellama--session-deactivate)))
(define-minor-mode ellama-request-mode
"Minor mode for ellama buffers with active request to llm."
:interactive nil
:keymap '(([remap keyboard-quit] . ellama--cancel-current-request-and-quit))
(if ellama-request-mode
(add-hook 'kill-buffer-hook 'ellama--cancel-current-request nil t)
(remove-hook 'kill-buffer-hook 'ellama--cancel-current-request)
(ellama--cancel-current-request)))
(defvar-local ellama--change-group nil)
(defvar-local ellama--current-request nil)
(defconst ellama--code-prefix
(rx (minimal-match
(zero-or-more anything) (literal "```") (zero-or-more anything) (+ (or "\n" "\r")))))
(defconst ellama--code-suffix
(rx (minimal-match
(literal "```") (zero-or-more anything))))
(defun ellama--code-filter (text)
"Filter code prefix/suffix from TEXT."
;; Trim left first as `string-trim' trims from the right and ends up deleting all the code.
(string-trim-right (string-trim-left text ellama--code-prefix) ellama--code-suffix))
(defun ellama--fill-long-lines (text)
"Fill long lines only in TEXT."
(if ellama-fill-paragraphs
(with-temp-buffer
(insert (propertize text 'hard t))
(let ((fill-column ellama-long-lines-length)
(use-hard-newlines t))
(fill-region (point-min) (point-max) nil t t))
(buffer-substring-no-properties (point-min) (point-max)))
text))
(defun ellama--replace-first-begin-src (text)
"Replace first begin src in TEXT."
(if (not (string-match-p (rx (literal "#+BEGIN_SRC")) text))
(replace-regexp-in-string "^[[:space:]]*```\\(\\(.\\|\n\\)*\\)" "#+BEGIN_SRC\\1" text)
text))
(defun ellama--replace-bad-code-blocks (text)
"Replace code src blocks in TEXT."
(with-temp-buffer
(insert text)
(goto-char (point-min))
;; skip good code blocks
(while (re-search-forward "#\\+BEGIN_SRC\\(.\\|\n\\)*?#\\+END_SRC" nil t))
(while (re-search-forward "#\\+END_SRC\\(\\(.\\|\n\\)*?\\)#\\+END_SRC" nil t)
(replace-match "#+BEGIN_SRC\\1#+END_SRC"))
(buffer-substring-no-properties (point-min) (point-max))))
(defun ellama--replace (from to beg end)
"Replace FROM to TO in region BEG END."
(goto-char beg)
(while (and
(> end beg)
(re-search-forward from end t))
(replace-match to)))
(defun ellama--apply-transformations (beg end)
"Apply md to org transformations for region BEG END."
;; headings
(ellama--replace "^# " "* " beg end)
(ellama--replace "^## " "** " beg end)
(ellama--replace "^### " "*** " beg end)
(ellama--replace "^#### " "**** " beg end)
(ellama--replace "^##### " "***** " beg end)
(ellama--replace "^###### " "****** " beg end)
;; bold
(ellama--replace "__\\(.+?\\)__" "*\\1*" beg end)
(ellama--replace "\\*\\*\\(.+?\\)\\*\\*" "*\\1*" beg end)
(ellama--replace "<b>\\(.+?\\)</b>" "*\\1*" beg end)
;; italic
(when ellama-translate-italic
(ellama--replace "_\\(.+?\\)_" "/\\1/" beg end))
(ellama--replace "<i>\\(.+?\\)</i>" "/\\1/" beg end)
;; underlined
(ellama--replace "<u>\\(.+?\\)</u>" "_\\1_" beg end)
;; inline code
(ellama--replace "`\\(.+?\\)`" "~\\1~" beg end)
;; lists
(ellama--replace "^\\* " "+ " beg end)
;; strikethrough
(ellama--replace "~~\\(.+?\\)~~" "+\\1+" beg end)
(ellama--replace "<s>\\(.+?\\)</s>" "+\\1+" beg end)
;; badges
(ellama--replace "\\[\\!\\[.*?\\](\\(.*?\\))\\](\\(.*?\\))" "[[\\2][file:\\1]]" beg end)
;;links
(ellama--replace "\\[\\(.*?\\)\\](\\(.*?\\))" "[[\\2][\\1]]" beg end)
;; filling long lines
(goto-char beg)
(when ellama-fill-paragraphs
(let ((fill-column ellama-long-lines-length)
(use-hard-newlines t))
(fill-region beg end nil t t))))
(defun ellama--replace-outside-of-code-blocks (text)
"Replace markdown elements in TEXT with org equivalents.
Skip code blocks and math environments."
(with-temp-buffer
(insert (propertize text 'hard t))
(goto-char (point-min))
(let (block-start
block-end
(prev-point (point-min)))
;; Process regions outside of blocks
(while (re-search-forward "\\(#\\+BEGIN_SRC\\|\\$\\$\\|\\$\\)" nil t)
(setq block-start (match-beginning 0))
(goto-char block-start)
(let ((block-type (cond ((looking-at "#\\+BEGIN_SRC") 'src)
((looking-at "\\$\\$") 'math-display)
((looking-at "\\$") 'math-inline))))
;; Apply transformations to text before the block
(ellama--apply-transformations prev-point block-start)
;; Skip over the block content
(goto-char block-start)
(setq block-end
(cond
((eq block-type 'src)
(if (re-search-forward "#\\+END_SRC" nil t) (point) (point-max)))
((eq block-type 'math-display)
(if (re-search-forward "\\$\\$.+\\$\\$" nil t) (point) (point-max)))
((eq block-type 'math-inline)
(if (re-search-forward "\\$.+\\$" nil t) (point) (point-max)))))
(when block-end
(goto-char block-end))
(setq prev-point (point))))
;; Process any remaining text after the last block
(ellama--apply-transformations prev-point (point-max)))
(prog1
(buffer-substring-no-properties (point-min) (point-max))
(kill-buffer))))
(defun ellama--translate-markdown-to-org-filter (text)
"Filter to translate code blocks from markdown syntax to org syntax in TEXT.
This filter contains only subset of markdown syntax to be good enough."
(thread-last
text
;; code blocks
(replace-regexp-in-string "^[[:space:]]*```\\(.+\\)$" "#+BEGIN_SRC \\1")
(ellama--replace-first-begin-src)
(replace-regexp-in-string "^<!-- language: \\(.+\\) -->\n```" "#+BEGIN_SRC \\1")
(replace-regexp-in-string "^[[:space:]]*```$" "#+END_SRC")
(replace-regexp-in-string "^[[:space:]]*```" "#+END_SRC\n")
(replace-regexp-in-string "```" "\n#+END_SRC\n")
(replace-regexp-in-string "<think>[\n]?" "#+BEGIN_QUOTE\n")
(replace-regexp-in-string "</think>[\n]?" "#+END_QUOTE\n")
(ellama--replace-bad-code-blocks)
(ellama--replace-outside-of-code-blocks)))
(defcustom ellama-enable-keymap t
"Enable or disable Ellama keymap."
:type 'boolean
:group 'ellama
:set (lambda (symbol value)
(custom-set-default symbol value)
(if value
(ellama-setup-keymap)
;; If ellama-enable-keymap is nil, remove the key bindings
(define-key global-map (kbd ellama-keymap-prefix) nil))))
(defcustom ellama-sessions-directory (file-truename
(file-name-concat
user-emacs-directory
"ellama-sessions"))
"Directory for saved ellama sessions."
:type 'string
:group 'ellama)
(defcustom ellama-naming-provider nil
"LLM provider for generating names."
:group 'ellama
:type '(sexp :validate llm-standard-provider-p))
(defcustom ellama-always-show-chain-steps nil
"Always show ellama chain buffers."
:type 'boolean
:group 'ellama)
(defvar-local ellama--current-session nil)
(defvar ellama--current-session-id nil)
(defvar ellama--active-sessions (make-hash-table :test #'equal))
(cl-defstruct ellama-session
"A structure represent ellama session.
ID is an unique identifier of session, string.
PROVIDER is an llm provider of session.
FILE is a path to file contains string representation of this session, string.
PROMPT is a variable contains last prompt in this session.
CONTEXT contains context for next request.
EXTRA contains additional information."
id provider file prompt context extra)
(defun ellama-get-session-buffer (id)
"Return ellama session buffer by provided ID."
(gethash id ellama--active-sessions))
(defconst ellama--forbidden-file-name-characters (rx (any "/\\?%*:|\"<>.;=")))
(defun ellama--fix-file-name (name)
"Change forbidden characters in the NAME to acceptable."
(replace-regexp-in-string
ellama--forbidden-file-name-characters
"_"
name))
(defun ellama-generate-name-by-words (provider action prompt)
"Generate name for ACTION by PROVIDER by getting first N words from PROMPT."
(let* ((cleaned-prompt (replace-regexp-in-string "/" "_" prompt))
(prompt-words (split-string cleaned-prompt)))
(string-join
(flatten-tree
(list (split-string (format "%s" action) "-")
(seq-take prompt-words ellama-name-prompt-words-count)
(if (> (length prompt-words) ellama-name-prompt-words-count)
"..."
nil)
(format "(%s)" (llm-name provider))))
" ")))
(defun ellama-get-name (prompt)
"Generate session name by LLM based on PROMPT."
(let ((provider (or ellama-naming-provider ellama-provider)))
(string-trim-right
(string-trim
(seq-first
(split-string
(llm-chat provider (llm-make-simple-chat-prompt
(format ellama-get-name-template prompt)))
"\n")))
"\\.")))
(defun ellama-remove-reasoning (text)
"Remove R1-like reasoning from TEXT."
(string-trim (replace-regexp-in-string
"<think>\\(.\\|\n\\)*</think>"
""
text)))
(defun ellama-generate-name-by-llm (provider _action prompt)
"Generate name for ellama ACTION by PROVIDER and PROMPT by LLM."
(format "%s (%s)"
(ellama-get-name prompt)
(llm-name provider)))
(defun ellama-generate-name-by-reasoning-llm (provider _action prompt)
"Generate name for ellama ACTION by PROVIDER and PROMPT by LLM."
(format "%s (%s)"
(ellama-remove-reasoning
(llm-chat (or ellama-naming-provider ellama-provider)
(llm-make-simple-chat-prompt
(format ellama-get-name-template prompt))))
(llm-name provider)))
(defun ellama-get-current-time ()
"Return string representation of current time."
(replace-regexp-in-string
"\\([0-9]\\{2\\}\\)\\([0-9]\\{2\\}\\)\\'" "\\1:\\2"
(format-time-string "%FT%T%z" (current-time))))
(defun ellama-generate-name-by-time (_provider _action _prompt)
"Generate name for ellama session by current time."
(ellama-get-current-time))
(defun ellama-generate-name (provider action prompt)
"Generate name for ellama ACTION by PROVIDER according to PROMPT."
(ellama--fix-file-name (funcall ellama-naming-scheme provider action prompt)))
(defun ellama-get-nick-prefix-for-mode ()
"Return preferred header prefix char based om the current mode.
Defaults to #, but supports `org-mode'. Depends on `ellama-major-mode'."
(let* ((prefix-char
(cond ((provided-mode-derived-p ellama-major-mode 'org-mode) ?*)
(t ?#))))
(make-string ellama-nick-prefix-depth prefix-char)))
(defun ellama-get-session-file-extension ()
"Return file extension based om the current mode.
Defaults to md, but supports org. Depends on \"ellama-major-mode.\""
(cond ((provided-mode-derived-p ellama-major-mode 'org-mode) "org")
(t "md")))
(defvar ellama--global-context nil
"Global context.")
(defun ellama-new-session (provider prompt &optional ephemeral)
"Create new ellama session with unique id.
Provided PROVIDER and PROMPT will be used in new session.
If EPHEMERAL non nil new session will not be associated with any file."
(let* ((name (ellama-generate-name provider 'ellama prompt))
(count 1)
(name-with-suffix (format "%s %d" name count))
(id (if (not (ellama-get-session-buffer name))
name
(while (ellama-get-session-buffer name-with-suffix)
(setq count (+ count 1))
(setq name-with-suffix (format "%s %d" name count)))
name-with-suffix))
(file-name (when (and (not ephemeral)
ellama-session-auto-save)
(file-name-concat
ellama-sessions-directory
(concat id "." (ellama-get-session-file-extension)))))
(previous-session
(when ellama--current-session-id
(with-current-buffer
(ellama-get-session-buffer ellama--current-session-id)
ellama--current-session)))
(session (make-ellama-session
:id id :provider provider :file file-name
:context (or (when previous-session
(ellama-session-context previous-session))
ellama--global-context)))
(buffer (if file-name
(progn
(make-directory ellama-sessions-directory t)
(find-file-noselect file-name))
(get-buffer-create id))))
(setq ellama--current-session-id id)
(puthash id buffer ellama--active-sessions)
(with-current-buffer buffer
(funcall ellama-major-mode)
(setq ellama--current-session session)
(ellama-session-mode +1))
session))
(defun ellama--cancel-current-request ()
"Cancel current running request."
(when ellama--current-request
(llm-cancel-request ellama--current-request)
(setq ellama--current-request nil)))
(defun ellama--cancel-current-request-and-quit ()
"Cancel the current request and quit."
(interactive)
(ellama--cancel-current-request)
(keyboard-quit))
(defun ellama--session-deactivate ()
"Deactivate current session."
(ellama--cancel-current-request)
(when-let* ((session ellama--current-session)
(id (ellama-session-id session)))
(when (string= (buffer-name)
(buffer-name (ellama-get-session-buffer id)))
(remhash id ellama--active-sessions)
(when (equal ellama--current-session-id id)
(setq ellama--current-session-id nil)))))
(defun ellama--get-session-file-name (file-name)
"Get ellama session file name for FILE-NAME."
(let* ((base-name (file-name-nondirectory file-name))
(dir (file-name-directory file-name))
(session-file-name
(file-name-concat
dir
(concat "." base-name ".session.el"))))
session-file-name))
(defun ellama--get-translation-file-name (file-name)
"Get ellama translation file name for FILE-NAME."
(let* ((base-name (file-name-base file-name))
(ext (file-name-extension file-name))
(dir (file-name-directory file-name))
(translation-file-name
(file-name-concat
dir
(concat base-name ".translation"
(when ext
(concat "." ext))))))
translation-file-name))
(defun ellama--save-session ()
"Save current ellama session."
(when ellama--current-session
(let* ((session ellama--current-session)
(file-name (ellama-session-file session))
(session-file-name (ellama--get-session-file-name file-name)))
(with-temp-file session-file-name
(insert (prin1-to-string session))))))
;;;###autoload
(defun ellama-load-session ()
"Load ellama session from file."
(interactive)
(when-let* ((dir (if current-prefix-arg
(read-directory-name
"Select directory containing sessions: "
ellama-sessions-directory)
ellama-sessions-directory))
(file-name (file-name-concat
ellama-sessions-directory
(completing-read
"Select session to load: "
(directory-files
ellama-sessions-directory nil "^[^\.].*"))))
(session-file-name (ellama--get-session-file-name file-name))
(session-file-exists (file-exists-p session-file-name))
(buffer (find-file-noselect file-name))
(session-buffer (find-file-noselect session-file-name)))
(with-current-buffer session-buffer
(goto-char (point-min))
;; old sessions support
(when (string= "(setq "
(buffer-substring-no-properties 1 7))
(goto-char (point-min))
;; skip "("
(forward-char)
;; skip setq
(forward-sexp)
;; skip ellama--current-session
(forward-sexp)
;; skip space
(forward-char)
;; remove all above
(kill-region (point-min) (point))
(goto-char (point-max))
;; remove ")"
(delete-char -1)
;; save session in new format
(save-buffer)
(goto-char (point-min))))
(with-current-buffer buffer
;; support sessions without user nick at the end of buffer
(when (not (save-excursion
(save-match-data
(goto-char (point-max))
(and (search-backward (concat (ellama-get-nick-prefix-for-mode) " " ellama-user-nick ":\n") nil t)
(search-forward (concat (ellama-get-nick-prefix-for-mode) " " ellama-user-nick ":\n") nil t)
(equal (point) (point-max))))))
(goto-char (point-max))
(insert (ellama-get-nick-prefix-for-mode) " " ellama-user-nick ":\n")
(save-buffer))
(let* ((session (read session-buffer))
;; workaround for old sessions
(offset (cl-struct-slot-offset 'ellama-session 'extra))
(extra (when (> (length session)
offset)
(aref session offset))))
(setq ellama--current-session
(make-ellama-session
:id (ellama-session-id session)
:provider (ellama-session-provider session)
:file (ellama-session-file session)
:prompt (ellama-session-prompt session)
:context ellama--global-context
:extra extra)))
(setq ellama--current-session-id (ellama-session-id ellama--current-session))
(puthash (ellama-session-id ellama--current-session)
buffer ellama--active-sessions)
(ellama-session-mode +1))
(kill-buffer session-buffer)
(ellama-hide-quotes)
(display-buffer buffer (when ellama-chat-display-action-function
`((ignore . (,ellama-chat-display-action-function)))))))
;;;###autoload
(defun ellama-session-remove ()
"Remove ellama session."
(interactive)
(let* ((id (completing-read
"Select session to remove: "
(hash-table-keys ellama--active-sessions)))
(buffer (ellama-get-session-buffer id))
(file (buffer-file-name buffer))
(session-file (ellama--get-session-file-name file))
(translation-file (ellama--get-translation-file-name file)))
(kill-buffer buffer)
(delete-file file t)
(delete-file session-file t)
(mapc
(lambda (buf)
(when (and (buffer-file-name buf)
(file-equal-p (buffer-file-name buf)
translation-file))
(kill-buffer buf)))
(buffer-list))
(when (file-exists-p translation-file)
(delete-file translation-file t))))
(defun ellama-activate-session (id)
"Change current active session to session with ID."
(setq ellama--current-session-id id))
;;;###autoload
(defun ellama-session-switch ()
"Change current active session."
(interactive)
(let* ((id (completing-read
"Select session to activate: "
(hash-table-keys ellama--active-sessions)))
(buffer (ellama-get-session-buffer id)))
(ellama-activate-session id)
(display-buffer buffer (when ellama-chat-display-action-function
`((ignore . (,ellama-chat-display-action-function)))))))