Skip to content

Instantly share code, notes, and snippets.

@beothorn
Created October 2, 2024 09:36
Show Gist options
  • Save beothorn/8b264b06f42fc1e006f22070af693619 to your computer and use it in GitHub Desktop.
Save beothorn/8b264b06f42fc1e006f22070af693619 to your computer and use it in GitHub Desktop.
Script for ubuntu that asks openai to prepare a command
#!/bin/bash
# Check if the OPENAI_API_KEY environment variable is set
if [ -z "$OPENAI_API_KEY" ]; then
echo "Error: OPENAI_API_KEY is not set."
exit 1
fi
# Check if an argument was passed
if [ -z "$1" ]; then
echo "Usage: $0 <command>"
exit 1
fi
# Combine all arguments into a single string
command="$*"
# Make the API request
response=$(curl -s https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": [
{
"type": "text",
"text": "Outputs one liners for ubuntu terminal based on a request. Example:\nRequest:\nfind and rename all images recursively, append a _image in the file name.\nResponse:\n# This command does the following:\n# 1. `find . -type f`: Finds all files recursively starting from the current directory.\n# 2. `\\( -iname \"*.jpg\" -o -iname \"*.jpeg\" -o -iname \"*.png\" -o -iname \"*.gif\" -o -iname \"*.bmp\" -o -iname \"*.tiff\" \\)`: Filters the search to include only image files with specific extensions.\n# 3. `-exec bash -c '\''mv \"$0\" \"${0%.*}_image.${0##*.}\"'\'' {} \\;`: Executes the `mv` command to rename each found file. The `${0%.*}_image.${0##*.}` part appends `_image` before the file extension.\nThis command will work for `.jpg`, `.jpeg`, `.png`, `.gif`, `.bmp`, and `.tiff` files. You can add or remove file extensions as needed.\n#COMMAND:\nfind . -type f \\( -iname \"*.jpg\" -o -iname \"*.jpeg\" -o -iname \"*.png\" -o -iname \"*.gif\" -o -iname \"*.bmp\" -o -iname \"*.tiff\" \\) -exec bash -c '\''mv \"$0\" \"${0%.*}_image.${0##*.}\"'\'' {} \\;"
}
]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "'"$command"'"
}
]
}
],
"temperature": 1,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
}')
# Use jq to extract the content from the response
command_output=$(echo "$response" | jq -r '.choices[0].message.content' 2>/dev/null)
# Check if jq was successful or if there was an error in the response
if [ $? -ne 0 ] || [ "$command_output" == "null" ]; then
echo "Error: Failed to extract command from the response."
echo "Response: $response"
exit 1
fi
# Output the extracted command
echo "$command_output"
echo "$command_output" >> ~/.aiHistory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment