#!/bin/bash # Examples of reading the arguments readonly arg_count=$# readonly first_arg=$1 readonly all_args=$* # Construct and make an OpenAI query openai_query () { # Check if a query has been provided, otherwise use a default local prompt="haiku about c++" [[ -z $* ]] || prompt=$* # Models # The first is the most accurate if a little slow # But it does fail a lot, perhaps because it gets hammered as the default? # text-davinci-003 # text-davinci-002 # text-davinci-001 # text-curie-003 # Create request JSON request=$(cat <&2 # Otherwise we're good, but trim the first two newlines of the response echo -e "$response2" return done # Report the error response if we've got here after retrying # This error JSON will end up in the input file instead of the response echo "COMPUTER_SAYS_NO: $response2" } # Process a simple command line query if [[ $arg_count -ge 2 ]]; then # Send all command line params as a prompt prompt=$all_args openai_query_with_retry "$prompt" exit 0 fi # Create a tmp file in case we're overwriting the input file readonly temp_file=$(mktemp) # Process a named file or stdin if [[ $arg_count -eq 0 ]] || [[ $arg_count -eq 1 ]]; then # Preserve leading spaces # Otherwise we lose the indents in code excerpts IFS='' # By magic this works for both stdin and a file # If first arg is undefined, cat just passes on stdin cat $first_arg | while read -r line; do # Check if the line starts and ends with a brace if [[ $line =~ ^\{(.*)\}$ ]]; then # Use the bit between the braces as the prompt prompt=${BASH_REMATCH[1]} openai_query_with_retry "$prompt" else echo "$line" fi done fi | tee "$temp_file" if [[ $arg_count -eq 1 ]]; then cp "$temp_file" "$first_arg" echo cp "$temp_file" "$first_arg" >&2 fi # Tidy up after ourselves rm "$temp_file" echo rm "$temp_file" >&2