Skip to content

Instantly share code, notes, and snippets.

@arondeparon
Last active November 11, 2024 11:58
Show Gist options
  • Save arondeparon/1d176136f0738433aac8c1d00a3a9682 to your computer and use it in GitHub Desktop.
Save arondeparon/1d176136f0738433aac8c1d00a3a9682 to your computer and use it in GitHub Desktop.
Simple ChatGPT CLI wrapper
#!/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