-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt
executable file
·65 lines (56 loc) · 1.42 KB
/
gpt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/bash
set -o pipefail
export LANG=C.UTF-8
export API=${API:-https://api.openai.com/v1/chat/completions}
export KEY=${KEY:-$(< ~/.config/secrets/openai)}
export MODEL=${MODEL:-gpt-4o}
if [[ -t 0 ]] && [[ $# -eq 0 ]] || [[ $1 == -* ]]; then
echo "Usage: ${0##*/} [PROMPT] < INPUT" 2>&1
exit 64
elif [[ -t 0 ]]; then
exec < /dev/null
fi
exec 3<<EOF
{
"model": env.MODEL,
"messages": [
{ "role": "developer", "content": env.PROMPT },
{ "role": "user", "content": . | rtrimstr("\\n") }
],
"n": (env.COUNT | tonumber? // 1)
} | .messages[] |= select(.content and .content != "")
EOF
exec 4<<EOF
Authorization: Bearer $KEY
Content-Type: application/json
EOF
exec 5<<EOF
.choices
| map(
if .finish_reason == "stop" then
.message.content
else
.message.content + "\\n\\n[Truncated: \\(.finish_reason)]"
end
)
| join("\\n\\n\\n")
| gsub("[‘’]"; "'")
| gsub("[“”]"; "\\"")
| gsub("…"; "...")
| gsub(" ?— ?"; " - ")
EOF
PROMPT=$* jq -f /dev/fd/3 -s -R \
| curl -d @- -f -m 30 -s -H @/dev/fd/4 "$API" \
| jq -e -f /dev/fd/5 -r \
| fmt -s -w 76
set $? ${PIPESTATUS[@]}
if [[ $3 -eq 6 ]] || [[ $3 -eq 7 ]]; then
echo "Failed to connect to host"
elif [[ $3 -eq 28 ]]; then
echo "Content generation timed out"
elif [[ $3 -ne 0 ]]; then
echo "Content generation failed: $3"
elif [[ $4 -ne 0 ]]; then
echo "Invalid response from model"
fi >&2
exit $(($1 != 0))