~kmaasrud/shatgpt

53b33905cfa85e03724e1ccabe8cbe41ca8e0779 — Knut Magnus Aasrud 1 year, 6 months ago a19a3e8
revamp field getting and add editor support
1 files changed, 48 insertions(+), 4 deletions(-)

M shatgpt
M shatgpt => shatgpt +48 -4
@@ 1,4 1,8 @@
#!/usr/bin/env dash
#!/usr/bin/env sh

err() {
    printf 'error: %s\n' "$1" >&2
}

has() {
    # check if a command exists


@@ 70,10 74,35 @@ mkbody() {
}

get_field() {
    # get a field from a json string by grepping
    # get a field from a json string
    # $1 - json string
    # $2 - field to grep
    printf '%s\n' "$1" | grep -o "\"$2\":\"[^\"]*" | sed "s/\"$2\":\"//"
    case $1 in
      *"$2"*);;
      *) return;;
    esac

    tmp="${1#*\"$2\":\"}"
    while [ -n "$tmp" ]; do
      rest="${tmp#?}"
      char="${tmp%"$rest"}"
      tmp="$rest"
      case $char in
        '"')
          break
        ;;
        '\')
          printf '%s' "$char"
          i=$((i + 1))
          rest="${tmp#?}"
          char="${tmp%"$rest"}"
          tmp="$rest"
        ;;
        *);;
      esac
      printf '%s' "$char"
      i=$((i + 1))
    done
}

process_event() {


@@ 98,8 127,8 @@ stream_events() {
	    fi
            process_event "$event"
        done
        printf '\n'
    else
        printf '%s\n' "Error: curl not found"
        cleanup
        err "curl not found"
        exit 1


@@ 119,6 148,21 @@ term() {
trap term INT TERM

main() {
    case "$1" in
        -h|--help)
            printf '%s\n' "Usage: shatgpt [prompt]"
            exit 0
        ;;
        -e|--edit)
            prompt=$(mktemp)
            printf '%s' "$*" > $prompt
            $(editor) "$prompt"
            prompt="$(mkprompt "$(cat $prompt)")"
        ;;
        *)
            prompt="$(mkprompt "$*")"
        ;;
    esac

    stream_events "https://api.openai.com/v1/chat/completions" "$(mkbody "$prompt")"
}