~kmaasrud/shatgpt

a19a3e863b73712a4b64903b3a40b975bcbe9ccf — Knut Magnus Aasrud 10 months ago 2ec685c
add a role
1 files changed, 47 insertions(+), 18 deletions(-)

M shatgpt
M shatgpt => shatgpt +47 -18
@@ 7,6 7,31 @@ has() {
    [ -x "$cmd" ] || return 1
}

editor() {
    # get the user's editor
    printf '%s' "${EDITOR:-nano}"
}

shell() {
    # get the user's editor
    printf '%s' "${SHELL:-sh}"
}

os() {
    # get the user's os
    printf '%s' "$(uname -s)"
}

hostname() {
    # get the user's hostname
    printf '%s' "$(uname -n)"
}

cwd() {
    # get the current working directory
    printf '%s' "${PWD:-$(pwd)}"
}

clear_line() {
    # clear the current line and place cursor at the beginning
    printf '\r\033[K'


@@ 27,10 52,21 @@ spinner() {
    done
}

make_body() {
mkprompt() {
    # make a preprompt to send to the openai chat api
    prompt="Provide only $(shell) commands for OS $(os) without any description."
    prompt="$prompt The user is currently in the directory \`$(cwd)\` on a machine called $(hostname)."
    prompt="$prompt If there is a lack of details, provide most logical solution."
    prompt="$prompt Ensure the output is a valid shell command."
    prompt="$prompt If multiple steps are required, try to combine them together."
    prompt="$prompt The request is: $1"
    printf '%s\n' "$prompt"
}

mkbody() {
    # make a body to send to the openai chat api
    # $1 - prompt
    printf '%s\n' "{\"model\": \"gpt-3.5-turbo\", \"stream\": true, \"messages\": [{\"role\": \"user\", \"content\": \"$1\"}]}"
    printf '%s\n' "{\"model\": \"gpt-3.5-turbo\", \"stream\": true, \"messages\": [{\"role\": \"user\", \"content\": \"$*\"}]}"
}

get_field() {


@@ 64,34 100,27 @@ stream_events() {
        done
    else
        printf '%s\n' "Error: curl not found"
        cleanup
        err "curl not found"
        exit 1
    fi
}

cleanup() {
    # cleanup function to be called on script termination
    # Add any cleanup tasks here
    kill $spinner_pid 2>/dev/null
    printf '\n'
    clear_line
}

term() {
    cleanup
    exit 0
}

trap cleanup INT TERM
trap term INT TERM

main() {

    stream_events "https://api.openai.com/v1/chat/completions" "$(make_body "$*")"

    cleanup

    # content=$(get_field "$response" content)
    #
    # kill "$spinner_pid" >/dev/null 2>&1
    # clear_line
    #
    # printf '%s\n' "$response"
    # printf '\n%s\n' "$response" | json '"choices"' 0 '"message"' '"content"'
    # printf '\n%s\n' "$response" | json '"choices"' 0 '"message"' '"content"' | trim_quotes | fold -sw 80
    stream_events "https://api.openai.com/v1/chat/completions" "$(mkbody "$prompt")"
}

main "$*"