llm.vim 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. function! Llm()
  2. let url = "http://127.0.0.1:8080/completion"
  3. " Save the current cursor position
  4. let save_cursor = getpos('.')
  5. silent! %s/\n/\\n/g
  6. silent! %s/\t/\\t/g
  7. silent! %s/\\n$//
  8. " Get the content of the current buffer
  9. let buffer_content = join(getline(1, '$'), "\n")
  10. " Replace true newlines with "\n"
  11. let buffer_content = substitute(buffer_content, '\n', '\\n', 'g')
  12. " Trim leading/trailing whitespace
  13. let buffer_content = substitute(buffer_content, '^\s\+', '', '')
  14. let buffer_content = substitute(buffer_content, '\s\+$', '', '')
  15. " Create the JSON payload
  16. " can't escape backslash, \n gets replaced as \\n
  17. let json_payload = '{"prompt":"' . escape(buffer_content, '"/') . '","temp":0.72,"top_k":100,"top_p":0.73,"repeat_penalty":1.100000023841858,"n_predict":10,"stream":false}'
  18. let prompt_tmpfile = tempname()
  19. let response_tmpfile = tempname()
  20. call writefile([json_payload], prompt_tmpfile)
  21. " Define the curl command
  22. let curl_command = 'curl -k -s -X POST -H "Content-Type: application/json" -o ' . shellescape(response_tmpfile) . ' -d @' . shellescape(prompt_tmpfile) . ' ' . url
  23. silent execute '!'.curl_command
  24. let response = join(readfile(response_tmpfile), '')
  25. let start_marker = '{"content":"'
  26. let end_marker = '","generation_settings'
  27. let content_start = stridx(response, start_marker) + len(start_marker)
  28. let content_end = stridx(response, end_marker, content_start)
  29. " Extract the content field from the response
  30. let content = strpart(response, content_start, content_end - content_start)
  31. " Insert the content at the cursor position
  32. call setline(line('.'), getline('.') . content)
  33. " Replace newline "\n" strings with actual newlines in the content
  34. silent! %s/\\n/\r/g
  35. " and tabs
  36. silent! %s/\\t/\t/g
  37. " and quote marks for C sources
  38. silent! %s/\\"/\"/g
  39. " Remove the temporary file
  40. call delete(prompt_tmpfile)
  41. call delete(response_tmpfile)
  42. endfunction
  43. command! Llm call Llm()