I love ChatGPT, but wish I could tell it do do more real things. The incredible GPT4ALL offers an API, but wanted to go deeper and bring ChatGPT into the terminal, in context. This simple script enables the execution right in the terminal. There are a few other short steps:
- save this file as ai (no extension) somewhere like /usr/local/bin
- Use this command in the folder where the file is: chmod +x ai
- If you are missing jq, use brew install jq (you might need to install brew also)
You can then either type ai into the terminal to start the session or ai and then the prompt (example: ai what command do i need to see the current directory). It will then show the command and if you want to execute it.
#!/bin/bash
# API endpoint and your API key
API_ENDPOINT="https://api.openai.com/v1/completions"
API_KEY="YOUR_API_KEY"
# Get user input
if [ $# -gt 0 ]; then
MESSAGE="$*"
else
read -p "Prompt: " -r MESSAGE
fi
# Remove non-command text and extract commands separated by &&
COMMANDS=$(echo "$MESSAGE" | grep -oE '(\w+\s*&&\s*)*\w+\s*' | sed 's/&&//g')
# Check if there are commands
if [ -z "$COMMANDS" ]; then
echo "No valid commands found."
exit 0
fi
# Prepare the data for API request
DATA=$(jq -n \
--arg prompt "You are a user asking for commands in your mac terminal. Please only list the commands separated by && and remove all other text that isn't a command: $COMMANDS" \
'{model: "text-davinci-003", prompt: $prompt, max_tokens: 50}')
# Make the API request
RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${API_KEY}" -d "$DATA" "$API_ENDPOINT")
echo "$RESPONSE"
# Extract the completion text from the response
COMPLETION=$(echo "$RESPONSE" | jq -r '.choices[0].text' | tr -d '\r\n')
# Remove any leading &&
COMPLETION=$(echo "$COMPLETION" | sed 's/^&&\s*//')
# Check if a completion is present
if [ -z "$COMPLETION" ] || [ "$COMPLETION" == "null" ]; then
echo "No valid completion found."
exit 0
fi
# Display the completion result
echo "Completion Result:"
echo "$COMPLETION"
# Prompt for confirmation
read -p "Confirm execution? [y/n]: " CHOICE
CHOICE=$(echo "$CHOICE" | tr '[:upper:]' '[:lower:]') # Convert choice to lowercase
# Execute the completion if the choice is affirmative
if [[ $CHOICE == "y" || $CHOICE == "yes" ]]; then
eval "$COMPLETION"
fi