Unlock the power of AI directly in your terminal!
With the rise of ChatGPT everyone is finding benefits in the power of AI.
But the web interface isn’t ideal for everyone, and doesn’t give you the “street cred” of doing everything in the terminal like a true gangster.
What if you could take it one step further and use AI directly in your terminal via a simple shell script?
Prerequisites
I attempted to make this script as straightforward as possible without the need for NodeJS or Python. However, there is one small shell dependency needed to parse the JSON response.
You can get
jq
from https://github.com/stedolan/jq
Or install it with homebrew:
brew install jq
Creating a OpenAI account and API-key
To interact with OpenAI we need an OpenAI account and API key.
The script
#!/bin/bash
if [ ! -n "$OPENAI_API_KEY" ]
then
echo "ERROR: Please set an environment variable for OPENAI_API_KEY"
exit 1
fi
clean_input=$(printf '%s' "$1" | tr -d '"' | tr -d '\n')
response=$(curl -s https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "text-davinci-003",
"prompt": "'"$clean_input"'",
"temperature": 0.1,
"max_tokens": 600
}')
generated_text=$(printf '%s' "$response" | jq '.choices[].text' | tr -d '"' | cut -c 3-)
printf "$generated_text\n"
printf "$generated_text\n" | pbcopy
- The script is pretty simple: remove any newlines and double quotes from the input, make a cURL request to OpenAI, and then print the parsed and cleaned response.
- This version will auto-copy the response to your clipboard (Mac only)
- First set the environment variable
OPENAI_API_KEY
on your system. - The script uses the
text-davinci-003
model, which is currently the most advanced OpenAI model. - You can play around with the temperature setting, a higher value will give more randomness / creativity.
- With the
max_tokens
setting you can specify the maximum amount of tokens spend on one request.
In order to easily call this script from every directory i’ve added a simple function which you can put in your .zshrc
or .bashrc
ai() {
if [ -n "$1" ]
then
sh "~/scripts/openai.sh" "$1"
fi
}
So how to use this script?
Simply call the ai function, and give within quotes your prompt to OpenAI.
e.g.
Wait a few seconds….
SHEBANG! 🍺 There it is!
< ~ > ai "how to perform a cURL with JWT token?"
1. Generate a JWT token.
2. Create a cURL request with the JWT token in the Authorization header.
curl -H \Authorization: Bearer <JWT_TOKEN>\ <URL>
3. Execute the cURL request.
The title of this blog was generated by AI 😎