-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy paths-pilot
executable file
·1129 lines (1018 loc) · 40.9 KB
/
s-pilot
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# set -x
SHELL_PILOT_CONFIG_PATH="/usr/local/bin"
SHELL_PILOT_PLUGINS_PATH="${SHELL_PILOT_CONFIG_PATH}/plugins"
COMMON_CONFIG_FILE="${SHELL_PILOT_CONFIG_PATH}/spilot_common.sh"
source $COMMON_CONFIG_FILE
source "${SHELL_PILOT_CONFIG_PATH}/spilot_llm_rq_apis.sh"
source "${SHELL_PILOT_PLUGINS_PATH}/package_version.sh"
source "${SHELL_PILOT_PLUGINS_PATH}/system_alias.sh"
SPINNER_SIGNAL_FILE=${SPILOT_FILES_DEFAULT_DIR}/spilot_spinner_signal
# check if the OPENAI_KEY is set
if [[ -z "$OPENAI_KEY" && "$USE_API" == "openai" ]]; then
echo "You need to set your OPENAI_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export OPENAI_KEY=YOUR_KEY_HERE"
exit 1
fi
# check if the MISTRAL_API_KEY is set
if [[ -z "$MISTRAL_API_KEY" && "$USE_API" == "mistralai" ]]; then
echo "You need to set your MISTRAL_API_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export MISTRAL_API_KEY=YOUR_KEY_HERE"
exit 1
fi
# check if the ZHIPUAI_API_KEY is set
if [[ -z "$ZHIPUAI_API_KEY" && "$USE_API" == "zhipuai" ]]; then
echo "You need to set your ZHIPUAI_API_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export ZHIPUAI_API_KEY=YOUR_KEY_HERE"
exit 1
fi
# check if the ZHIPUAI_API_KEY is set
if [[ -z "$ANTHROPIC_API_KEY" && "$USE_API" == "athropic" ]]; then
echo "You need to set your ANTHROPIC_API_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export ANTHROPIC_API_KEY=YOUR_KEY_HERE"
exit 1
fi
# check if the MOONSHOT_API_KEY is set
if [[ -z "$MOONSHOT_API_KEY" && "$USE_API" == "moonshot" ]]; then
echo "You need to set your MOONSHOT_API_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export MOONSHOT_API_KEY=YOUR_KEY_HERE"
exit 1
fi
# check if the OLLAMA host is set
if [[ "$USE_API" == "ollama" ]]; then
if [[ -z "$OLLAMA_SERVER_IP" ]]; then
echo "Error: OLLAMA_SERVER_IP is not set in the configuration file."
exit 1
fi
if ! [[ $OLLAMA_SERVER_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: OLLAMA_SERVER_IP is not a valid IP address."
exit 1
fi
fi
# check if the OLLAMA host is set
if [[ "$USE_API" == "localai" ]]; then
if [[ -z "$LOCALAI_SERVER_IP" ]]; then
echo "Error: LOCALAI_SERVER_IP is not set in the configuration file."
exit 1
fi
if ! [[ $LOCALAI_SERVER_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Error: LOCALAI_SERVER_IP is not a valid IP address."
exit 1
fi
fi
# check if the NOVITA_API_KEY is set
if [[ -z "$NOVITA_API_KEY" && "$USE_API" == "novita" ]]; then
echo "You need to set your NOVITA_API_KEY to use this script!"
echo "You can set it temporarily by running this on your terminal: export NOVITA_API_KEY=YOUR_KEY_HERE"
exit 1
fi
usage() {
cat <<EOF
A simple, lightweight shell script to use OpenAI's Language Models and DALL-E
or Ollama models or MistralAI models or LocalAI or ZhupuAI or Anthropic models
from the terminal without installing Python or Node.js.
Open Source and written in 100% Shell (Bash).
https://github.com/reid41/shell-pilot.git
For default model:
OpenAI: "gpt-3.5-turbo" model
Ollama: "llama2" model.
MistralAI: "mistral-small" model.
LocalAI: "gpt-4" model.
ZhipuAI: "glm-4" model.
Anthropic: "claude-3-opus-20240229" model.
Moonshot: "moonshot-v1-8k" model.
It will enter "chat" mode without any options, here are some commands you can use:
Commands:
history - To view your chat history
models - To get a list of the models available at OpenAI/localai/ollama/mistralai
model: - To view all the information on a specific model, start a prompt with model: and the model id as it appears in the list of models. For example: "model:text-babbage:001" will get you all the fields for text-babbage:001 model
cmd: - To get a command with the specified functionality and run it, just type "cmd:" and explain what you want to achieve. The script will always ask you if you want to execute the command.
Options:
cmp, -cmp, --change-model-provider Change the model provider between openai,
ollama, mistralai, localai, zhipuai, anthropic, moonshot
e, -e, --edit Edit the configuration file directly
ip, -ip, --init-prompt Provide initial chat prompt to use in context
ipf, -ipf --init-prompt-from-file Provide initial prompt from file
p, -p, --prompt Provide prompt instead of starting chat
pf, --prompt-from-file Provide prompt from file
mlp | -mlp | --multi-line-prompt Allow multi-line prompts during chat mode
t, -t, --temperature Update Temperature
mt, -mt --max-tokens Update Max number of tokens
lc, -lc, --list-config List s-pilot common config
lm, -lm, --list-models List available openAI/ollama models
lr, -lr, --list-chat-record List chat record files
dr, -dr, --delete-record Delete chat record file
m, -m, --model Update the Model to use
h, -h, --help list available options and usage
v, -v, --version Show the version of the script
cr, -cr, --chat-recording Enable chat recording, which will save all the chat history in a file
c, -c, --chat-context For models that do not support chat context by
default (all models except gpt-3.5-turbo and
gpt-4), you can enable chat context, for the
model to remember your previous questions and
its previous answers. It also makes models
aware of todays date and what data it was trained
on.
cc, -cc, --code-chat This is a very handy feature, which allows you to use shellpilot
completions directly in your terminal, without the need to type cmd
to chat.
Plugins:
pv, -pv, --package-version Check the system package version, -f for fuzzy match
sa, -sa, --system-alias system alias, -a/a to add, -r/r to remove, -l/l to list
EOF
}
# error handling function
# $1 should be the response body
handle_error() {
# check if USE_API is openai
if [[ "$USE_API" == "openai" ]]; then
if echo "$1" | jq -e '.error' >/dev/null; then
echo -e "Your request to Open AI API failed: \033[0;31m$(echo "$1" | jq -r '.error.type')\033[0m"
echo "$1" | jq -r '.error.message'
exit 1
fi
fi
}
# conver the model size to human readable format
convert_size() {
local -i bytes=$1
if [[ $bytes -ge 1073741824 ]]; then
printf "%.2f GB" "$(echo "scale=2; $bytes / 1073741824" | bc)"
elif [[ $bytes -ge 1048576 ]]; then
printf "%.2f MB" "$(echo "scale=2; $bytes / 1048576" | bc)"
else
printf "%d bytes" "$bytes"
fi
}
# show the list of models
show_llm_models_output(){
# cache file is present, read from the cache
echo -ne "\n\033[36mReading from the cache and the cache_max_age is: ${CACHE_MAX_AGE} seconds, please check the config file if need to reset!\n\033[0m"
if [[ "$USE_API" == "ollama" ]]; then
cat "$LIST_MODELS_CACHE_FILE" | jq -c '.' | while read -r model; do
format_and_display "$model"
done
elif [[ "$USE_API" == "openai" ]]; then
cat "$LIST_MODELS_CACHE_FILE"
elif [[ "$USE_API" == "mistralai" ]]; then
cat "$LIST_MODELS_CACHE_FILE"
elif [[ "$USE_API" == "localai" ]]; then
cat "$LIST_MODELS_CACHE_FILE"
elif [[ "$USE_API" == "novita" ]]; then
cat "$LIST_MODELS_CACHE_FILE"
fi
}
# list the models
list_models() {
local cache_file="$LIST_MODELS_CACHE_FILE"
local max_age=${CACHE_MAX_AGE}
[[ ! -d $SPILOT_FILES_DEFAULT_DIR ]] && mkdir -p $SPILOT_FILES_DEFAULT_DIR
# Check if the cache file exists and is not empty
if [[ -f "$cache_file" ]] && [[ -s "$cache_file" ]]; then
# Get the last modified time based on the OS
if [[ "$(uname)" == "Darwin" ]]; then
local last_modified=$(stat -f %m "$cache_file")
else
local last_modified=$(stat -c %Y "$cache_file")
fi
local current_time=$(date +%s)
local age=$((current_time - last_modified))
# Check if the cache is not older than the max age
if (( age < max_age )); then
# Additional check for API content
# Fix the issue of changing the API with "e" option
local content_valid=false
case $USE_API in
ollama)
grep -qi "llama" "$cache_file" && content_valid=true
;;
openai)
grep -qi "gpt" "$cache_file" && content_valid=true
;;
mistralai)
grep -qi "mistral" "$cache_file" && content_valid=true
;;
localai)
grep -qi "stablediffusion" "$cache_file" && content_valid=true
;;
esac
if [[ "$content_valid" == true ]]; then
show_llm_models_output
return 0
else
# Cache is expired, invalid, or does not exist, fetch the models
fetch_and_cache_models "$cache_file"
# Read from the new cache
show_llm_models_output
return 0
fi
fi
fi
# Cache is expired, invalid, or does not exist, fetch the models
fetch_and_cache_models "$cache_file"
# Read from the new cache
show_llm_models_output
}
# fetch and cache the models
fetch_and_cache_models() {
local cache_file=$1
echo -ne "\n\033[36mFetching it from the API and store it for cache...\n\033[0m"
if [[ "$USE_API" == "ollama" ]]; then
models_response=$(fetch_model_from_ollama)
echo $models_response | jq -c '.models[]' > "$cache_file"
elif [[ "$USE_API" == "openai" ]]; then
models_response=$(fetch_model_from_openai)
handle_error "$models_response"
echo $models_response | jq -r -C '.data[] | {id, owned_by, created}' > "$cache_file"
elif [[ "$USE_API" == "localai" ]]; then
models_response=$(fetch_model_from_localai)
echo $models_response | jq -r -C '.data[] | {id, object}' > "$cache_file"
elif [[ "$USE_API" == "mistralai" ]]; then
models_response=$(fetch_model_from_mistralai)
echo $models_response | jq -r -C '.data[] | {id, owned_by, created}' > "$cache_file"
elif [[ "$USE_API" == "novita" ]]; then
models_response=$(fetch_model_from_novitaai)
echo $models_response | jq -r -C '.data[] | {id, owned_by, created}' > "$cache_file"
else
echo "Error: No API specified."
exit 1
fi
}
# format and display the model details
format_and_display() {
local model=$1
local name=$(echo "$model" | jq -r '.name')
local size=$(echo "$model" | jq -r '.size')
local format=$(echo "$model" | jq -r '.details.format')
local parameter_size=$(echo "$model" | jq -r '.details.parameter_size')
local quantization_level=$(echo "$model" | jq -r '.details.quantization_level')
local converted_size=$(convert_size $size)
echo -ne "$OVERWRITE_PROCESSING_LINE"
echo -ne "$PROCESSING_LABEL"
sleep 0.5 # set delay to avoid flickering
echo -ne "$OVERWRITE_PROCESSING_LINE"
# build a new JSON object with the model details
jq -n --arg name "$name" \
--arg size "$converted_size" \
--arg format "$format" \
--arg parameter_size "$parameter_size" \
--arg quantization_level "$quantization_level" \
'{name: $name, size: $size, format: $format, parameter_size: $parameter_size, quantization_level: $quantization_level}'
}
# build chat context before each request for /completions (all models except
# gpt turbo and gpt 4)
# $1 should be the escaped request prompt,
# it extends $chat_context
build_chat_context() {
local escaped_request_prompt="$1"
if [ -z "$chat_context" ]; then
chat_context="$CHAT_INIT_PROMPT\nQ: $escaped_request_prompt"
else
chat_context="$chat_context\nQ: $escaped_request_prompt"
fi
}
escape() {
echo "$1" | jq -Rrs 'tojson[1:-1]'
}
# maintain chat context function for /completions (all models except
# gpt turbo and gpt 4)
# builds chat context from response,
# keeps chat context length under max token limit
# * $1 should be the escaped response data
# * it extends $chat_context
maintain_chat_context() {
local escaped_response_data="$1"
# add response to chat context as answer
chat_context="$chat_context${chat_context:+\n}\nA: $escaped_response_data"
# check prompt length, 1 word =~ 1.3 tokens
# reserving 100 tokens for next user prompt
while (($(echo "$chat_context" | wc -c) * 1, 3 > (MAX_TOKENS - 100))); do
# remove first/oldest QnA from prompt
chat_context=$(echo "$chat_context" | sed -n '/Q:/,$p' | tail -n +2)
# add init prompt so it is always on top
chat_context="$CHAT_INIT_PROMPT $chat_context"
done
}
# build user chat message function for /chat/completions (gpt models)
# builds chat message before request,
# $1 should be the escaped request prompt,
# it extends $chat_message
build_user_chat_message() {
local escaped_request_prompt="$1"
if [ -z "$chat_message" ]; then
chat_message="{\"role\": \"user\", \"content\": \"$escaped_request_prompt\"}"
else
chat_message="$chat_message, {\"role\": \"user\", \"content\": \"$escaped_request_prompt\"}"
fi
}
# adds the assistant response to the message in (chatml) format
# for /chat/completions (gpt models)
# keeps messages length under max token limit
# * $1 should be the escaped response data
# * it extends and potentially shrinks $chat_message
add_assistant_response_to_chat_message() {
local escaped_response_data="$1"
# add response to chat context as answer
chat_message="$chat_message, {\"role\": \"assistant\", \"content\": \"$escaped_response_data\"}"
# transform to json array to parse with jq
local chat_message_json="[ $chat_message ]"
# check prompt length, 1 word =~ 1.3 tokens
# reserving 100 tokens for next user prompt
while (($(echo "$chat_message" | wc -c) * 1, 3 > (MAX_TOKENS - 100))); do
# remove first/oldest QnA from prompt
chat_message=$(echo "$chat_message_json" | jq -c '.[2:] | .[] | {role, content}')
done
}
# update spilot common config function
update_config() {
local new_value="$1"
local config_var_name="$2" # Variable name to update
local config_file="${SHELL_PILOT_CONFIG_PATH}/spilot_common.sh"
local backup_file="${config_file}.bak"
# Read the current value from the configuration file
local current_value=$(grep "^${config_var_name}=" "$config_file" | cut -d'=' -f2)
# Check if the value is already set to the new value
if [[ "$current_value" == "$new_value" ]]; then
echo "${config_var_name} is already set to $new_value. No update needed."
return 0
fi
# Backup the configuration file before updating
cp "$config_file" "$backup_file"
# Update the value in the configuration file
awk -v var_name="${config_var_name}=" -v new_val="$new_value" \
'$0 ~ var_name {print var_name new_val; next} 1' "$backup_file" > "$config_file"
echo "Attempting to update ${config_var_name} to $new_value."
# Read the updated value to confirm
local updated_value=$(grep "^${config_var_name}=" "$config_file" | cut -d'=' -f2)
# Check if the update was successful
if [[ "$updated_value" == "$new_value" ]]; then
if [ -f "$backup_file" ] && [[ "$current_value" != "$updated_value" ]]; then
rm "$backup_file"
echo "Backup file removed after successful update."
else
echo "${config_var_name} updated successfully to $new_value."
fi
echo "The setting will save in the configuration file."
else
echo "Failed to update ${config_var_name}. Restoring from backup."
mv "$backup_file" "$config_file"
fi
}
check_the_setting(){
local setting_name="$1"
local setting_variable="$2"
echo
echo "Here is the checklist to change the ${setting_name}:"
grep ^${setting_variable} $COMMON_CONFIG_FILE
exit 0
}
# Function to retrieve detailed system information
get_system_info() {
local os_type=$(uname -s)
if [[ "$os_type" == "Darwin" ]]; then
# macOS system detected
local mac_version=$(sw_vers -productVersion)
system_info="Operating system: macOS, Version: ${mac_version}"
elif [[ "$os_type" == "Linux" ]]; then
# Linux system detected
if [[ -f /etc/os-release ]]; then
# This should work for most Linux distributions
local version=$(grep PRETTY_NAME /etc/os-release | cut -d '"' -f2)
system_info="Operating system: Linux, Version: ${version}"
else
# Unable to find version, return generic info
system_info="Operating system: Linux, Version: Unknown"
fi
else
# Only return the generic OS type if it's neither Linux nor Darwin
system_info="Operating system: ${os_type}, Version: Unknown"
fi
echo "$system_info"
}
# check if the input value is empty
validate_not_empty() {
local input_value="$1"
if [[ -z "$input_value" ]]; then
echo "Error: The input cannot be empty."
exit 1
else
return 0
fi
}
# Function to validate the temperature value
validate_temperature() {
local input_value="$1"
# check if the input value is a number between 0 and 1
if [[ "$input_value" =~ ^[0-9]+(\.[0-9]+)?$ ]] && (( $(echo "$input_value >= 0 && $input_value <= 1" | bc -l) )); then
# temperature is valid
return 0
else
# temperature is invalid
echo "Invalid: temperature value must be between 0 and 1 inclusive."
exit 1
fi
}
# Function to enable the code chat mode
code_chat_function(){
# if the code chat mode is enabled, the user can enter the command directly
echo "Starting code chat mode..."
# check if the chat record flag is enabled
if [[ "$chat_record_flag" == "true" ]]; then
if [ -s "${CHAT_RECORD_FILE}" ]; then
# Loading existing session data...
chat_message=$(cat "${CHAT_RECORD_FILE}")
fi
fi
while true; do
# show the user a prompt to enter the command
echo -ne "\n\033[97m[You description(quit|q)]: \033[0m"
# echo -n "Enter your command: "
# read the command from the user
read command
# check if the user wants to quit
if [[ "$command" == "quit" || "$command" == "q" ]]; then
if [[ "$chat_record_flag" == "true" ]]; then
echo "$chat_message" > "${CHAT_RECORD_FILE}"
fi
echo "Exiting..."
break
fi
# clear the previous line
echo -ne "\033[1A\033[K"
system_info=$(get_system_info)
request_prompt="System info: ${system_info}\n${COMMAND_GENERATION_PROMPT}\nCommand request: ${command}"
build_user_chat_message "$request_prompt"
response=$(request_to_chat "$chat_message")
handle_error "$response"
if [[ "$USE_API" == "ollama" ]]; then
response_data=$(echo $response | jq -r '.message.content')
elif [[ "$USE_API" == "openai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "localai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "mistralai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "zhipuai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "anthropic" ]]; then
response_data=$(echo $response | jq -r '.content[0].text')
elif [[ "$USE_API" == "moonshot" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "novita" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
fi
add_assistant_response_to_chat_message "$(escape "$response_data")"
# execute_cmd=$(echo "$response_data" | sed 's/[`$]//g')
execute_cmd=$(echo "$response_data" | sed 's/[`$]//g' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
execute_cmd=$(echo "$execute_cmd" | xargs)
# if the processed command is not empty, ask the user to confirm or edit the command
if [[ ! -z "$execute_cmd" ]]; then
read -e -p "Confirm or edit the code(or leave empty to skip): " -i "$execute_cmd" final_command
echo -ne "\033[1A\033[K" # clear the previous line
if [[ ! -z "$final_command" ]]; then
echo -ne "Executing: $final_command\r" # show the command that will be executed
sleep 1 # wait for 1 second
echo -ne "\033[K" # clear the line
echo $final_command # print the command
eval "$final_command" # execute the command
fi
fi
done
}
# spin output
dynamic_spinner_wait() {
[[ ! -f ${SPINNER_SIGNAL_FILE} ]] && touch ${SPINNER_SIGNAL_FILE}
echo "0" > ${SPINNER_SIGNAL_FILE}
local -a marks=('/' '-' '\' '|')
local delay=0.2
while [[ $(cat ${SPINNER_SIGNAL_FILE}) == "0" ]]; do
for mark in "${marks[@]}"; do
echo -ne "\r\033[92m$mark Processing...\033[0m"
sleep $delay
done
done
echo -ne "\r\033[0K"
}
# check if the chat record flag is enabled
chat_record_flag=false
# parse command line arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
cr | -cr | --chat-record)
validate_not_empty "$2"
# Chat recording is enabled, the chat history will be saved in the specified session file.
chat_record_flag=true
CHAT_RECORD_ID=$2
CHAT_RECORD_FILE=${SPILOT_FILES_DEFAULT_DIR}/${CHAT_RECORD_ID}-chat_record.spilot
if [ ! -d "$SPILOT_FILES_DEFAULT_DIR" ]; then
mkdir -p $SPILOT_FILES_DEFAULT_DIR
fi
# create a new session file if it does not exist
# Starting a new session
if [ ! -f "${CHAT_RECORD_FILE}" ]; then
touch "${CHAT_RECORD_FILE}"
fi
shift 2
;;
e | -e | --edit)
# check vi is installed
if ! command -v vi &>/dev/null; then
echo -e "\033[33m==> Error: vi is not installed.\nPlease install vi or set the EDITOR environment variable.\033[0m"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 1 || exit 1
fi
/usr/bin/vi $COMMON_CONFIG_FILE
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
ip | -ip | --init-prompt)
validate_not_empty "$2"
CHAT_INIT_PROMPT="$2"
SYSTEM_PROMPT="$2"
CONTEXT=true
shift 2
;;
ipf | -ipf | --init-prompt-from-file)
validate_not_empty "$2"
CHAT_INIT_PROMPT=$(cat "$2")
SYSTEM_PROMPT=$(cat "$2")
CONTEXT=true
shift 2
;;
p | -p | --prompt)
validate_not_empty "$2"
prompt="$2"
# get the pipeline result to the -p
# e.g. cat error.log | ./spilot.sh -p "check any errors"
if ! [ -t 0 ]; then
piped_input=""
while IFS= read -r line; do
piped_input+="$line\n"
done
prompt="$prompt $piped_input"
fi
shift 2
;;
pf | -pf | --prompt-from-file)
validate_not_empty "$2"
prompt=$(cat "$2")
shift 2
;;
pv | -pv | --package-verison)
echo -e "\033[36mCheck the system package version\033[0m"
if [ $# -lt 2 ]; then
echo "Usage: $0 pv [-f] <pkg1> [pkg2] ..."
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
fi
fuzzy_option=$2
if [[ $fuzzy_option == "-f" ]]; then
fuzzy_match=1
shift 2
else
shift 1
fi
# Process each command line argument
for cmd in "$@"; do
generic_version_detect $cmd
done
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
sa | -sa | --system-alias)
system_alias_action=$2
if [[ $system_alias_action == "-a" || $system_alias_action == "a" ]]; then
if [ $# -lt 4 ]; then
echo "Usage: ss-pilot sa -a <alias1> <cmd1> [alias2] [cmd2] ..."
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
fi
shift 2
shell_pilot_add_system_aliases "$@"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
elif [[ $system_alias_action == "-r" || $system_alias_action == "r" ]];then
if [ $# -lt 3 ]; then
echo "Usage: ss-pilot sa -r <alias1> [alias2] ..."
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
fi
shift 2
shell_pilot_remove_system_aliases "$@"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
elif [[ $system_alias_action == "-l" || $system_alias_action == "l" ]]; then
shell_pilot_list_system_aliases
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
else
echo -e "Info: Invalid system alias action!\nPlease choose \033[1;36m-a/a\033[0m to add, \033[1;35m-r/r\033[0m to remove, or \033[1;34m-l/l\033[0m to list the system alias."
echo "Usage: ss-pilot sa <-a|a> <alias1> <cmd1> [alias2] [cmd2] ..."
echo "Usage: ss-pilot sa <-r|r> <alias1> [alias2] ..."
echo "Usage: ss-pilot sa <-l|l>"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
fi
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
t | -t | --temperature)
validate_not_empty "$2"
validate_temperature "$2"
update_config "$2" "TEMPERATURE"
check_the_setting "temperature" "TEMPERATURE"
;;
mt | -mt | --max-tokens)
validate_not_empty "$2"
update_config "$2" "MAX_TOKENS"
check_the_setting "max tokens" "MAX_TOKENS"
;;
lc | -lc | --list-config)
grep ^USE_API -B 1 $COMMON_CONFIG_FILE
echo
grep SYSTEM_PROMPT -A 1 -B 2 $COMMON_CONFIG_FILE
echo
tail -11 $COMMON_CONFIG_FILE
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
lm | -lm | --list-models)
list_models
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
lr | -lr | --list-chat-record)
CHAT_RECORD_FILE_NAME=$2
if [ -n "$CHAT_RECORD_FILE_NAME" ]; then
CHAT_RECORD_FILE=${SPILOT_FILES_DEFAULT_DIR}/${CHAT_RECORD_FILE_NAME}-chat_record.spilot
if [[ -f "${CHAT_RECORD_FILE}" && -s "${CHAT_RECORD_FILE}" ]]; then
echo -e "\033[36m==> Here is the chat record file content:\033[0m"
# cat "${CHAT_RECORD_FILE}"
# pretty print the json file
awk 'BEGIN {print "["} NR > 1 {print line ","} {line = $0} END {print line "]"}' "${CHAT_RECORD_FILE}" | jq .
else
echo -e "\033[36m==> Error: The chat record file does not exist or the name is not provided or empty.\033[0m"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 1 || exit 1
fi
else
echo -e "\033[36m==> Here are the chat record files[<name>-chat_record.spilot]:\033[0m"
ls -l $SPILOT_FILES_DEFAULT_DIR | grep chat_record.spilot
fi
exit 0
;;
dr | -dr | --delete-record)
CHAT_RECORD_FILE_NAME=$2
if [ -z "$CHAT_RECORD_FILE_NAME" ]; then
echo -e "\033[31mError: You must provide a file name to delete.\033[0m"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 1 || exit 1
fi
CHAT_RECORD_FILE="${SPILOT_FILES_DEFAULT_DIR}/${CHAT_RECORD_FILE_NAME}-chat_record.spilot"
if [[ -f "${CHAT_RECORD_FILE}" ]]; then
rm -i "${CHAT_RECORD_FILE}"
echo -e "\033[32mFile ${CHAT_RECORD_FILE} has been deleted successfully.\033[0m"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
else
echo -e "\033[31mError: ${CHAT_RECORD_FILE} file does not exist.\033[0m"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 1 || exit 1
fi
;;
m | --model)
validate_not_empty "$2"
if [[ "$USE_API" == "openai" ]]; then
update_config "$2" "MODEL_OPENAI"
check_the_setting "openai model" "MODEL_OPENAI"
elif [[ "$USE_API" == "localai" ]]; then
update_config "$2" "MODEL_LOCALAI"
check_the_setting "localai model" "MODEL_LOCALAI"
elif [[ "$USE_API" == "mistralai" ]]; then
update_config "$2" "MODEL_MISTRALAI"
check_the_setting "mistralai model" "MODEL_MISTRALAI"
elif [[ "$USE_API" == "ollama" ]]; then
update_config "$2" "MODEL_OLLAMA"
check_the_setting "ollama model" "MODEL_OLLAMA"
elif [[ "$USE_API" == "zhipuai" ]]; then
update_config "$2" "MODEL_ZHIPUAI"
check_the_setting "zhipuai model" "MODEL_ZHIPUAI"
elif [[ "$USE_API" == "anthropic" ]]; then
update_config "$2" "MODEL_ANTHROPIC"
check_the_setting "anthropic model" "MODEL_ANTHROPIC"
elif [[ "$USE_API" == "moonshot" ]]; then
update_config "$2" "MODEL_MOONSHOT"
check_the_setting "moonshot model" "MODEL_MOONSHOT"
elif [[ "$USE_API" == "novita" ]]; then
update_config "$2" "MODEL_NOVITA"
check_the_setting "novita model" "MODEL_NOVITA"
fi
;;
mlp | -mlp | --multi-line-prompt)
validate_not_empty "$2"
update_config "$2" "MULTI_LINE_PROMPT"
check_the_setting "multi-line prompt" "MULTI_LINE_PROMPT"
;;
c | -c | --chat-context)
validate_not_empty "$2"
update_config "$2" "CONTEXT"
check_the_setting "chat context"
;;
cc | -cc | --code-chat)
code_chat_function
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
cmp | -cmp | --change-model-provider)
validate_not_empty "$2"
# check if the model provider is valid
if [[ "$2" == "openai" || "$2" == "ollama" || "$2" == "mistralai" || "$2" == "localai" || "$2" == "zhipuai" || "$2" == "anthropic" || "$2" == "moonshot" ]]; then
# update the model provider
update_config "$2" "USE_API"
# clean the cache
rm -f ${LIST_MODELS_CACHE_FILE}
check_the_setting "model provider" "USE_API"
else
# print error message and exit if the model provider is invalid
echo -e "Error: Invalid model provider. Please choose \033[1;36mopenai\033[0m or \033[1;37mmistralai\033[0m or \033[1;35mollama\033[0m or \033[1;35mlocalai\033[0m or \033[1;35mzhipuai\033[0m or \033[1;35manthropic\033[0m or \033[1;35mmoonshot\033[0m."
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 1 || exit 1
fi
;;
v | -v | --version)
echo -ne "\033[36m[Shell Pilot Version]: ${SHELL_PILOT_VERSION}\033[0m\n"
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
h | -h | --help)
usage
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
*)
echo "Unknown parameter: $1"
# fix the source issue
[[ "${BASH_SOURCE[0]}" != "$0" ]] && return 0 || exit 0
;;
esac
done
# create our temp file for multi-line input
if [ $MULTI_LINE_PROMPT = true ]; then
USER_INPUT_TEMP_FILE=$(mktemp)
trap 'rm -f ${USER_INPUT}' EXIT
fi
# create history file
[[ -d $SPILOT_FILES_DEFAULT_DIR ]] || mkdir -p $SPILOT_FILES_DEFAULT_DIR
SIPLOT_HISTORY_FILE=$SPILOT_FILES_DEFAULT_DIR/.spilot_history
if [ ! -f $SIPLOT_HISTORY_FILE ]; then
touch $SIPLOT_HISTORY_FILE
chmod 600 $SIPLOT_HISTORY_FILE
fi
# check input source and determine run mode
running=true
# prompt from argument, run on pipe mode (run once, no chat)
if [ -n "$prompt" ]; then
pipe_mode_prompt=${prompt}
# if input file_descriptor is a terminal, run on chat mode
elif [ -t 0 ]; then
echo -e "Welcome to \033[94mShell Pilot\033[0m!!\nYou can quit with '\033[36mq\033[0m' or '\033[36me\033[0m'."
# prompt from pipe or redirected stdin, run on pipe mode
else
pipe_mode_prompt+=$(cat -)
fi
while $running; do
if [ -z "$pipe_mode_prompt" ]; then
if [ $MULTI_LINE_PROMPT = true ]; then
echo -e "\nYou: (Press Enter then Ctrl-D to send)"
cat >"${USER_INPUT_TEMP_FILE}"
input_from_temp_file=$(cat "${USER_INPUT_TEMP_FILE}")
prompt=$(escape "$input_from_temp_file")
else
echo -e "\n\033[97m<<You>>\033[0m"
read -e prompt
fi
if [[ ! $prompt =~ ^(e|q)$ ]]; then
dynamic_spinner_wait &
dynamic_spinner_pid=$!
fi
else
# set vars for pipe mode
# p option run this
prompt=${pipe_mode_prompt}
running=false
SHELLPILOT_CYAN_LABEL=""
fi
# exit for chat mode
if [[ $prompt =~ ^(e|q)$ ]]; then
running=false
# save the chat record for chat mode
if [[ "$chat_record_flag" == "true" ]]; then
echo "$chat_message" > "${CHAT_RECORD_FILE}"
fi
elif [[ "$prompt" == "history" ]]; then
# echo "1" > ${SPINNER_SIGNAL_FILE}
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -ne "$OVERWRITE_PROCESSING_LINE"
echo -e "\n$(cat $SIPLOT_HISTORY_FILE)"
elif [[ "$prompt" == "models" ]]; then
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
list_models
elif [[ "$prompt" =~ ^model: ]]; then
if [[ "$USE_API" == "openai" ]]; then
models_response=$(fetch_model_from_openai)
handle_error "$models_response"
model_data=$(echo $models_response | jq -r -C '.data[] | select(.id=="'"${prompt#*model:}"'")')
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -e "$OVERWRITE_PROCESSING_LINE"
echo -e "${SHELLPILOT_CYAN_LABEL}Complete details for model: ${prompt#*model:}\n ${model_data}"
elif [[ "$USE_API" == "localai" ]]; then
models_response=$(fetch_model_from_localai)
model_data=$(echo $models_response | jq -r -C '.data[] | select(.id=="'"${prompt#*model:}"'")')
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -e "$OVERWRITE_PROCESSING_LINE"
echo -e "${SHELLPILOT_CYAN_LABEL}Complete details for model: ${prompt#*model:}\n ${model_data}"
elif [[ "$USE_API" == "mistralai" ]]; then
models_response=$(fetch_model_from_mistralai)
model_data=$(echo $models_response | jq -r -C '.data[] | select(.id=="'"${prompt#*model:}"'")')
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -e "$OVERWRITE_PROCESSING_LINE"
echo -e "${SHELLPILOT_CYAN_LABEL}Complete details for model: ${prompt#*model:}\n ${model_data}"
elif [[ "$USE_API" == "ollama" ]]; then
echo -e "$OVERWRITE_PROCESSING_LINE"
# get the model name
escaped_prompt=$(escape "$prompt")
escaped_prompt=${escaped_prompt#model:}
escaped_prompt=$(echo "$escaped_prompt" | sed 's/\\n//g' | sed 's/\.//g')
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -e "$OVERWRITE_PROCESSING_LINE"
curl -s http://${OLLAMA_SERVER_IP}:11434/api/show -d '{
"name": "'"$escaped_prompt"'"
}' | jq -r '[
"License: \(.license)",
"Format: \(.details.format)",
"Family: \(.details.family)",
"Parameter Size: \(.details.parameter_size)",
"Quantization Level: \(.details.quantization_level)"
] | .[]'
elif [[ "$USE_API" == "novita" ]]; then
models_response=$(fetch_model_from_novitaai)
model_data=$(echo $models_response | jq -r -C '.data[] | select(.id=="'"${prompt#*model:}"'")')
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
echo -e "$OVERWRITE_PROCESSING_LINE"
echo -e "${SHELLPILOT_CYAN_LABEL}Complete details for model: ${prompt#*model:}\n ${model_data}"
else
echo "Error: No API specified".
exit 1
fi
elif [[ "$prompt" =~ ^cmd: ]]; then
# escape quotation marks, new lines, backslashes...
# enable chat record flag
if [[ "$chat_record_flag" == "true" ]]; then
if [ -s "${CHAT_RECORD_FILE}" ]; then
# Loading existing session data...
chat_message=$(cat "${CHAT_RECORD_FILE}")
fi
fi
escaped_prompt=$(escape "$prompt")
escaped_prompt=${escaped_prompt#cmd:}
system_info=$(get_system_info)
request_prompt="System info: ${system_info}\n${COMMAND_GENERATION_PROMPT}\nCommand request: ${escaped_prompt}"
build_user_chat_message "$request_prompt"
response=$(request_to_chat "$chat_message")
# stop the spinner
cat ${SPINNER_SIGNAL_FILE} >/dev/null 2>&1
echo "1" > ${SPINNER_SIGNAL_FILE}
wait $dynamic_spinner_pid
handle_error "$response"
if [[ "$USE_API" == "ollama" ]]; then
response_data=$(echo $response | jq -r '.message.content')
elif [[ "$USE_API" == "openai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "moonshot" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "localai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "mistralai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "zhipuai" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
elif [[ "$USE_API" == "anthropic" ]]; then
response_data=$(echo $response | jq -r '.content[0].text')
elif [[ "$USE_API" == "novita" ]]; then
response_data=$(echo $response | jq -r '.choices[].message.content')
fi