-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaiv
executable file
·239 lines (218 loc) · 8.45 KB
/
aiv
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/bin/sh
#
#######################################################################
# Initial Configuration
#######################################################################
#
# === Initialize Shell Environment ====================================
set -u
umask 0022
export LC_ALL='C'
export PATH="$(command -p getconf PATH)${PATH:+:}:${PATH:-}"
# === Basic Configuration =============================================
CONFIG_DIR="$HOME/.config/aiv"
CONFIG_FILE="$CONFIG_DIR/config"
CONVERSATION="$CONFIG_DIR/conversation"
# === Usage Printing Function =========================================
print_usage_and_exit () {
cat <<-USAGE 1>&2
${0##*/} - AI Valve: Pipes for AI
Usage : ${0##*/} [options] [prompt]
Options : -c [file_pattern|-] Add context from files (glob pattern) or stdin (-)
In case there is no prompt in stdin(-), it will
only be added to the context.
-r Repeat the input before output
-e Continue previous conversation thread
-m MODEL Use specified model
(default: claude-3.7-sonnet-latest)
-h Display this help message
-v Display version information
-s [prompt] Overwite system prompt
Version : Sun Mar 2 14:23:42 JST 2025
USAGE
exit 1
}
# === Define Error Exit Function =======================================
error_exit () {
${2+:} false && echo "${0##*/}: $2" 1>&2
exit $1
}
# === JSON Functions ===================================================
json_escape() {
tab=" "
cr=$(printf '\r')
sed '
s/\\/\\\\/g;
s/"/\\"/g;
s/'"$tab"'/\\t/g
' | sed 's/'"$cr"'/\\r/g' | awk '
BEGIN { ORS=""; first=1 }
{
if (first) { first=0 }
else { print "\\n" }
print $0
}
'
}
json_extract() {
awk '{
gsub(/\\\\n/, "\n")
gsub(/\\n/, "\n")
gsub(/\\\\t/, "\t")
gsub(/\\t/, "\t")
gsub(/\\"/, "\"")
gsub(/\\\\r/, "\r")
gsub(/\\r/, "\r")
gsub(/^"|"$/, "")
print
}'
}
#######################################################################
# Prepare for the Main Routine
#######################################################################
# === Ensure Config ===================================================
[ -d "$CONFIG_DIR" ] || mkdir -p "$CONFIG_DIR"
[ -f "$CONFIG_FILE" ] || error_exit 1 "config file not found"
# === Load Config File ================================================
API_KEY=
MODEL=
MAX_TOKENS=
SYS_PROMPT=
while IFS='=' read -r key value; do
value=$(printf "%s\n" "$value" |
sed -e 's/^"//' -e 's/" *$//' |
tr -d '\n' )
case "$(echo "$key" | tr '[:upper:]' '[:lower:]')" in
api_key) API_KEY="$value" ;;
model) MODEL="$value" ;;
max_tokens) MAX_TOKENS="$value" ;;
system_prompt|sys_prompt) SYS_PROMPT="$value" ;;
esac
done << END
$(cat "$CONFIG_FILE" |
sed 's/#.*$//' |
sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' |
grep -v '^$' |
grep -Ei '^(API_KEY|MODEL|MAX_TOKENS|SYS_PROMPT)=' )
END
# === Parse Arguments =================================================
CONTXT_FILE=
EXTEND_PREV=
REPEAT_INPT=
PROMPT_ARG=
while getopts :c:earm:s:h opt
do
case $opt in
c) CONTXT_FILE="$CONTXT_FILE $OPTARG" ;;
e) EXTEND_PREV=true ;;
r) REPEAT_INPT=true ;;
m) MODEL="$OPTARG" ;;
s) SYS_PROMPT="$OPTARG" ;;
h | v ) print_usage_and_exit ;;
'?') error_exit 1 "Invalid Option: -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
PROMPT_ARG="$*"
# === Ensure Conversation File ========================================
touch $CONVERSATION
if [ ! -f "$CONVERSATION" ] || [ "$EXTEND_PREV" != "true" ]; then
if [ -n "$SYS_PROMPT" ]; then
printf "%s" "$SYS_PROMPT" |
json_escape |
sed 's/^\(.*\)$/"system":"\1","messages":[/' \
> "$CONVERSATION"
else
printf "%s\n" '"messages":[' \
> "$CONVERSATION"
fi
fi
#######################################################################
# Main Routine
#######################################################################
# === Build Contents ==================================================
if [ -t 0 ]; then
printf "%s" "$PROMPT_ARG"
else
awk -v ctx="$CONTXT_FILE" -v prompt="$PROMPT_ARG" ' #
BEGIN { #
if (length(ctx) > 0) split(ctx, files, " ") #
context = 0; #
for (i in files) { #
if (files[i] == "-") { #
context = 1 #
} else if (length(files[i])) { #
print "---CONTEXT_FILE:" files[i] "---" #
system("cat \"" files[i] "\"") #
print "---END---" #
} #
} #
} #
{ #
if (NR == 1) { #
if (context) print "---CONTEXT_TEXT---" #
else printf("%s\n---STDIN---\n", prompt); #
} #
print #
} #
END { #
if (context) { #
print "---END---" #
printf("%s", prompt); #
} else if (NR>0) { #
print "---END---" #
} else if (NR==0) { #
printf("%s", prompt); #
} #
}' #
fi |
json_escape |
sed 's/^\(.*\)$/{"role":"user","content": "\1"}/' |
{ #
if [ -s "$CONVERSATION" ] && #
tail -c 2 "$CONVERSATION" | grep -q '\['; #
then #
cat #
else #
sed 's/^/,/' #
fi #
} |
tee -a "$CONVERSATION" |
if [ -n "$REPEAT_INPT" ]; then
sed 's/.*---STDIN---\\n\(..*\)\\n---END---.*/\1/' |
json_extract
fi
# === End If We Have Only Context =====================================
if [ -z "$PROMPT_ARG" ] &&
printf "%s" "$CONTXT_FILE" | grep -Eq '(^-| - |-$)';
then
exit 0
fi
# === API Request & Response Processing ===============================
# Anthropic
URL="https://api.anthropic.com/v1/messages"
BODY_PARTS="{\"model\":\"$MODEL\",\"max_tokens\":$MAX_TOKENS,"
HEADERS=$(cat <<HEADERS
x-api-key: $API_KEY
anthropic-version: 2023-06-01
content-type: application/json
HEADERS)
REQ_CMD=
if command -v curl >/dev/null 2>&1; then
HEADERS=$(printf "%s" "$HEADERS" |
sed 's/.*/-H "&" /' |
tr -d '\n')
REQ_CMD="curl -s $URL $HEADERS -d @-"
else
error_exit 1 "curl not found"
fi
cat "$CONVERSATION" |
sed -e '1s/^/'"$BODY_PARTS"'/' -e '$s/$/]}/' |
tr -d '\n' |
eval "$REQ_CMD" |
sed 's/.*"content":\[{\(.*"}\)\],.*/\1/' |
sed 's/.*"text":\(".*[^\]}\)$/\1/' |
sed 's/^/,{"role": "assistant", "content": /' |
tee -a "$CONVERSATION" |
sed 's/.*"content": "\(.*\)"}$/\1/' |
json_extract