Last active
November 11, 2024 11:58
-
-
Save arondeparon/1d176136f0738433aac8c1d00a3a9682 to your computer and use it in GitHub Desktop.
Simple ChatGPT CLI wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Set your OpenAI API key | |
OPENAI_API_KEY= | |
# Initialize input variable | |
input="" | |
# Determine input source: stdin or command-line argument | |
if [ -p /dev/stdin ]; then | |
# Use piped input and format it with "stdin: ..." prefix | |
stdin_content=$(cat) | |
input="stdin: $stdin_content" | |
fi | |
# If an additional command-line argument is provided, add it on a new line | |
if [ -n "$1" ]; then | |
input="$input | |
$1" | |
fi | |
# Check if we have any input to process | |
if [ -z "$input" ]; then | |
echo "Error: No input provided. Please pipe content or pass an argument." | |
exit 1 | |
fi | |
# Escape special characters in the input for safe JSON formatting | |
escaped_input=$(echo "$input" | jq -Rs .) | |
# Send the input to OpenAI API and output the response | |
response=$(curl -s https://api.openai.com/v1/chat/completions \ | |
-H "Authorization: Bearer $OPENAI_API_KEY" \ | |
-H "Content-Type: application/json" \ | |
-d "{ | |
\"model\": \"gpt-4\", | |
\"messages\": [{\"role\": \"user\", \"content\": $escaped_input}], | |
\"max_tokens\": 100 | |
}") | |
# Parse and display the response | |
echo "$response" | jq -r '.choices[0].message.content' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment