Prompt Genius

Transforming Natural Language Into Terminal Commands

Posted on March 16, 2023  •  7 minutes  • 1333 words
Table of contents

Source - Professional-Use6370

I want to see if ChatGPT is capable of coming up with the code itself for the cli app.

Prompt

You are an AI programming assistant.

First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail, then output the code in a single code block.
You will minimize any other prose.

- bash script using jq, curl, openai api key: that will take a natural language command and interpret it into a useful bash command
- use model gpt-3.5-turbo
- put the script in a code block
- make the user confirm the command before running
- use /v1/chat/completions
- Usage: pls [natural language command]

Chat History

You are an AI programming assistant.

First think step-by-step – describe your plan for what to build in pseudocode, written out in great detail, hen output the code in a single code block. You will minimize any other prose.

“Requirements:

jq binary (commandline JSON processor) curl binary (commandline HTTP client) openai api key

Usage:

pls [natural language command]”

ChatGPT »

Pseudocode:

  1. Take the user input natural language command as argument.
  1. Use curl to send a POST request to the OpenAI API endpoint /v1/chat/completions with the following parameters:

Model: gpt-3.5-turbo

Prompt: “Please execute the following command: [generated bash command]”

API key: [Your OpenAI API key]

  1. Use jq to extract the generated bash command from the API response.
  1. Display the generated bash command to the user and ask for confirmation.
  1. If the user confirms, execute the bash command using the system command in bash.

I had to run this several times to get the model version correct. There were lots of variations of code that kept using other models. ¯_(ツ)_/¯

Here’s some other script it came up with.

Incorrect Script #1

#!/bin/bash

# Define OpenAI API endpoint and authentication variables
OPENAI_API_ENDPOINT=https://api.openai.com/v1/chat/completions
# OPENAI_API_KEY=<insert your API key here>

# Check for required dependencies
command -v jq >/dev/null 2>&1 || { echo >&2 "Please install jq (https://stedolan.github.io/jq/)"; exit 1; }
command -v curl >/dev/null 2>&1 || { echo >&2 "Please install curl (https://curl.se/)"; exit 1; }

# Parse user input and send it to the OpenAI API
read -p "Enter natural language command: " user_command
openai_response=$(curl -s "$OPENAI_API_ENDPOINT" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
      "prompt": "'"$user_command"'",
      "temperature": 0.5,
      "max_tokens": 100,
      "top_p": 1,
      "frequency_penalty": 0,
      "presence_penalty": 0
  }')

# Extract suggested bash command from OpenAI response
suggested_command=$(echo "$openai_response" | jq -r '.choices[0].text' | sed 's/^ *//g' | sed 's/ *$//g')

# Prompt user to confirm command before executing it
read -p "Suggested command: $suggested_command. Confirm to execute (y/n): " confirm_command
if [ "$confirm_command" = "y" ]; then
    bash -c "$suggested_command"
else
    echo "Command not executed."
fi

Incorrect Script #2

#!/bin/bash

# Define OpenAI API key
OPENAI_API_KEY="<your_api_key_here>"

# Define OpenAI API endpoint
OPENAI_API_ENDPOINT="https://api.openai.com/v1/chat/completions"

# Define function to prompt user for confirmation
confirm() {
    read -r -p "${1:-Are you sure? [y/N]} " response
    case "$response" in
        [yY][eE][sS]|[yY]) 
            true
            ;;
        *)
            false
            ;;
    esac
}

# Take input from user
NL_COMMAND="$1"

# Send input to OpenAI API and extract suggested bash command
SUGGESTED_COMMAND=$(curl -s -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer $OPENAI_API_KEY" \
     -d "{\"model\": \"davinci-codex-1\", \"prompt\": \"$NL_COMMAND\", \"max_tokens\": 128, \"temperature\": 0.5, \"stop\": \"\n\"}" \
     $OPENAI_API_ENDPOINT | jq -r '.choices[].text')

# Prompt user for confirmation
echo "Suggested command: $SUGGESTED_COMMAND"
if confirm "Do you want to run this command? [y/N]"; then
    # Execute suggested command
    eval "$SUGGESTED_COMMAND"
else
    echo "Command not executed."
fi

After trying many times it finally came up with a version with the correct model but the parameters were still incorrect for the call.

#!/bin/bash

# Step 1: Take the user input natural language command as argument
if [ -z "$1" ]; then
  echo "Usage: pls [natural language command]"
  exit 1
fi

# Step 2: Use curl to send a POST request to the OpenAI API endpoint /v1/chat/completions
OPENAI_API_KEY=[Your OpenAI API key]
model="gpt-3.5-turbo"
response=$(curl -s -X POST https://api.openai.com/v1/chat/completions \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $OPENAI_API_KEY" \
            -d '{
                "model": "'$model'",
                "prompt": "Please execute the following command: '$1'",
                "temperature": 0.7,
                "max_tokens": 256,
                "stop": ["\n"]
            }')

# Step 3: Use jq to extract the generated bash command from the API response
generated_command=$(echo $response | jq -r '.choices[].text')

# Step 4: Display the generated bash command to the user and ask for confirmation
echo "Generated bash command: $generated_command"
read -p "Confirm to execute this command (y/n)? " choice

if [ "$choice" == "y" ]; then
  # Step 5: Execute the bash command using the system command in bash
  echo "Executing the command..."
  eval $generated_command
else
  echo "Aborting."
fi

Commands

Now lets use it to run some commands. I named my script plz not to collide with pls.

plz list all files in the current directory
jq: error (at <stdin>:1): Cannot iterate over null (null)
Generated bash command: 
Confirm to execute this command (y/n)? 

Remember I was mentioning the parameters were incorrect for the call.

Now lets use the pls script from the reddit article:

➜ bin ✗ ./pls list all files in the current directory
ls
Press any button to continue, or n to cancel: 
Executing command...

folder		plz		pls

Here’s a link to the script: pls

GPT-4 Update

You are an AI programming assistant.

First think step-by-step – describe your plan for what to build in pseudocode, written out in great detail, then output the code in a single code block. You will minimize any other prose.

Pseudocode:

  1. Check if dependencies (jq, curl) are installed
  1. Define API_KEY and MODEL
  1. Parse input (natural language command)
  1. Define the function to call the OpenAI API with input command
  1. Call the API function
  1. Parse the API response to extract the suggested command
  1. Display the suggested command to the user
  1. Ask for user confirmation to run the suggested command
  1. Run the command if the user confirms
#!/bin/bash

# Check if dependencies are installed
command -v jq >/dev/null 2>&1 || { echo >&2 "jq is required but not installed. Aborting."; exit 1; }
command -v curl >/dev/null 2>&1 || { echo >&2 "curl is required but not installed. Aborting."; exit 1; }

# Define API_KEY and MODEL
API_KEY="your_openai_api_key"
MODEL="gpt-3.5-turbo"
ENDPOINT="https://api.openai.com/v1/chat/completions"

# Parse input
input_command="$*"

# Define the function to call the OpenAI API with input command
call_openai_api() {
  curl -s -X POST "${ENDPOINT}" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer ${API_KEY}" \
    -d "{
      \"model\": \"${MODEL}\",
      \"messages\": [
        {
          \"role\": \"system\",
          \"content\": \"You are a helpful assistant that translates English commands to bash commands. Your response should contain ONLY the command and NO explanation. Do NOT ever use newlines to separate commands, instead use ; or &&.\"
        },
        {
          \"role\": \"user\",
          \"content\": \"${input_command}\"
        }
      ]
    }"
}

# Call the API function
response=$(call_openai_api)

# Parse the API response to extract the suggested command
suggested_command=$(echo "${response}" | jq -r '.choices[0].message.content' | tr -d '\n')

# Display the suggested command to the user
echo "Suggested command: ${suggested_command}"

# Ask for user confirmation to run the suggested command
read -p "Do you want to run this command? (y/n): " confirmation

# Run the command if the user confirms
if [[ "${confirmation}" =~ ^[Yy]$ ]]; then
  eval "${suggested_command}"
else
  echo "Command not executed."
fi

This script run with having to make any adjustments. So GPT-4 FTW in code generation!!