-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathllama.vim
More file actions
2136 lines (1764 loc) · 71.9 KB
/
llama.vim
File metadata and controls
2136 lines (1764 loc) · 71.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
" vim: ts=4 sts=4 expandtab
" colors (adjust to your liking)
" fim colors
highlight default llama_hl_fim_hint guifg=#ff772f ctermfg=202
highlight default llama_hl_fim_info guifg=#77ff2f ctermfg=119
" instruct colors for selected block
highlight default llama_hl_inst_src guibg=#554433 ctermbg=236
" virtual text colors for instructions
highlight default llama_hl_inst_virt_proc guifg=#77ff2f ctermfg=119
highlight default llama_hl_inst_virt_gen guifg=#77ff2f ctermfg=119
highlight default llama_hl_inst_virt_ready guifg=#ff772f ctermfg=202
" general parameters:
"
" endpoint_fim: llama.cpp server endpoint for FIM completion
" endpoint_inst: llama.cpp server endpoint for instruction completion
" model_fim: model name in case when multiple models are loaded (optional, recommended: Qwen3 Coder 30B)
" model_inst: instruction model name (optional, recommended: gpt-oss-120b)
" api_key: llama.cpp server api key (optional)
" n_prefix: number of lines before the cursor location to include in the local prefix
" n_suffix: number of lines after the cursor location to include in the local suffix
" n_predict: max number of tokens to predict
" stop_strings_fim return the result immediately as soon as any of these strings are encountered in the generated text for FIM completions
" stop_strings_inst return the result immediately as soon as any of these strings are encountered in the generated text for instruction completions
" n_cmpl: number of completions to cache per position (ring buffer, default: 1)
" t_max_prompt_ms: max alloted time for the prompt processing (TODO: not yet supported)
" t_max_predict_ms: max alloted time for the prediction
" show_info: show extra info about the inference (0 - disabled, 1 - statusline, 2 - inline)
" auto_fim: trigger FIM completion automatically on cursor movement
" max_line_suffix: do not auto-trigger FIM completion if there are more than this number of characters to the right of the cursor
" max_cache_keys: max number of cached completions to keep in result_cache
" enable_at_startup: enable llama.vim functionality at startup (default: v:true)
"
" ring buffer of chunks, accumulated with time upon:
"
" - completion request
" - yank
" - entering a buffer
" - leaving a buffer
" - writing a file
"
" parameters for the ring-buffer with extra context:
"
" ring_n_chunks: max number of chunks to pass as extra context to the server (0 to disable)
" ring_chunk_size: max size of the chunks (in number of lines)
" note: adjust these numbers so that you don't overrun your context
" at ring_n_chunks = 64 and ring_chunk_size = 64 you need ~32k context
" ring_scope: the range around the cursor position (in number of lines) for gathering chunks after FIM
" ring_update_ms: how often to process queued chunks in normal mode
"
" keymaps parameters (empty string to disable):
"
" keymap_fim_trigger: keymap to trigger the completion, default: <C-F>
" keymap_fim_accept_full: keymap to accept full suggestion, default: <Tab>
" keymap_fim_accept_line: keymap to accept line suggestion, default: <S-Tab>
" keymap_fim_accept_word: keymap to accept word suggestion, default: <C-B>
" keymap_fim_next: keymap to cycle to next completion, default: <C-J>
" keymap_fim_prev: keymap to cycle to prev completion, default: <C-K>
" keymap_debug_toggle: keymap to toggle the debug pane, default: null
" keymap_inst_trigger: keymap to trigger the instruction command, default: <leader>lli
" keymap_inst_rerun: keymap to rerun the instruction, default: <leader>llr
" keymap_inst_continue: keymap to continue the instruction, default: <leader>llc
" keymap_inst_accept: keymap to accept the instruction, default: <Tab>
" keymap_inst_cancel: keymap to cancel the instruction, default: <Esc>
"
let s:default_config = {
\ 'endpoint_fim': 'http://127.0.0.1:8012/infill',
\ 'endpoint_inst': 'http://127.0.0.1:8012/v1/chat/completions',
\ 'model_fim': '',
\ 'model_inst': '',
\ 'api_key': '',
\ 'n_prefix': 256,
\ 'n_suffix': 64,
\ 'n_predict': 128,
\ 'stop_strings_fim': [],
\ 'stop_strings_inst': [],
\ 'n_cmpl': 1,
\ 't_max_prompt_ms': 500,
\ 't_max_predict_ms': 1000,
\ 'show_info': 2,
\ 'auto_fim': v:true,
\ 'max_line_suffix': 8,
\ 'max_cache_keys': 250,
\ 'ring_n_chunks': 16,
\ 'ring_chunk_size': 64,
\ 'ring_scope': 1024,
\ 'ring_update_ms': 1000,
\ 'keymap_fim_trigger': "<leader>llf",
\ 'keymap_fim_accept_full': "<Tab>",
\ 'keymap_fim_accept_line': "<S-Tab>",
\ 'keymap_fim_accept_word': "<leader>ll]",
\ 'keymap_fim_next': "<C-J>",
\ 'keymap_fim_prev': "<C-K>",
\ 'keymap_inst_trigger': "<leader>lli",
\ 'keymap_inst_rerun': "<leader>llr",
\ 'keymap_inst_continue': "<leader>llc",
\ 'keymap_inst_accept': "<Tab>",
\ 'keymap_inst_cancel': "<Esc>",
\ 'keymap_debug_toggle': "<leader>lld",
\ 'enable_at_startup': v:true,
\ }
let llama_config = get(g:, 'llama_config', s:default_config)
" rename deprecated keys in `llama_config`.
let s:renames = {
\ 'endpoint' : 'endpoint_fim',
\ 'model' : 'model_fim',
\ 'keymap_trigger' : 'keymap_fim_trigger',
\ 'keymap_accept_full' : 'keymap_fim_accept_full',
\ 'keymap_accept_line' : 'keymap_fim_accept_line',
\ 'keymap_accept_word' : 'keymap_fim_accept_word',
\ 'keymap_debug' : 'keymap_debug_toggle',
\ 'stop_strings' : 'stop_strings_fim',
\ }
for [old_key, new_key] in items(s:renames)
if has_key(llama_config, old_key)
let llama_config[new_key] = llama_config[old_key]
call remove(llama_config, old_key)
echohl WarningMsg
echomsg printf(
\ 'llama.vim: %s is deprecated, use %s instead',
\ old_key, new_key)
echohl None
endif
endfor
let g:llama_config = extendnew(s:default_config, llama_config, 'force')
let s:llama_enabled = v:false
" containes cached responses from the server
" each key maps to a ring buffer of up to n_cmpl individual completion responses
" used to avoid re-computing the same completions and to also create new completions with similar context
" ref: https://github.com/ggml-org/llama.vim/pull/18
let g:cache_data = {}
let g:cache_lru_order = []
" insert a single completion response into the cache ring buffer for a key
" the ring buffer holds up to g:llama_config.n_cmpl entries per key
function! s:cache_insert(key, response)
" Check if we need to evict a key
if !has_key(g:cache_data, a:key) && len(keys(g:cache_data)) >= g:llama_config.max_cache_keys
" Get the least recently used key (first in order list)
let l:lru_key = g:cache_lru_order[0]
" Remove from cache data
call remove(g:cache_data, l:lru_key)
" Remove from LRU order
call remove(g:cache_lru_order, 0)
endif
" Initialize ring buffer for this key if needed
if !has_key(g:cache_data, a:key)
let g:cache_data[a:key] = []
endif
" skip if a completion with the same content already exists for this key
let l:new_content = get(a:response, 'content', '')
for l:existing in g:cache_data[a:key]
if get(l:existing, 'content', '') ==# l:new_content
return
endif
endfor
" Add to ring buffer, evict oldest if full
if len(g:cache_data[a:key]) >= g:llama_config.n_cmpl
call remove(g:cache_data[a:key], 0)
endif
call add(g:cache_data[a:key], a:response)
" Update LRU order - remove key if it exists and add to end (most recent)
call filter(g:cache_lru_order, 'v:val !=# a:key')
call add(g:cache_lru_order, a:key)
endfunction
" Get all cached completions for a key (ring buffer), or v:null if not found
function! s:cache_get(key)
if !has_key(g:cache_data, a:key)
return v:null
endif
" Update LRU order - remove key if it exists and add to end (most recent)
call filter(g:cache_lru_order, 'v:val !=# a:key')
call add(g:cache_lru_order, a:key)
return g:cache_data[a:key]
endfunction
" Count total cached entries across all keys
function! s:cache_count()
let l:total = 0
for l:entries in values(g:cache_data)
let l:total += len(l:entries)
endfor
return l:total
endfunction
" get the number of leading spaces of a string
function! s:get_indent(str)
let l:count = 0
for i in range(len(a:str))
if a:str[i] == "\t"
let l:count += &tabstop
elseif a:str[i] == " "
let l:count += 1
else
break
endif
endfor
return l:count
endfunction
function! s:rand(i0, i1) abort
return a:i0 + rand() % (a:i1 - a:i0 + 1)
endfunction
function! llama#disable()
call llama#fim_hide()
autocmd! llama
" TODO: these unmaps don't seem to work properly
if g:llama_config.keymap_fim_trigger != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_trigger
endif
if g:llama_config.keymap_fim_accept_full != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_accept_full
endif
if g:llama_config.keymap_fim_accept_line != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_accept_line
endif
if g:llama_config.keymap_fim_accept_word != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_accept_word
endif
if g:llama_config.keymap_fim_next != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_next
endif
if g:llama_config.keymap_fim_prev != ''
exe "silent! iunmap <buffer> " .. g:llama_config.keymap_fim_prev
endif
if g:llama_config.keymap_debug_toggle != ''
exe "silent! unmap " .. g:llama_config.keymap_debug_toggle
endif
if g:llama_config.keymap_inst_trigger != ''
exe "silent! vunmap " .. g:llama_config.keymap_inst_trigger
endif
if g:llama_config.keymap_inst_rerun != ''
exe "silent! unmap " .. g:llama_config.keymap_inst_rerun
endif
if g:llama_config.keymap_inst_continue != ''
exe "silent! unmap " .. g:llama_config.keymap_inst_continue
endif
if g:llama_config.keymap_inst_accept != ''
exe "silent! unmap " .. g:llama_config.keymap_inst_accept
endif
if g:llama_config.keymap_inst_cancel != ''
exe "silent! unmap " .. g:llama_config.keymap_inst_cancel
endif
let s:llama_enabled = v:false
call llama#debug_log('plugin disabled')
endfunction
function! llama#toggle()
if s:llama_enabled
call llama#disable()
else
call llama#enable()
endif
endfunction
function! llama#toggle_auto_fim()
if !s:llama_enabled
return
endif
let g:llama_config.auto_fim = !g:llama_config.auto_fim
call llama#setup_autocmds()
endfunction
function! llama#status()
let l:fim_base = substitute(g:llama_config.endpoint_fim, '/infill$', '', '')
let l:inst_base = substitute(g:llama_config.endpoint_inst, '/v1/chat/completions$', '', '')
let s:status_messages = {'fim': '', 'inst': '', 'count': 0}
" If both endpoints are the same then we are running llama-server as a
" router. Otherwise each are independent servers.
if l:fim_base ==# l:inst_base
let l:models_url = l:fim_base . '/v1/models'
call s:fetch_status(l:models_url, 'both')
else
let l:fim_url = l:fim_base . '/v1/models'
let l:inst_url = l:inst_base . '/v1/models'
call s:fetch_status(l:fim_url, 'fim')
call s:fetch_status(l:inst_url, 'inst')
endif
endfunction
function! s:fetch_status(url, type)
let l:curl_command = [
\ "curl",
\ "--silent",
\ "--max-time", "3",
\ "--request", "GET",
\ "--url", a:url,
\ ]
if s:ghost_text_nvim
let l:job = jobstart(l:curl_command, {
\ 'on_stdout': function('s:status_on_response', [a:type]),
\ 'on_exit': function('s:status_on_exit', [a:type]),
\ 'stdout_buffered': v:true
\ })
elseif s:ghost_text_vim
let l:job = job_start(l:curl_command, {
\ 'out_cb': function('s:status_on_response', [a:type]),
\ 'exit_cb': function('s:status_on_exit', [a:type])
\ })
endif
endfunction
function! s:status_on_response(type, job_id, data, event = v:null)
if s:ghost_text_nvim
let l:raw = join(a:data, "\n")
elseif s:ghost_text_vim
let l:raw = a:data
endif
if empty(l:raw)
return
endif
try
let l:response = json_decode(l:raw)
let l:models = get(l:response, 'data', [])
if a:type ==# 'both'
let l:fim_status = s:get_model_status(g:llama_config.model_fim, l:models)
let l:inst_status = s:get_model_status(g:llama_config.model_inst, l:models)
echo 'FIM model (' . g:llama_config.model_fim . '): ' . l:fim_status . ', Instruction model (' . g:llama_config.model_inst . '): ' . l:inst_status
elseif a:type ==# 'fim'
let l:fim_status = s:get_model_status(g:llama_config.model_fim, l:models)
let s:status_messages.fim = 'FIM model (' . g:llama_config.model_fim . '): ' . l:fim_status
let s:status_messages.count += 1
call s:display_status_if_ready()
elseif a:type ==# 'inst'
let l:inst_status = s:get_model_status(g:llama_config.model_inst, l:models)
let s:status_messages.inst = 'Instruction model (' . g:llama_config.model_inst . '): ' . l:inst_status
let s:status_messages.count += 1
call s:display_status_if_ready()
endif
catch
echom 'Error parsing status response: ' . v:exception
endtry
endfunction
function! s:status_on_exit(type, job_id, exit_code, event = v:null)
if a:exit_code != 0
call llama#debug_log('status_on_exit (' . a:type . '): curl failed with exit code ' . a:exit_code)
if a:type ==# 'both'
echo 'LlamaStatus: ❌ Server not reachable'
elseif a:type ==# 'fim'
let s:status_messages.fim = 'FIM server: ❌ Not reachable'
let s:status_messages.count += 1
call s:display_status_if_ready()
elseif a:type ==# 'inst'
let s:status_messages.inst = 'Instruction server: ❌ Not reachable'
let s:status_messages.count += 1
call s:display_status_if_ready()
endif
endif
endfunction
function! s:display_status_if_ready()
" Wait for both FIM and instruction responses.
if s:status_messages.count >= 2
echo s:status_messages.fim . ', ' . s:status_messages.inst
endif
endfunction
function! s:get_model_status(model_name, models)
if empty(a:model_name)
return '❌ Not configured'
endif
for l:model in a:models
if get(l:model, 'id', '') ==# a:model_name || index(get(l:model, 'tags', []), a:model_name) >= 0 || index(get(l:model, 'aliases', []), a:model_name) >= 0
if has_key(l:model, 'status')
let l:status_value = get(get(l:model, 'status', {}), 'value', 'unknown')
return l:status_value ==# 'loaded' ? '✅ Ready' : l:status_value
else
return '✅ Ready'
endif
endif
endfor
if len(a:models) == 1
let l:model = a:models[0]
if has_key(l:model, 'status')
let l:status_value = get(get(l:model, 'status', {}), 'value', 'unknown')
return l:status_value ==# 'loaded' ? '✅ Ready' : l:status_value
else
return '✅ Ready'
endif
endif
return '❌ Not loaded'
endfunction
function! llama#setup()
command! LlamaEnable call llama#enable()
command! LlamaDisable call llama#disable()
command! LlamaToggle call llama#toggle()
command! LlamaToggleAutoFim call llama#toggle_auto_fim()
command! LlamaStatus call llama#status()
command! -range=% LlamaInstruct call llama#inst(<line1>, <line2>)
call llama#debug_setup()
endfunction
function! llama#init()
call llama#debug_log('llama.vim initializing ...')
if !executable('curl')
echohl WarningMsg
echo 'llama.vim requires the "curl" command to be available'
echohl None
return
endif
call llama#setup()
let s:fim_data = {}
let s:ring_chunks = [] " current set of chunks used as extra context
let s:ring_queued = [] " chunks that are queued to be sent for processing
let s:ring_n_evict = 0
let s:fim_hint_shown = v:false
let s:pos_y_pick = -9999 " last y where we picked a chunk
let s:indent_last = -1 " last indentation level that was accepted (TODO: this might be buggy)
let s:timer_fim = -1
let s:t_last_move = reltime() " last time the cursor moved
let s:current_job_fim = v:null
let s:inst_reqs = {}
let s:inst_req_id = 0
let s:ghost_text_nvim = exists('*nvim_buf_get_mark')
let s:ghost_text_vim = has('textprop')
if s:ghost_text_vim
if version < 901
echom 'Warning: llama.vim requires version 901 or greater. Current version: ' . version
endif
let s:hlgroup_hint = 'llama_hl_fim_hint'
let s:hlgroup_info = 'llama_hl_fim_info'
let s:hlgroup_inst = 'llama_hl_inst_src'
let s:hlgroup_inst_info = 'llama_hl_inst_info'
if empty(prop_type_get(s:hlgroup_hint))
call prop_type_add(s:hlgroup_hint, {'highlight': s:hlgroup_hint})
endif
if empty(prop_type_get(s:hlgroup_info))
call prop_type_add(s:hlgroup_info, {'highlight': s:hlgroup_info})
endif
if empty(prop_type_get(s:hlgroup_inst))
call prop_type_add(s:hlgroup_inst, {'highlight': s:hlgroup_inst})
endif
if !hlexists(s:hlgroup_inst_info)
highlight link llama_hl_inst_info Comment
endif
if empty(prop_type_get(s:hlgroup_inst_info))
call prop_type_add(s:hlgroup_inst_info, {'highlight': s:hlgroup_inst_info})
endif
endif
if g:llama_config.enable_at_startup
call llama#enable()
endif
endfunction
function! llama#setup_autocmds()
augroup llama
autocmd!
autocmd InsertLeavePre * call llama#fim_hide()
autocmd CompleteChanged * call llama#fim_hide()
autocmd CompleteDone * call s:on_move()
if g:llama_config.auto_fim
autocmd CursorMoved * call s:on_move()
autocmd CursorMovedI * call s:on_move()
autocmd CursorMovedI * call llama#fim(-1, -1, v:true, [], v:true)
endif
" gather chunks upon yanking
autocmd TextYankPost * if v:event.operator ==# 'y' | call s:pick_chunk(v:event.regcontents, v:false, v:true) | endif
" gather chunks upon entering/leaving a buffer
autocmd BufEnter * call timer_start(100, {-> s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)})
autocmd BufLeave * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)
" gather chunk upon saving the file
autocmd BufWritePost * call s:pick_chunk(getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')])), v:true, v:true)
augroup END
endfunction
function! llama#enable()
if s:llama_enabled
return
endif
" setup keymaps
if g:llama_config.keymap_fim_trigger != ''
exe "autocmd InsertEnter * inoremap <buffer> <expr> <silent> " . g:llama_config.keymap_fim_trigger . " llama#fim_inline(v:false, v:false)"
endif
if g:llama_config.keymap_debug_toggle != ''
exe "nnoremap <silent> " .. g:llama_config.keymap_debug_toggle .. " :call llama#debug_toggle()<CR>"
endif
if g:llama_config.keymap_inst_trigger != ''
exe "vnoremap <silent> " .. g:llama_config.keymap_inst_trigger .. " :LlamaInstruct<CR>"
endif
if g:llama_config.keymap_inst_rerun != ''
exe "nnoremap <silent> " .. g:llama_config.keymap_inst_rerun .. " :call llama#inst_rerun()<CR>"
endif
if g:llama_config.keymap_inst_continue != ''
exe "nnoremap <silent> " .. g:llama_config.keymap_inst_continue .. " :call llama#inst_continue()<CR>"
endif
if g:llama_config.keymap_inst_accept != ''
exe "nnoremap <silent> " .. g:llama_config.keymap_inst_accept .. " :call llama#inst_accept()<CR>"
endif
if g:llama_config.keymap_inst_cancel != ''
exe "nnoremap <silent> " .. g:llama_config.keymap_inst_cancel .. " :call llama#inst_cancel()<CR>"
endif
call llama#setup_autocmds()
silent! call llama#fim_hide()
" init background update of the ring buffer
if g:llama_config.ring_n_chunks > 0
call s:ring_update()
endif
let s:llama_enabled = v:true
call llama#debug_log('plugin enabled')
endfunction
" compute how similar two chunks of text are
" 0 - no similarity, 1 - high similarity
function! s:chunk_sim(c0, c1)
let l:tokens0 = split(join(a:c0, "\n"), '\W\+')
let l:tokens1 = split(join(a:c1, "\n"), '\W\+')
let l:set0 = {}
for l:tok in l:tokens0
let l:set0[l:tok] = 1
endfor
let l:common = 0
for l:tok in l:tokens1
if has_key(l:set0, l:tok)
let l:common += 1
endif
endfor
if (len(l:tokens0) + len(l:tokens1)) == 0
let l:res = 1.0
else
let l:res = 2.0 * l:common / (len(l:tokens0) + len(l:tokens1))
endif
"call llama#debug_log('chunk_sim: ' . l:res, join(a:c0, "\n") . '\n\n====================\n\n' . join(a:c1, "\n"))
return l:res
endfunction
" pick a random chunk of size g:llama_config.ring_chunk_size from the provided text and queue it for processing
"
" no_mod - do not pick chunks from buffers with pending changes
" do_evict - evict chunks that are very similar to the new one
"
function! s:pick_chunk(text, no_mod, do_evict)
" do not pick chunks from buffers with pending changes or buffers that are not files
if a:no_mod && (getbufvar(bufnr('%'), '&modified') || !buflisted(bufnr('%')) || !filereadable(expand('%')))
return
endif
" if the extra context option is disabled - do nothing
if g:llama_config.ring_n_chunks <= 0
return
endif
" don't pick very small chunks
if len(a:text) < 3
return
endif
if len(a:text) + 1 < g:llama_config.ring_chunk_size
let l:chunk = a:text
else
let l:l0 = s:rand(0, max([0, len(a:text) - g:llama_config.ring_chunk_size/2]))
let l:l1 = min([l:l0 + g:llama_config.ring_chunk_size/2, len(a:text)])
let l:chunk = a:text[l:l0:l:l1]
endif
let l:chunk_str = join(l:chunk, "\n") . "\n"
" check if this chunk is already added
let l:exist = v:false
for i in range(len(s:ring_chunks))
if s:ring_chunks[i].data == l:chunk
let l:exist = v:true
break
endif
endfor
for i in range(len(s:ring_queued))
if s:ring_queued[i].data == l:chunk
let l:exist = v:true
break
endif
endfor
if l:exist
return
endif
" evict queued chunks that are very similar to the new one
for i in range(len(s:ring_queued) - 1, 0, -1)
if s:chunk_sim(s:ring_queued[i].data, l:chunk) > 0.9
if a:do_evict
call remove(s:ring_queued, i)
let s:ring_n_evict += 1
else
return
endif
endif
endfor
" also from s:ring_chunks
for i in range(len(s:ring_chunks) - 1, 0, -1)
if s:chunk_sim(s:ring_chunks[i].data, l:chunk) > 0.9
if a:do_evict
call remove(s:ring_chunks, i)
let s:ring_n_evict += 1
else
return
endif
endif
endfor
" TODO: become parameter ?
if len(s:ring_queued) == 16
call remove(s:ring_queued, 0)
endif
call add(s:ring_queued, {'data': l:chunk, 'str': l:chunk_str, 'time': reltime(), 'filename': expand('%')})
"let &statusline = 'extra context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued)
endfunction
function! s:ring_get_extra()
" extra context
let l:extra = []
for l:chunk in s:ring_chunks
call add(l:extra, {
\ 'text': l:chunk.str,
\ 'time': l:chunk.time,
\ 'filename': l:chunk.filename
\ })
endfor
return l:extra
endfunction
" picks a queued chunk, sends it for processing and adds it to s:ring_chunks
" called every g:llama_config.ring_update_ms
function! s:ring_update()
call timer_start(g:llama_config.ring_update_ms, {-> s:ring_update()})
" skip update if not in normal model and the cursor has moved recently
if mode() !=# 'n' && reltimefloat(reltime(s:t_last_move)) < 3.0
return
endif
if len(s:ring_queued) == 0
return
endif
" move the first queued chunk to the ring buffer
if len(s:ring_chunks) == g:llama_config.ring_n_chunks
call remove(s:ring_chunks, 0)
endif
call add(s:ring_chunks, remove(s:ring_queued, 0))
"let &statusline = 'updated context: ' . len(s:ring_chunks) . ' / ' . len(s:ring_queued)
" send asynchronous job with the new extra context so that it is ready for the next FIM
let l:extra = s:ring_get_extra()
" no samplers needed here
let l:request = {
\ 'id_slot': 0,
\ 'input_prefix': "",
\ 'input_suffix': "",
\ 'input_extra': l:extra,
\ 'prompt': "",
\ 'n_predict': 0,
\ 'temperature': 0.0,
\ 'samplers': [],
\ 'stream': v:false,
\ 'cache_prompt': v:true,
\ 't_max_prompt_ms': 1,
\ 't_max_predict_ms': 1,
\ 'response_fields': [""]
\ }
let l:curl_command = [
\ "curl",
\ "--silent",
\ "--no-buffer",
\ "--request", "POST",
\ "--url", g:llama_config.endpoint_fim,
\ "--header", "Content-Type: application/json",
\ "--data", "@-",
\ ]
if exists ("g:llama_config.model_fim") && len(g:llama_config.model_fim) > 0
let l:request['model'] = g:llama_config.model_fim
end
if exists ("g:llama_config.api_key") && len(g:llama_config.api_key) > 0
call extend(l:curl_command, ['--header', 'Authorization: Bearer ' .. g:llama_config.api_key])
endif
" no callbacks because we don't need to process the response
let l:request_json = json_encode(l:request)
if s:ghost_text_nvim
let jobid = jobstart(l:curl_command, {})
call chansend(jobid, l:request_json)
call chanclose(jobid, 'stdin')
elseif s:ghost_text_vim
let jobid = job_start(l:curl_command, {})
let channel = job_getchannel(jobid)
call ch_sendraw(channel, l:request_json)
call ch_close_in(channel)
endif
endfunction
" =====================================
" Fill-in-Middle (FIM) completion
" =====================================
" get the local context at a specified position
" a:prev can optionally contain a previous completion for this position
" in such cases, create the local context as if the completion was already inserted
function! s:fim_ctx_local(pos_x, pos_y, prev)
let l:max_y = line('$')
if empty(a:prev)
let l:line_cur = getline(a:pos_y)
let l:line_cur_prefix = strpart(l:line_cur, 0, a:pos_x)
let l:line_cur_suffix = strpart(l:line_cur, a:pos_x)
let l:lines_prefix = getline(max([1, a:pos_y - g:llama_config.n_prefix]), a:pos_y - 1)
let l:lines_suffix = getline(a:pos_y + 1, min([l:max_y, a:pos_y + g:llama_config.n_suffix]))
" special handling of lines full of whitespaces - start from the beginning of the line
if match(l:line_cur, '^\s*$') >= 0
let l:indent = 0
let l:line_cur_prefix = ""
let l:line_cur_suffix = ""
else
" the indentation of the current line
let l:indent = strlen(matchstr(l:line_cur, '^\s*'))
endif
else
if len(a:prev) == 1
let l:line_cur = getline(a:pos_y) . a:prev[0]
else
let l:line_cur = a:prev[-1]
endif
let l:line_cur_prefix = l:line_cur
let l:line_cur_suffix = ""
let l:lines_prefix = getline(max([1, a:pos_y - g:llama_config.n_prefix + len(a:prev) - 1]), a:pos_y - 1)
if len(a:prev) > 1
call add(l:lines_prefix, getline(a:pos_y) . a:prev[0])
for l:line in a:prev[1:-2]
call add(l:lines_prefix, l:line)
endfor
endif
let l:lines_suffix = getline(a:pos_y + 1, min([l:max_y, a:pos_y + g:llama_config.n_suffix]))
let l:indent = s:indent_last
endif
let l:prefix = ""
\ . join(l:lines_prefix, "\n")
\ . "\n"
let l:middle = ""
\ . l:line_cur_prefix
let l:suffix = ""
\ . l:line_cur_suffix
\ . "\n"
\ . join(l:lines_suffix, "\n")
\ . "\n"
let l:res = {}
let l:res['prefix'] = l:prefix
let l:res['middle'] = l:middle
let l:res['suffix'] = l:suffix
let l:res['indent'] = l:indent
let l:res['line_cur'] = l:line_cur
let l:res['line_cur_prefix'] = l:line_cur_prefix
let l:res['line_cur_suffix'] = l:line_cur_suffix
return l:res
endfunction
" necessary for 'inoremap <expr>'
function! llama#fim_inline(is_auto, use_cache) abort
" exit if not enabled
if !s:llama_enabled
return ''
endif
" we already have a suggestion displayed - hide it
if s:fim_hint_shown && !a:is_auto
call llama#fim_hide()
return ''
endif
call llama#fim(-1, -1, a:is_auto, [], a:use_cache)
return ''
endfunction
" the main FIM call
" takes local context around the cursor and sends it together with the extra context to the server for completion
function! llama#fim(pos_x, pos_y, is_auto, prev, use_cache) abort
let l:pos_x = a:pos_x
let l:pos_y = a:pos_y
if l:pos_x < 0
let l:pos_x = col('.') - 1
endif
if l:pos_y < 0
let l:pos_y = line('.')
endif
" avoid sending repeated requests too fast
if s:current_job_fim != v:null
if s:timer_fim != -1
call timer_stop(s:timer_fim)
let s:timer_fim = -1
endif
let s:timer_fim = timer_start(100, {-> llama#fim(a:pos_x, a:pos_y, v:true, a:prev, a:use_cache)})
return
endif
"if s:fim_hint_shown && empty(a:prev)
" return
"endif
"let s:t_fim_start = reltime()
let l:ctx_local = s:fim_ctx_local(l:pos_x, l:pos_y, a:prev)
let l:prefix = l:ctx_local['prefix']
let l:middle = l:ctx_local['middle']
let l:suffix = l:ctx_local['suffix']
let l:indent = l:ctx_local['indent']
if a:is_auto && len(l:ctx_local['line_cur_suffix']) > g:llama_config.max_line_suffix
return
endif
let l:t_max_predict_ms = g:llama_config.t_max_predict_ms
if empty(a:prev)
" the first request is quick - we will launch a speculative request after this one is displayed
let l:t_max_predict_ms = 250
endif
" compute multiple hashes that can be used to generate a completion for which the
" first few lines are missing. this happens when we have scrolled down a bit from where the original
" generation was done
"
let l:hashes = []
call add(l:hashes, sha256(l:prefix . l:middle . 'Î' . l:suffix))
let l:prefix_trim = l:prefix
for i in range(3)
let l:prefix_trim = substitute(l:prefix_trim, '^[^\n]*\n', '', '')
if empty(l:prefix_trim)
break
endif
call add(l:hashes, sha256(l:prefix_trim . l:middle . 'Î' . l:suffix))
endfor
" if we already have a cached completion for one of the hashes, don't send a request
if a:use_cache
for l:hash in l:hashes
let l:cached = s:cache_get(l:hash)
if l:cached isnot v:null && len(l:cached) > 0
return
endif
endfor
endif
" TODO: this might be incorrect
let s:indent_last = l:indent
" TODO: refactor in a function
let l:text = getline(max([1, line('.') - g:llama_config.ring_chunk_size/2]), min([line('.') + g:llama_config.ring_chunk_size/2, line('$')]))
let l:l0 = s:rand(0, max([0, len(l:text) - g:llama_config.ring_chunk_size/2]))
let l:l1 = min([l:l0 + g:llama_config.ring_chunk_size/2, len(l:text)])
let l:chunk = l:text[l:l0:l:l1]
" evict chunks that are very similar to the current context
" this is needed because such chunks usually distort the completion to repeat what was already there
for i in range(len(s:ring_chunks) - 1, 0, -1)
if s:chunk_sim(s:ring_chunks[i].data, l:chunk) > 0.5
call remove(s:ring_chunks, i)
let s:ring_n_evict += 1
endif
endfor
let l:extra = s:ring_get_extra()
let l:request = {
\ 'id_slot': 0,
\ 'input_prefix': l:prefix,
\ 'input_suffix': l:suffix,
\ 'input_extra': l:extra,
\ 'prompt': l:middle,
\ 'n_predict': g:llama_config.n_predict,
\ 'stop': g:llama_config.stop_strings_fim,
\ 'n_cmpl': g:llama_config.n_cmpl,
\ 'n_indent': l:indent,
\ 'top_k': 40,
\ 'top_p': 0.90,
\ 'samplers': ["top_k", "top_p", "infill"],
\ 'stream': v:false,
\ 'cache_prompt': v:true,
\ 't_max_prompt_ms': g:llama_config.t_max_prompt_ms,
\ 't_max_predict_ms': l:t_max_predict_ms,
\ 'response_fields': [
\ "content",
\ "timings/prompt_n",
\ "timings/prompt_ms",
\ "timings/prompt_per_token_ms",
\ "timings/prompt_per_second",
\ "timings/predicted_n",
\ "timings/predicted_ms",
\ "timings/predicted_per_token_ms",
\ "timings/predicted_per_second",
\ "truncated",
\ "tokens_cached",