Skip to content

Instantly share code, notes, and snippets.

@chrischoy
Created March 17, 2023 12:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrischoy/37ae6c04876564df00e3210ac0aeb828 to your computer and use it in GitHub Desktop.
Save chrischoy/37ae6c04876564df00e3210ac0aeb828 to your computer and use it in GitHub Desktop.
OpenAI API call from command line
# OpenAI call
export OPENAI_API_TOKEN=<YOUR_API_KEY from https://platform.openai.com/account/api-keys>
function openai-completion() {
# echo "\nCompleting $LBUFFER ..."
# echo '{ "model": "text-davinci-003", "prompt": "'$LBUFFER'", "max_tokens": 15, "temperature": 0.7 }\n\n'
local response=$(curl --progress-bar https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_TOKEN" \
-d '{ "model": "text-davinci-003", "prompt": "'$LBUFFER'", "max_tokens": 100, "temperature": 0.7 }')
# echo "\n\nResponse:\n\n$response"
local clean_response=$(echo $response | tr -d '\000-\031')
local text=$(echo $clean_response | jq -r '.choices[0].text')
echo $text
zle && zle .reset-prompt && zle -R
zle backward-kill-line
}
zle -N openai-completion
bindkey '^X^A' openai-completion
@chrischoy
Copy link
Author

Write your question and press Ctrl-x Ctrl-a. It will fetch a completion result and print out on the zsh command line.

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