Skip to content

Commit

Permalink
Add continuation support for chatgpt
Browse files Browse the repository at this point in the history
  • Loading branch information
Zeming Lin authored and ebetica committed Jul 15, 2023
1 parent 926587a commit 78b0a28
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions chatgpt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -124,22 +124,31 @@ request_to_image() {
# request to OpenAPI API chat completion endpoint function
# $1 should be the message(s) formatted with role and content
request_to_chat() {
local message="$1"
if [ "$CONTEXT" = true ]; then
local message=$([[ -s /tmp/chatgpt-last-session.json ]] && jq ". += [$1]" /tmp/chatgpt-last-session.json || "$1")
else
local message='[
{"role": "system", "content": "'"$escaped_system_prompt"'"},
'"$1"'
]'
fi
escaped_system_prompt=$(escape "$SYSTEM_PROMPT")
local json='{
"model": "'"$MODEL"'",
"max_tokens": '$MAX_TOKENS',
"temperature": '$TEMPERATURE',
"messages": '$message'
}'

curl https://api.openai.com/v1/chat/completions \
local response=$(curl https://api.openai.com/v1/chat/completions \
-sS \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $OPENAI_KEY" \
-d '{
"model": "'"$MODEL"'",
"messages": [
{"role": "system", "content": "'"$escaped_system_prompt"'"},
'"$message"'
],
"max_tokens": '$MAX_TOKENS',
"temperature": '$TEMPERATURE'
}'
-d "$json")
local response_message="$(echo $response | jq '.choices[0].message')"
jq ".[0].messages += [.[1].choices[0].message] | .[0].messages" -s <(echo $json) <(echo $response) > /tmp/chatgpt-last-session.json

echo $response
}

# build chat context before each request for /completions (all models except
Expand Down Expand Up @@ -386,7 +395,7 @@ while $running; do

if [[ "$prompt" =~ ^command: ]]; then
echo -e "$OVERWRITE_PROCESSING_LINE"
echo -e "${CHATGPT_CYAN_LABEL} ${response_data}" | fold -s -w $COLUMNS
echo -e "${CHATGPT_CYAN_LABEL} ${response_data}" | fold -s -w ${COLUMNS:-80}
dangerous_commands=("rm" ">" "mv" "mkfs" ":(){:|:&};" "dd" "chmod" "wget" "curl")

for dangerous_command in "${dangerous_commands[@]}"; do
Expand Down Expand Up @@ -421,7 +430,7 @@ while $running; do
echo -e "${CHATGPT_CYAN_LABEL}"
echo "${response_data}" | glow -
else
echo -e "${CHATGPT_CYAN_LABEL}${response_data}" | fold -s -w "$COLUMNS"
echo -e "${CHATGPT_CYAN_LABEL}${response_data}" | fold -s -w "${COLUMNS:-80}"
fi
add_assistant_response_to_chat_message "$(escape "$response_data")"

Expand All @@ -447,7 +456,7 @@ while $running; do
else
# else remove empty lines and print
formatted_text=$(echo "${response_data}" | sed '1,2d; s/^A://g')
echo -e "${CHATGPT_CYAN_LABEL}${formatted_text}" | fold -s -w $COLUMNS
echo -e "${CHATGPT_CYAN_LABEL}${formatted_text}" | fold -s -w ${COLUMNS:-80}
fi

if [ "$CONTEXT" = true ]; then
Expand Down

0 comments on commit 78b0a28

Please sign in to comment.