Skip to content

Instantly share code, notes, and snippets.

@macrat
Last active March 3, 2023 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macrat/2818e988361061fcf27d3e14f7420369 to your computer and use it in GitHub Desktop.
Save macrat/2818e988361061fcf27d3e14f7420369 to your computer and use it in GitHub Desktop.
ChatGPT on Vim

ChatGPT on Vim

This is just a experimental code. Not for practical use.

More useful version is on macrat/askgpt.vim.

  1. Place autoload-chatgpt.vim to ~/.vim/autoload/chatgpt.vim.

  2. Write this to your vimrc:

command ChatGPT call chatgpt#Open()

" Replace XXXXX with your OpenAI API Key.
g:chatgpt_api_key = 'XXXXX'
  1. Open chat buffer by :ChatGPT command.

  2. You can chat now!

vim9script
export def Open()
if !exists('g:chatgpt_api_key')
echoerr 'please set g:chatgpt_api_key before use this plugin.'
return
endif
new chatgpt://
set filetype=markdown buftype=prompt
if !exists('b:chatgpt_history')
b:chatgpt_history = [{
role: 'system',
content: 'You are a helpful AI assistant embedded in a text editor Vim.',
}]
endif
append(0, '__User__')
prompt_setprompt(bufnr(), '')
prompt_setcallback(bufnr(), OnInput)
enddef
def OnInput(text: string)
query = trim(text)
if query == ''
return
endif
b:chatgpt_history += [{
role: 'user',
content: query,
}]
const resp = system('curl https://api.openai.com/v1/chat/completions --silent -H "Content-Type: application/json" -H "Authorization: Bearer ' .. g:chatgpt_api_key .. '" -d @-', json_encode({
model: "gpt-3.5-turbo",
messages: b:chatgpt_history,
}))
const msg = json_decode(resp)["choices"][0]["message"]
b:chatgpt_history += [msg]
append(line('$'), [
'__Assistant__',
msg["content"],
'',
'__User__',
'',
])
enddef
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment