From 687c5cce3fd366a0132cea07a391637b5d40c5e2 Mon Sep 17 00:00:00 2001 From: git Date: Mon, 11 Aug 2025 14:09:57 +0100 Subject: [PATCH] Add askChatGPT --- askChatGPT | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 askChatGPT diff --git a/askChatGPT b/askChatGPT new file mode 100644 index 0000000..bc86ca8 --- /dev/null +++ b/askChatGPT @@ -0,0 +1,116 @@ +#!/usr/bin/env bash + +# askChatGPT - A simple Bash client for OpenAI Chat API +# Requires: curl, jq +# Env var: OPENAI_API_KEY must be set + +set -euo pipefail + +MODEL="gpt-4o-mini" +PREPEND_TEXT="" +CONTENT_FILE="" +LIST_MODELS=0 + +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 +EOF +} + +# Parse args +while [[ $# -gt 0 ]]; do + case "$1" in + -model) + MODEL="$2" + shift 2 + ;; + --list-models) + LIST_MODELS=1 + shift + ;; + -prepend) + PREPEND_TEXT="$2" + shift 2 + ;; + -content-from-file) + CONTENT_FILE="$2" + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + *) + PROMPT_WORDS+=("$1") + shift + ;; + esac +done + +# Check API key +if [[ -z "${OPENAI_API_KEY:-}" ]]; then + echo "Error: OPENAI_API_KEY is not set." + exit 1 +fi + +# List models +if [[ "$LIST_MODELS" -eq 1 ]]; then + curl -s https://api.openai.com/v1/models \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + | jq -r '.data[].id' | sort + exit 0 +fi + +# Build prompt +PROMPT="" +if [[ -n "$PREPEND_TEXT" ]]; then + PROMPT+="$PREPEND_TEXT " +fi + +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[*]}" +else + # Read from stdin if nothing else provided + if ! [ -t 0 ]; then + PROMPT+="$(cat)" + else + echo "Error: No prompt provided." + usage + exit 1 + fi +fi + +# Send request +RESPONSE=$(curl -s https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d @- <