Skip to content

Instantly share code, notes, and snippets.

@woodongwong
Created April 9, 2023 07:19
Show Gist options
  • Save woodongwong/7d186f164982ce483198bd384a005d72 to your computer and use it in GitHub Desktop.
Save woodongwong/7d186f164982ce483198bd384a005d72 to your computer and use it in GitHub Desktop.
Implement chatGPT streaming content output in the shell
#!/usr/bin/env sh
OPENAI_API_KEY="sk-xxx"
request_params=$(
cat <<EOF
{
"model": "gpt-3.5-turbo",
"stream": true,
"messages": [
{
"role": "user",
"content": "$1"
}
]
}
EOF
)
curl --header "Authorization: Bearer $OPENAI_API_KEY" \
--header 'Content-Type: application/json' \
--data "$request_params" -N -s 'https://api.openai.com/v1/chat/completions' |
awk -F 'data: ' '{print $2; system("")}' |
jq --unbuffered -R 'fromjson?' |
jq --unbuffered -r '(.choices[].delta.content)? | select(. != null)' |
awk '{printf "%s", $0}'
echo
@woodongwong
Copy link
Author

chat-gpt-streaming-output.sh.2023-04-09.15-30-51.online-video-cutter.com.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment