Skip to content

Instantly share code, notes, and snippets.

@rkmax
Created October 21, 2024 14:38
Show Gist options
  • Save rkmax/61f4ce1ead4ff00e661a32a49641ba74 to your computer and use it in GitHub Desktop.
Save rkmax/61f4ce1ead4ff00e661a32a49641ba74 to your computer and use it in GitHub Desktop.
#!/bin/zsh
gpt() {
if [[ ! $+commands[curl] ]]; then
echo "Curl must be installed."
return 1
fi
if [[ ! $+commands[jq] ]]; then
echo "Jq must be installed."
return 1
fi
if [[ ! -v OPENAI_API_KEY ]]; then
echo "Must set OPENAI_API_KEY to your API key"
return 1
fi
curl https://api.openai.com/v1/chat/completions -s \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4o-mini",
"messages": [{"role": "system", "content": "you''re an in-line zsh assistant running on linux. Your task is to answer the questions without any commentation at all, providing only the code to run on terminal. You can assume that the user understands that they need to fill in placeholders like <PORT>. You''re not allowed to explain anything and you''re not a chatbot. You only provide shell commands or code. Keep the responses to one-liner answers as much as possible. Do not decorate the answer with tickmarks"}, {"role": "user", "content": "'"$*"'"}]
}' | jq -r '.choices[0].message.content'
}
spinner() {
local chars="/|\\-"
local delay=0.1
local i=0
tput civis
while :; do
printf "\r%c" "${chars:i%${#chars}:1}"
i=$((i+1))
sleep $delay
done
}
# TODO implement correctly the spinner
spinner_pid=
show_spinner() {
spinner &
spinner_pid=$!
}
hide_spinner() {
kill $spinner_pid
tput cnorm
}
request_with_buffer() {
# show_spinner
result=$(gpt "$BUFFER")
result_length=${#result}
# hide_spinner
BUFFER=$result
CURSOR+=$result_length
}
zle -N request_with_buffer
bindkey '^G' request_with_buffer
@rkmax
Copy link
Author

rkmax commented Oct 21, 2024

the gpt function was taken from here https://github.com/antonjs/zsh-gpt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment