-
Notifications
You must be signed in to change notification settings - Fork 4
/
elisa.el
1462 lines (1335 loc) · 48.4 KB
/
elisa.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
;;; elisa.el --- Emacs Lisp Information System Assistant -*- lexical-binding: t -*-
;; Copyright (C) 2024 Free Software Foundation, Inc.
;; Author: Sergey Kostyaev <[email protected]>
;; URL: http://github.com/s-kostyaev/elisa
;; Keywords: help local tools
;; Package-Requires: ((emacs "29.2") (ellama "0.11.2") (llm "0.9.1") (async "1.9.8") (plz "0.9"))
;; Version: 1.1.1
;; SPDX-License-Identifier: GPL-3.0-or-later
;; Created: 18th Feb 2024
;; 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:
;;
;; ELISA (Emacs Lisp Information System Assistant) is a system
;; designed to generate informative answers to user queries using a
;; Retrieval Augmented Generation (RAG) approach. RAG combines the
;; capabilities of Large Language Models (LLMs) with Information
;; Retrieval (IR) techniques to enhance the accuracy and relevance of
;; generated responses.
;;
;; ELISA addresses limitations inherent in purely LLM-based systems by:
;;
;; - Leveraging External Knowledge: Unlike LLMs trained on a fixed
;; dataset, ELISA can access and process information from external
;; knowledge sources, expanding its knowledge base beyond its initial
;; training data.
;;
;; - Reducing Computational Requirements: Instead of
;; retraining the entire LLM for new information, ELISA focuses on
;; retrieving relevant data, minimizing computational resources
;; required for query processing.
;;
;; - Minimizing Hallucinations: By grounding responses in factual
;; data retrieved from external sources, ELISA aims to reduce the
;; likelihood of generating incorrect or nonsensical information
;; (hallucinations) often associated with LLMs.
;;
;; The following sections will detail the key components and processes
;; involved in ELISA's operation: parsing, retrieval, augmentation,
;; and generation.
;;
;; Parsing.
;;
;; Simple solution is split text document into chunks by length with
;; overlap and save it to storage. In ELISA we use more advanced
;; solution. Instead of split by length we split text by semantic
;; distances between parts of text document. To store this chunks we
;; use sqlite database.
;;
;; Retrieving.
;;
;; Simple solution is to extract top K chunks by semantic similarity
;; from storage. To improve quality we use more robust solution.
;;
;; Before going to storage we let LLM rewrite user query to make it
;; context agnostic. For example, user ask LLM about llamas, LLM
;; answer. Then user ask "where it lives?". If we try to search for
;; this query we barely find something useful. But LLM can rewrite it
;; to something like "where llamas lives?" and we will find useful
;; information.
;;
;; Instead of use simple semantic similarity search only we use hybrid
;; search. It means that ELISA search relevant chunks by semantic
;; similarity and by full text search and then combine results.
;;
;; To improve relevance even more instead of use top K results from
;; hybrid search user can enable reranker. Reranker is a service that
;; gives user query, top N chunks and feed it to reranker model. This
;; model gives pairs of text: user query and text chunk and return
;; number that means relevance. Service collect this results and sort
;; it by relevance. Also if reranker enabled ELISA filter out
;; irrelevant results.
;;
;; Augmentation.
;;
;; ELISA gets text retrieved in previous step and put it into context.
;; This context later will be sent to LLM together with user query.
;;
;; Generation.
;;
;; To improve generation quality to user query will be added
;; instructions to LLM how to answer. We let LLM ability to say "not
;; enough data" instead of hallucinations. LLM generates answer based
;; on context, instructions and user query.
;;; Code:
(require 'ellama)
(require 'llm)
(require 'llm-provider-utils)
(require 'info)
(require 'async)
(require 'dom)
(require 'shr)
(require 'plz)
(require 'json)
(defgroup elisa nil
"RAG implementation for `ellama'."
:group 'tools)
(defcustom elisa-embeddings-provider (progn (require 'llm-ollama)
(make-llm-ollama
:embedding-model "nomic-embed-text"))
"Embeddings provider to generate embeddings."
:type '(sexp :validate 'llm-standard-provider-p))
(defcustom elisa-chat-provider (progn (require 'llm-ollama)
(make-llm-ollama
:chat-model "sskostyaev/openchat:8k-rag"
:embedding-model "nomic-embed-text"))
"Chat provider."
:type '(sexp :validate 'llm-standard-provider-p))
(defcustom elisa-db-directory (file-truename
(file-name-concat
user-emacs-directory "elisa"))
"Directory for elisa database."
:type 'directory)
(defcustom elisa-limit 5
"Count quotes to pass into llm context for answer."
:type 'natnum)
(defcustom elisa-find-executable find-program
"Path to find executable."
:type 'string)
(defcustom elisa-tar-executable "tar"
"Path to tar executable."
:type 'string)
(defcustom elisa-sqlite-vss-version "v0.1.2"
"Sqlite VSS version."
:type 'string)
(defcustom elisa-sqlite-vss-path nil
"Path to sqlite-vss extension."
:type 'file)
(defcustom elisa-sqlite-vector-path nil
"Path to sqlite-vector extension."
:type 'file)
(defcustom elisa-semantic-split-function #'elisa-split-by-paragraph
"Function for semantic text split."
:type 'function)
(defcustom elisa-prompt-rewriting-enabled t
"Enable prompt rewriting for better retrieving."
:type 'boolean)
(defcustom elisa-chat-prompt-template
"Answer user query based on context above. \
If you can answer it partially do it. \
Provide list of open questions if any. \
Say \"not enough data\" if you can't answer user \
query based on provided context. User query:
%s"
"Chat prompt template.
Contains instructions to LLM to be more focused on data in
context, be able to say \"I don't know\" etc. User query will be
inserted at the end and all this result prompt will be sent to
LLM together with context."
:type 'string)
(defcustom elisa-rewrite-prompt-template
"<INSTRUCTIONS>
You are professional search agent. With given context and user
prompt you need to create new prompt for search **IN THE SAME
LANGUAGE AS ORIGINAL USER PROMPT**. It should be concise and
useful without additional context. Response with prompt only. You
should replace all words like 'this' or 'it' to its values to
make search successful. If user prompt contains question your
prompt should also be in form of question.
</INSTRUCTIONS>
<EXAMPLE>
- What is pony?
- Pony is ...
- How to buy it?
How to buy a pony?
</EXAMPLE>
<USER_PROMPT>
%s
</USER_PROMPT>"
"Prompt template for prompt rewriting."
:type 'string)
(defcustom elisa-tika-url "http://localhost:9998/"
"Apache tika url for file parsing."
:type 'string)
(defcustom elisa-searxng-url "http://localhost:8080/"
"Searxng url for web search. Json format should be enabled for this instance."
:type 'string)
(defcustom elisa-pandoc-executable "pandoc"
"Path to pandoc (https://pandoc.org/) executable."
:type 'string)
(defcustom elisa-webpage-extraction-function #'elisa-get-webpage-buffer
"Function to get buffer with webpage content."
:type 'function)
(defcustom elisa-complex-file-extraction-function #'elisa-parse-with-tika-buffer
"Function to get buffer with complex file (like pdf, odt etc.) content."
:type 'function)
(defcustom elisa-web-search-function #'elisa-search-duckduckgo
"Function to search the web.
Function should get prompt and return list of urls."
:type 'function)
(defcustom elisa-web-pages-limit 10
"Limit of web pages to parse during web search."
:type 'natnum)
(defcustom elisa-breakpoint-threshold-amount 0.4
"Breakpoint threshold amount.
Increase it if you need decrease semantic split granularity."
:type 'number)
(defcustom elisa-reranker-enabled nil
"Enable reranker to improve retrieving quality.
Reranker is a service to improve answer quality by mesure
relevance of text chunks to user query and sort chunks by
relevance. See https://github.com/s-kostyaev/reranker for more
details."
:type 'boolean)
(defcustom elisa-reranker-url "http://127.0.0.1:8787/"
"Reranker service url.
Reranker is a service to improve answer quality by mesure
relevance of text chunks to user query and sort chunks by
relevance. See https://github.com/s-kostyaev/reranker for more
details."
:type 'string)
(defcustom elisa-reranker-similarity-threshold 0
"Reranker similarity threshold.
If set, all quotes with similarity less than threshold will be filtered out."
:type 'number)
(defcustom elisa-reranker-limit 20
"Number of quotes for send to reranker."
:type 'integer)
(defcustom elisa-ignore-patterns-files '(".gitignore" ".ignore" ".rgignore")
"Files with patterns to ignore during file parsing."
:type '(repeat string))
(defcustom elisa-ignore-invisible-files t
"Ignore invisible files and directories during file parsing."
:type 'boolean)
(defcustom elisa-enabled-collections '("builtin manuals" "external manuals")
"Enabled collections for elisa chat."
:type '(repeat string))
(defcustom elisa-supported-complex-document-extensions '("doc" "dot" "ppt" "xls" "rtf" "docx" "pptx" "xlsx" "xlsm" "pdf" "epub" "msg" "odt" "odp" "ods" "odg" "docm")
"Supported complex document file extensions."
:type '(repeat string))
(defun elisa-supported-complex-document-p (path)
"Check if PATH contain supported complex document."
(cl-find (file-name-extension path)
elisa-supported-complex-document-extensions :test #'string=))
(defun elisa-sqlite-vss-download-url ()
"Generate sqlite vss download url based on current system.
Sqlite vss is an extension to sqlite providing vector search
similarity support that used to retrieve relevant data from
database."
(cond ((eq system-type 'darwin)
(if (or (string-prefix-p "aarch64" system-configuration)
(string-prefix-p "arm" system-configuration))
(format
"https://github.com/asg017/sqlite-vss/releases/download/%s/sqlite-vss-%s-loadable-macos-aarch64.tar.gz"
elisa-sqlite-vss-version
elisa-sqlite-vss-version)
(format
"https://github.com/asg017/sqlite-vss/releases/download/%s/sqlite-vss-%s-loadable-macos-x86_64.tar.gz"
elisa-sqlite-vss-version
elisa-sqlite-vss-version)))
((eq system-type 'gnu/linux)
(format
"https://github.com/asg017/sqlite-vss/releases/download/%s/sqlite-vss-%s-loadable-linux-x86_64.tar.gz"
elisa-sqlite-vss-version
elisa-sqlite-vss-version))
(t (user-error "Can't determine download url"))))
(defun elisa--vss-path ()
"Path to vss sqlite extension."
(or elisa-sqlite-vss-path
(let* ((ext (if (eq system-type 'darwin) "dylib" "so"))
(file (format "vss0.%s" ext)))
(file-name-concat elisa-db-directory file))))
(defun elisa--vector-path ()
"Path to vector sqlite extension."
(or elisa-sqlite-vector-path
(let* ((ext (if (string-equal system-type 'darwin) "dylib" "so"))
(file (format "vector0.%s" ext)))
(file-name-concat elisa-db-directory file))))
;;;###autoload
(defun elisa-download-sqlite-vss ()
"Download sqlite vss."
(interactive)
(let ((file-name
(file-truename
(file-name-concat
elisa-db-directory
(format "sqlite-vss-%s.tar.gz" elisa-sqlite-vss-version))))
(default-directory elisa-db-directory))
(make-directory elisa-db-directory t)
(url-copy-file (elisa-sqlite-vss-download-url) file-name t)
(process-lines (executable-find elisa-tar-executable) "-xf" file-name)
(delete-file file-name))
(elisa--reopen-db))
(defun elisa-get-embedding-size ()
"Get embedding size."
(length (llm-embedding elisa-embeddings-provider "test")))
(defun elisa-embeddings-create-table-sql ()
"Generate sql for create embeddings table."
"DROP TABLE IF EXISTS elisa_embeddings;")
(defun elisa-data-embeddings-create-table-sql ()
"Generate sql for create data embeddings table."
(format "CREATE VIRTUAL TABLE IF NOT EXISTS data_embeddings USING vss0(embedding(%d));"
(elisa-get-embedding-size)))
(defun elisa-data-fts-create-table-sql ()
"Generate sql for create full text search table."
"CREATE VIRTUAL TABLE IF NOT EXISTS data_fts USING FTS5(data);")
(defun elisa-info-create-table-sql ()
"Generate sql for create info table."
"DROP TABLE IF EXISTS info;")
(defun elisa-collections-create-table-sql ()
"Generate sql for create collections table."
"CREATE TABLE IF NOT EXISTS collections (name TEXT UNIQUE);")
(defun elisa-kinds-create-table-sql ()
"Generate sql for create kinds table."
"CREATE TABLE IF NOT EXISTS kinds (name TEXT UNIQUE);")
(defun elisa-fill-kinds-sql ()
"Generate sql for fill kinds table."
"INSERT INTO KINDS (name) VALUES ('web'), ('file'), ('info') ON CONFLICT DO NOTHING;")
(defun elisa-files-create-table-sql ()
"Generate sql for create files table."
"CREATE TABLE IF NOT EXISTS files (path TEXT UNIQUE, hash TEXT)")
(defun elisa-data-create-table-sql ()
"Generate sql for create data table."
"CREATE TABLE IF NOT EXISTS data (
kind_id INTEGER,
collection_id INTEGER,
path TEXT,
hash TEXT,
data TEXT,
FOREIGN KEY(kind_id) REFERENCES kinds(rowid),
FOREIGN KEY(collection_id) REFERENCES collections(rowid)
);")
(defun elisa--init-db (db)
"Initialize elisa DB."
(if (not (file-exists-p (elisa--vss-path)))
(warn "Please run M-x `elisa-download-sqlite-vss' to use this package")
(sqlite-pragma db "PRAGMA journal_mode=WAL;")
(sqlite-load-extension db (elisa--vector-path))
(sqlite-load-extension db (elisa--vss-path))
(sqlite-execute db (elisa-embeddings-create-table-sql))
(sqlite-execute db (elisa-info-create-table-sql))
(sqlite-execute db (elisa-collections-create-table-sql))
(sqlite-execute db (elisa-kinds-create-table-sql))
(sqlite-execute db (elisa-fill-kinds-sql))
(sqlite-execute db (elisa-files-create-table-sql))
(sqlite-execute db (elisa-data-create-table-sql))
(sqlite-execute db (elisa-data-embeddings-create-table-sql))
(sqlite-execute db (elisa-data-fts-create-table-sql))))
(defvar elisa-db
(let ((_ (make-directory elisa-db-directory t))
(db (sqlite-open (file-name-concat elisa-db-directory "elisa.sqlite"))))
(elisa--init-db db)
db))
(defun elisa-vector-to-sqlite (data)
"Convert DATA to sqlite vector representation."
(format "vector_from_json(json('%s'))" (json-encode data)))
(defun elisa-sqlite-escape (string)
"Escape single quotes in STRING for sqlite."
(let ((reps '(("'" . "''")
("\\" . "\\\\")
("\0" . "\n"))))
(replace-regexp-in-string
(regexp-opt (mapcar #'car reps))
(lambda (str) (alist-get str reps nil nil #'string=))
string nil t)))
(defun elisa-sqlite-format-int-list (ids)
"Convert list of integer IDS list to sqlite list representation."
(format
"(%s)"
(mapconcat (lambda (id) (format "%d" id)) ids ", ")))
(defun elisa-sqlite-format-string-list (names)
"Convert list of string NAMES list to sqlite list representation."
(format
"(%s)"
(mapconcat (lambda (name)
(format "'%s'"
(elisa-sqlite-escape name)))
names ", ")))
(defun elisa-avg (list)
"Calculate arithmetic average value of LIST."
(cl-loop for elem in list for count from 0
summing elem into sum
finally (return (/ sum (float count)))))
(defun elisa-std-dev (lst)
"Calculate standart deviation value of LST."
(let ((avg (elisa-avg lst))
(len (length lst)))
(sqrt (/ (cl-reduce
#'+
(mapcar
(lambda (x) (expt (- x avg) 2))
lst))
len))))
(defun elisa-calculate-threshold (k distances)
"Calculate breakpoint threshold for DISTANCES based on K standard deviations."
(+ (elisa-avg distances) (* k (elisa-std-dev distances))))
(defun elisa-parse-info-manual (name collection-name)
"Parse info manual with NAME and save index to COLLECTION-NAME."
(with-temp-buffer
(ignore-errors
(info name (current-buffer))
(let ((collection-id (or (caar (sqlite-select
elisa-db
(format
"SELECT rowid FROM collections WHERE name = '%s';"
collection-name)))
(progn
(sqlite-execute
elisa-db
(format
"INSERT INTO collections (name) VALUES ('%s');"
collection-name))
(caar (sqlite-select
elisa-db
(format
"SELECT rowid FROM collections WHERE name = '%s';"
collection-name))))))
(kind-id (caar (sqlite-select
elisa-db "SELECT rowid FROM kinds WHERE name = 'info';")))
(continue t)
(parsed-nodes nil))
(while continue
(let* ((node-name (concat "(" (file-name-sans-extension
(file-name-nondirectory Info-current-file))
") "
Info-current-node))
(chunks (elisa-split-semantically)))
(if (not (cl-find node-name parsed-nodes :test 'string-equal))
(progn
(mapc
(lambda (text)
(let* ((hash (secure-hash 'sha256 text))
(embedding (llm-embedding elisa-embeddings-provider text))
(rowid
(if-let ((rowid (caar (sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE kind_id = %s AND collection_id = %s AND path = '%s' AND hash = '%s';"
kind-id collection-id
(elisa-sqlite-escape node-name) hash)))))
nil
(sqlite-execute
elisa-db
(format
"INSERT INTO data(kind_id, collection_id, path, hash, data) VALUES (%s, %s, '%s', '%s', '%s');"
kind-id collection-id
(elisa-sqlite-escape node-name) hash (elisa-sqlite-escape text)))
(caar (sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE kind_id = %s AND collection_id = %s AND path = '%s' AND hash = '%s';"
kind-id collection-id
(elisa-sqlite-escape node-name) hash))))))
(when rowid
(sqlite-execute
elisa-db
(format "INSERT INTO data_embeddings(rowid, embedding) VALUES (%s, %s);"
rowid (elisa-vector-to-sqlite embedding)))
(sqlite-execute
elisa-db
(format "INSERT INTO data_fts(rowid, data) VALUES (%s, '%s');"
rowid (elisa-sqlite-escape text))))))
chunks)
(push node-name parsed-nodes)
(condition-case nil
(funcall-interactively #'Info-forward-node)
(error
(setq continue nil))))
(setq continue nil))))))))
(defun elisa--find-similar (text collections)
"Find similar to TEXT results in COLLECTIONS.
Return sqlite query. For asyncronous execution."
(let* ((rowids (flatten-tree
(sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE collection_id IN
(
SELECT rowid FROM collections WHERE name IN %s
);"
(elisa-sqlite-format-string-list collections)))))
(query (format "WITH
vector_search AS (
SELECT rowid, distance
FROM data_embeddings
WHERE vss_search(embedding, %s)
ORDER BY distance ASC
LIMIT 40
),
semantic_search AS (
SELECT rowid, RANK () OVER (ORDER BY distance ASC) AS rank
FROM vector_search
WHERE rowid IN %s
ORDER BY distance ASC
LIMIT 20
),
keyword_search AS (
SELECT rowid, RANK () OVER (ORDER BY bm25(data_fts) ASC) AS rank
FROM data_fts
WHERE rowid in %s and data_fts MATCH '%s'
ORDER BY bm25(data_fts) ASC
LIMIT 20
),
hybrid_search AS (
SELECT
COALESCE(semantic_search.rowid, keyword_search.rowid) AS rowid,
COALESCE(1.0 / (60 + semantic_search.rank), 0.0) +
COALESCE(1.0 / (60 + keyword_search.rank), 0.0) AS score
FROM semantic_search
FULL OUTER JOIN keyword_search ON semantic_search.rowid = keyword_search.rowid
ORDER BY score DESC
LIMIT %d
)
SELECT
hybrid_search.rowid
FROM hybrid_search
;
"
(elisa-vector-to-sqlite
(llm-embedding elisa-embeddings-provider text))
(elisa-sqlite-format-int-list rowids)
(elisa-sqlite-format-int-list rowids)
(elisa-fts-query text)
(elisa-get-limit))))
query))
(defun elisa-find-similar (text collections on-done)
"Find similar to TEXT results in COLLECTIONS.
Evaluate ON-DONE with result."
(message "searching in collected data")
(elisa--async-do
(lambda () (elisa--find-similar text collections))
on-done))
(defun elisa--split-by (func)
"Split buffer content to list by FUNC."
(let ((pt (point-min))
(result nil))
(save-excursion
(goto-char (point-min))
(while (not (eobp))
(funcall func)
(push (buffer-substring-no-properties pt (point)) result)
(setq pt (point)))
(nreverse (cl-remove-if #'string-empty-p result)))))
(defun elisa-split-by-sentence ()
"Split byffer to list of sentences."
(elisa--split-by #'forward-sentence))
(defun elisa-split-by-paragraph ()
"Split buffer to list of paragraphs."
(elisa--split-by #'forward-paragraph))
(defun elisa-dot-product (v1 v2)
"Calculate the dot produce of vectors V1 and V2."
(let ((result 0))
(dotimes (i (length v1))
(setq result (+ result (* (aref v1 i) (aref v2 i)))))
result))
(defun elisa-magnitude (v)
"Calculate magnitude of vector V."
(let ((sum 0))
(dotimes (i (length v))
(setq sum (+ sum (* (aref v i) (aref v i)))))
(sqrt sum)))
(defun elisa-cosine-similarity (v1 v2)
"Calculate the cosine similarity of V1 and V2.
The return is a floating point number between 0 and 1, where the
closer it is to 1, the more similar it is."
(let ((dot-product (elisa-dot-product v1 v2))
(v1-magnitude (elisa-magnitude v1))
(v2-magnitude (elisa-magnitude v2)))
(if (and v1-magnitude v2-magnitude)
(/ dot-product (* v1-magnitude v2-magnitude))
0)))
(defun elisa-cosine-distance (v1 v2)
"Calculate cosine-distance between V1 and V2."
(- 1 (elisa-cosine-similarity v1 v2)))
(defun elisa--similarities (list)
"Calculate cosine similarities between neighbour elements in LIST."
(let ((head (car list))
(tail (cdr list))
(result nil))
(while tail
(push (elisa-cosine-similarity head (car tail)) result)
(setq head (car tail))
(setq tail (cdr tail)))
(nreverse result)))
(defun elisa--distances (list)
"Calculate cosine distances between neighbour elements in LIST."
(let ((head (car list))
(tail (cdr list))
(result nil))
(while tail
(push (elisa-cosine-distance head (car tail)) result)
(setq head (car tail))
(setq tail (cdr tail)))
(nreverse result)))
(defun elisa-split-semantically (&rest args)
"Split buffer data semantically.
ARGS contains keys for fine control.
:function FUNC -- FUNC is a function for split buffer into chunks.
:threshold-amount K -- K is a breakpoint threshold amount.
than T, it will be packed into single semantic chunk."
(if-let* ((func (or (plist-get args :function) elisa-semantic-split-function))
(k (or (plist-get args :threshold-amount) elisa-breakpoint-threshold-amount))
(chunks (funcall func))
(embeddings (cl-remove-if
#'not
(mapcar (lambda (s)
(when (length> (string-trim s) 0)
(llm-embedding elisa-embeddings-provider s)))
chunks)))
(distances (elisa--distances embeddings))
(threshold (elisa-calculate-threshold k distances))
(current (car chunks))
(tail (cdr chunks)))
(let* ((result nil))
(dolist (el distances)
(if (<= el threshold)
(setq current (concat current (car tail)))
(push current result)
(setq current (car tail)))
(setq tail (cdr tail)))
(push current result)
(cl-remove-if
#'string-empty-p
(mapcar (lambda (s)
(if s
(string-trim s)
""))
(nreverse result))))
(list (buffer-substring-no-properties (point-min) (point-max)))))
(defun elisa--read-ignore-file-regexps (directory)
"Read ignore patterns from `elisa-ignore-patterns-files' in DIRECTORY."
(mapcar #'wildcard-to-regexp
(flatten-tree
(mapcar (lambda (file)
(let ((filepath (expand-file-name file directory)))
(when (file-exists-p filepath)
(with-temp-buffer
(insert-file-contents filepath)
(split-string (buffer-string) "\n" t)))))
elisa-ignore-patterns-files))))
(defun elisa--text-file-p (filename)
"Check if FILENAME contain text."
(or (and (get-file-buffer filename) t) ;; if file opened assume it text
(with-current-buffer (find-file-noselect filename t t)
(prog1
;; if there is null byte in file, file is binary
(not (search-forward "\0" nil t 1))
(kill-buffer)))))
(defun elisa--file-list (directory)
"List of files to parse in DIRECTORY."
(let ((ignore-regexps (elisa--read-ignore-file-regexps directory)))
(when elisa-ignore-invisible-files
(push "$\\.[^/]*" ignore-regexps)
(push "/\\.[^/]*" ignore-regexps))
(seq-filter (lambda (file)
(and (not (seq-some (lambda (regexp)
(string-match-p regexp file))
ignore-regexps))
(or
(elisa-supported-complex-document-p file)
(elisa--text-file-p file))))
(directory-files-recursively directory ".*"))))
(defun elisa-parse-file (collection-id path &optional force)
"Parse file PATH for COLLECTION-ID.
When FORCE parse even if already parsed."
(let* ((opened (get-file-buffer path))
(buf (if (elisa-supported-complex-document-p path)
(funcall elisa-complex-file-extraction-function path)
(or opened (find-file-noselect path t t))))
(hash (secure-hash 'sha256 buf))
(prev-hash (caar (sqlite-select
elisa-db
(format "SELECT hash FROM files WHERE path = '%s';"
(elisa-sqlite-escape path))))))
(when (or force
(not prev-hash)
(not (string-equal hash prev-hash)))
(with-current-buffer buf
(let ((chunks (elisa-split-semantically))
(old-row-ids
(flatten-tree (sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE path = '%s';"
(elisa-sqlite-escape path)))))
(row-ids nil)
(kind-id (caar (sqlite-select
elisa-db
"SELECT rowid FROM kinds WHERE name = 'file';"))))
;; remove old data
(when prev-hash
(sqlite-execute
elisa-db
(format "DELETE FROM files WHERE path = '%s';"
(elisa-sqlite-escape path))))
;; add new data
(dolist (text chunks)
(let* ((hash (secure-hash 'sha256 text))
(rowid
(if-let ((rowid (caar (sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE kind_id = %s AND collection_id = %s AND path = '%s' AND hash = '%s';"
kind-id collection-id
(elisa-sqlite-escape path) hash)))))
(progn
(push rowid row-ids)
nil)
(sqlite-execute
elisa-db
(format
"INSERT INTO data(kind_id, collection_id, path, hash, data) VALUES (%s, %s, '%s', '%s', '%s');"
kind-id collection-id
(elisa-sqlite-escape path) hash (elisa-sqlite-escape text)))
(caar (sqlite-select
elisa-db
(format "SELECT rowid FROM data WHERE kind_id = %s AND collection_id = %s AND path = '%s' AND hash = '%s';"
kind-id collection-id
(elisa-sqlite-escape path) hash))))))
(when rowid
(sqlite-execute
elisa-db
(format "INSERT INTO data_embeddings(rowid, embedding) VALUES (%s, %s);"
rowid (elisa-vector-to-sqlite
(llm-embedding elisa-embeddings-provider text))))
(sqlite-execute
elisa-db
(format "INSERT INTO data_fts(rowid, data) VALUES (%s, '%s');"
rowid (elisa-sqlite-escape text)))
(push rowid row-ids))))
;; remove old data
(when row-ids
(let ((delete-rows (cl-remove-if (lambda (id)
(cl-find id row-ids))
old-row-ids)))
(elisa--delete-data delete-rows)))
;; save hash to files table
(sqlite-execute
elisa-db
(format "INSERT INTO files (path, hash) VALUES ('%s', '%s');"
(elisa-sqlite-escape path) hash)))))
;; kill buffer if it was not open before parsing
(when (not opened)
(kill-buffer buf))))
(defun elisa--delete-from-table (table ids)
"Delete IDS from TABLE."
(sqlite-execute
elisa-db
(format "DELETE FROM %s WHERE rowid IN %s;"
table
(elisa-sqlite-format-int-list ids))))
(defun elisa--delete-data (ids)
"Delete data with IDS."
(elisa--delete-from-table "data_fts" ids)
(elisa--delete-from-table "data_embeddings" ids)
(elisa--delete-from-table "data" ids))
(defun elisa-parse-directory (dir)
"Parse DIR as new collection syncronously."
(setq dir (expand-file-name dir))
(let* ((collection-id (progn
(sqlite-execute
elisa-db
(format
"INSERT INTO collections (name) VALUES ('%s') ON CONFLICT DO NOTHING;"
(elisa-sqlite-escape dir)))
(caar (sqlite-select
elisa-db
(format
"SELECT rowid FROM collections WHERE name = '%s';"
(elisa-sqlite-escape dir))))))
(files (elisa--file-list dir))
(delete-ids (flatten-tree
(sqlite-select
elisa-db
(format
"SELECT rowid FROM data WHERE collection_id = %d AND path NOT IN %s;"
collection-id
(elisa-sqlite-format-string-list files))))))
(elisa--delete-data delete-ids)
(dolist (file files)
(message "parsing %s" file)
(elisa-parse-file collection-id file))))
;;;###autoload
(defun elisa-async-parse-directory (dir)
"Parse DIR as new collection asyncronously."
(interactive "DSelect directory: ")
(elisa--async-do (lambda ()
(elisa-parse-directory
(expand-file-name dir)))))
(defun elisa-search-duckduckgo (prompt)
"Search duckduckgo for PROMPT and return list of urls."
(let* ((url (format "https://duckduckgo.com/html/?q=%s" (url-hexify-string prompt)))
(buffer-name (plz 'get url :as 'buffer
:headers `(("Accept" . ,eww-accept-content-types)
("Accept-Encoding" . "gzip")
("User-Agent" . ,(url-http--user-agent-default-string))))))
(with-current-buffer buffer-name
(goto-char (point-min))
(search-forward "<!DOCTYPE")
(beginning-of-line)
(cl-remove-if
#'string-empty-p
(cl-remove-duplicates
(mapcar
(lambda (el)
(when el
(string-trim-right
(url-unhex-string
(cdar (url-parse-args (or (dom-attr el 'href) ""))))
"[&\\?].*")))
(dom-by-tag
(libxml-parse-html-region
(point) (point-max))
'a))
:test #'string-equal)))))
(defun elisa-starts-with-lowercase-p (string)
"Check if STRING start with lowercase character."
(let ((category (get-char-code-property (seq-first string) 'general-category)))
(or (eq 'Ll category)
(eq 'Ps category))))
(defun elisa-dehyphen (text)
"Dehyphen TEXT."
(ignore-errors (with-temp-buffer
(insert (string-join
(mapcar #'string-trim (string-split text "\n"))
"\n"))
(goto-char (point-min))
(while (not (eobp))
(end-of-line)
(if (eq (preceding-char) ?-)
(progn
(delete-char 1)
(delete-char -1))
(forward-line)))
(buffer-substring-no-properties (point-min) (point-max)))))
(defun elisa-parse-with-tika-buffer (file)
"Parse FILE with tika."
(let* ((url (format "%s/tika" (string-trim-right elisa-tika-url "/")))
(buf (plz 'put url :body (list 'file file) :as 'buffer))
(shr-use-fonts nil)
(shr-width (- ellama-long-lines-length 5))
(data (with-current-buffer buf
(libxml-parse-html-region (point-min) (point-max))))
(prev-elt nil))
(dolist (elt (dom-by-tag data 'p))
(dolist (text (dom-children elt))
;; trim string content
(when-let* ((trimmed-text (string-trim text))
(new-elt (if (or (string-match "^[0-9]+$" trimmed-text)
(string= "" trimmed-text))
(progn (dom-remove-node data elt)
nil)
(if (elisa-starts-with-lowercase-p trimmed-text)
(progn
(dom-remove-node data prev-elt)
(dom-node 'p nil (elisa-dehyphen
(concat
(car (dom-children prev-elt))
"\n" trimmed-text))))
(dom-node 'p nil (elisa-dehyphen trimmed-text))))))
(setq prev-elt new-elt)
(setq data (cl-nsubst new-elt elt data :test #'equal))))
(when (eq (length (dom-children elt)) 0)
(dom-remove-node data elt)))
(with-current-buffer buf
(delete-region (point-min) (point-max))
(ignore-errors
(shr-insert-document data))
buf)))
(defun elisa-search-searxng (prompt)
"Search searxng for PROMPT and return list of urls.
You can customize `elisa-searxng-url' to use non local instance."
(let ((url (format "%s/search?format=json&q=%s" elisa-searxng-url (url-hexify-string prompt))))
(thread-last
(plz 'get url :as #'json-read)
(alist-get 'results)
(mapcar (lambda (el) (alist-get 'url el))))))
(defun elisa-get-webpage-buffer (url)
"Get buffer with URL content."
(let ((buffer-name (ignore-errors
(plz 'get url :as 'buffer
:headers `(("Accept" . ,eww-accept-content-types)
("Accept-Encoding" . "gzip")
("User-Agent" . ,(url-http--user-agent-default-string))))))
;; fix one word lines for async execution
(shr-use-fonts nil)
(shr-width (- ellama-long-lines-length 5)))
(when buffer-name
(with-current-buffer buffer-name
(goto-char (point-min))
(or (search-forward "<!DOCTYPE" nil t)
(search-forward "<html" nil t))
(beginning-of-line)
(kill-region (point-min) (point))
(ignore-errors
(shr-insert-document (libxml-parse-html-region (point-min) (point-max))))
(goto-char (point-min))
(or (search-forward "<!DOCTYPE" nil t)
(search-forward "<html" nil t))
(beginning-of-line)
(kill-region (point) (point-max))
buffer-name))))
(defun elisa-get-webpage-buffer-pandoc (url)
"Get buffer with URL content translated to markdown with pandoc."
(let ((buffer-name (plz 'get url :as 'buffer)))
(with-current-buffer buffer-name
(shell-command-on-region
(point-min) (point-max)
(format "%s --from html --to plain" elisa-pandoc-executable)
buffer-name t)
buffer-name)))
(defun elisa-fts-query (prompt)
"Return fts match query for PROMPT."