diff --git a/askChatGPT b/askChatGPT old mode 100644 new mode 100755 index bc86ca8..96180da --- a/askChatGPT +++ b/askChatGPT @@ -1,5 +1,4 @@ #!/usr/bin/env bash - # askChatGPT - A simple Bash client for OpenAI Chat API # Requires: curl, jq # Env var: OPENAI_API_KEY must be set @@ -10,6 +9,7 @@ MODEL="gpt-4o-mini" PREPEND_TEXT="" CONTENT_FILE="" LIST_MODELS=0 +declare -a PROMPT_WORDS=() # <-- important: initialize the array usage() { cat < Set the OpenAI model (default: $MODEL) - --list-models List available models from OpenAI - -prepend Text to prepend before the main prompt - -content-from-file Read prompt content from file - -h, --help Show this help message - -Examples: - $0 "Write a haiku about Bash scripting" - $0 -model gpt-4o -prepend "Explain like I'm five:" "What is quantum physics?" - $0 -content-from-file notes.txt + --list-models List available models from OpenAI + -prepend Text to prepend before the main prompt + -content-from-file Read prompt content from file + -h, --help Show this help message EOF } @@ -33,32 +28,25 @@ EOF while [[ $# -gt 0 ]]; do case "$1" in -model) - MODEL="$2" - shift 2 - ;; + MODEL="$2"; shift 2 ;; --list-models) - LIST_MODELS=1 - shift - ;; + LIST_MODELS=1; shift ;; -prepend) - PREPEND_TEXT="$2" - shift 2 - ;; + PREPEND_TEXT="$2"; shift 2 ;; -content-from-file) - CONTENT_FILE="$2" - shift 2 - ;; + CONTENT_FILE="$2"; shift 2 ;; -h|--help) - usage - exit 0 - ;; + usage; exit 0 ;; *) - PROMPT_WORDS+=("$1") - shift - ;; + PROMPT_WORDS+=("$1"); shift ;; esac done +# Check deps +for dep in curl jq; do + command -v "$dep" >/dev/null 2>&1 || { echo "Error: '$dep' is required."; exit 1; } +done + # Check API key if [[ -z "${OPENAI_API_KEY:-}" ]]; then echo "Error: OPENAI_API_KEY is not set." @@ -74,23 +62,15 @@ if [[ "$LIST_MODELS" -eq 1 ]]; then fi # Build prompt -PROMPT="" -if [[ -n "$PREPEND_TEXT" ]]; then - PROMPT+="$PREPEND_TEXT " -fi - +PROMPT_MAIN="" if [[ -n "$CONTENT_FILE" ]]; then - if [[ ! -f "$CONTENT_FILE" ]]; then - echo "Error: file '$CONTENT_FILE' not found." - exit 1 - fi - PROMPT+="$(<"$CONTENT_FILE")" -elif [[ ${#PROMPT_WORDS[@]:-0} -gt 0 ]]; then - PROMPT+="${PROMPT_WORDS[*]}" + [[ -f "$CONTENT_FILE" ]] || { echo "Error: file '$CONTENT_FILE' not found."; exit 1; } + PROMPT_MAIN="$(<"$CONTENT_FILE")" +elif (( ${#PROMPT_WORDS[@]} > 0 )); then + PROMPT_MAIN="${PROMPT_WORDS[*]}" else - # Read from stdin if nothing else provided if ! [ -t 0 ]; then - PROMPT+="$(cat)" + PROMPT_MAIN="$(cat)" else echo "Error: No prompt provided." usage @@ -98,19 +78,36 @@ else fi fi +PROMPT_FULL="" +if [[ -n "$PREPEND_TEXT" ]]; then + PROMPT_FULL+="$PREPEND_TEXT"$'\n\n' +fi +PROMPT_FULL+="$PROMPT_MAIN" + +# JSON-escape content safely +JSON_CONTENT=$(printf '%s' "$PROMPT_FULL" | jq -Rs .) + # Send request RESPONSE=$(curl -s https://api.openai.com/v1/chat/completions \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer $OPENAI_API_KEY" \ - -d @- <