-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt
executable file
·79 lines (55 loc) · 2.18 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env bash
set -euo pipefail
SOURCE_DIR="$(dirname $0)"
source "$SOURCE_DIR/api-key"
SYSTEM_INPUT="You are a helpful assistant but your answers are short line you are a robot. You don't omit useful information but you don't repeat the question and you don't use filler words or try to be polite. When the context is not clear, it's most likely related to computer programming."
echo "What's your question?"
if [ -z "${USER_INPUT:-}" ]; then
USER_INPUT="$(cat)"
fi
: Create the request JSON
REQUEST_JSON="$(jq \
--raw-input \
--compact-output \
--null-input \
--arg model "$MODEL" \
--arg input "$USER_INPUT" \
--argjson max_tokens "$MAX_TOKENS" \
--arg system "$SYSTEM_INPUT" \
'{model: $model, messages: [{role: "system", content: $system}, {role: "user", content: $input}], temperature: 0, max_tokens: $max_tokens}')"
# echo "Request JSON: $(echo "$REQUEST_JSON" | jq .)""
: Send the request:
echo "Sending request..."
RESPONSE_JSON="$(curl https://api.openai.com/v1/chat/completions \
--silent \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--data "$REQUEST_JSON")"
ERROR="$(echo "$RESPONSE_JSON" | jq --raw-output '.error.message')"
if [ "$ERROR" != "null" ]; then
echo "ERROR: $RESPONSE_JSON" >&2
exit 1
fi
# echo "Response JSON: $(echo "$RESPONSE_JSON" | jq .)""
: Parse the response
ANSWER="$(echo "$RESPONSE_JSON" | jq --raw-output '.choices[] | .message.content')"
echo "Answer:"
echo
echo "$ANSWER"
echo
USAGE_TOKENS="$(echo "$RESPONSE_JSON" | jq '.usage.total_tokens')"
COST_CENTS="$(echo "$RESPONSE_JSON" | jq \
--argjson input_cost "$INPUT_TOKEN_COST_CENTS" \
--argjson output_cost "$OUTPUT_TOKEN_COST_CENTS" \
'.usage | ($input_cost * .prompt_tokens) + ($output_cost * .completion_tokens)')"
printf "%s cost: %g cents\n" "$MODEL" "$COST_CENTS"
: Log the interaction
LOG_JSON="$(jq \
--raw-input \
--compact-output \
--null-input \
--arg timestamp "$(date +"%Y-%m-%d %H:%M:%S")" \
--arg request "$REQUEST_JSON" \
--arg response "$RESPONSE_JSON" \
'{timestamp: $timestamp, request: $request, response: $response}')"
echo "$LOG_JSON" >> "$SOURCE_DIR/log"