-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathgaianet
executable file
·1944 lines (1656 loc) · 70.4 KB
/
gaianet
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
#!/bin/bash
set -e
# version of CLI tool
# Note that the version should kept same as the version of installer
version="0.4.16"
# version of the GaiaNet node
# Note that the version should kept same as the version of installer
installer_version="0.4.16"
# path to the default gaianet base directory. It could be changed by the --base option
gaianet_base_dir="$HOME/gaianet"
# We will make sure that the path is setup in case the user runs gaianet immediately after init
source $HOME/.wasmedge/env
# print in red color
RED=$'\e[0;31m'
# print in green color
GREEN=$'\e[0;32m'
# print in yellow color
YELLOW=$'\e[0;33m'
# No Color
NC=$'\e[0m'
# Mac OS requires this hack in order to run qdrant reliablly
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
ulimit -n 10000
fi
info() {
printf "${GREEN}$1${NC}\n\n"
}
error() {
printf "${RED}$1${NC}\n\n"
}
warning() {
printf "${YELLOW}$1${NC}\n\n"
}
# download target file to destination. If failed, then exit
check_curl() {
curl --retry 3 --progress-bar -L "$1" -o "$2"
if [ $? -ne 0 ]; then
error " * Failed to download $1"
exit 1
fi
}
check_curl_silent() {
curl --retry 3 -s --progress-bar -L "$1" -o "$2"
if [ $? -ne 0 ]; then
error " * Failed to download $1"
exit 1
fi
}
check_base_dir() {
# Check if $gaianet_base_dir directory exists
if [ ! -d $gaianet_base_dir ]; then
printf "\n[Error] Not found $gaianet_base_dir.\n\nPlease run 'bash install.sh' command first, then try again.\n\n"
exit 1
fi
}
sed_in_place() {
if [ "$(uname)" == "Darwin" ]; then
sed -i '' "$@"
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
sed -i "$@"
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
error " * For Windows users, please run this script in WSL."
exit 1
else
error " * Only support Linux, MacOS and Windows."
exit 1
fi
}
# check the validity of the config.json file
check_config_options() {
# check if config.json exists or not
if [ ! -f "$gaianet_base_dir/config.json" ]; then
error "Not found config.json file in $gaianet_base_dir"
exit 1
fi
# check if the `address` field exists or not
if ! grep -q '"address":' $gaianet_base_dir/config.json; then
error "Not found the 'address' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `chat` field exists or not
if ! grep -q '"chat":' $gaianet_base_dir/config.json; then
error "Not found the 'chat' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `prompt_template` field exists or not
if ! grep -q '"prompt_template":' $gaianet_base_dir/config.json; then
error "Not found the 'prompt_template' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `chat_ctx_size` field exists or not
if ! grep -q '"chat_ctx_size":' $gaianet_base_dir/config.json; then
error "Not found the 'chat_ctx_size' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `system_prompt` field exists or not
if ! grep -q '"system_prompt":' $gaianet_base_dir/config.json; then
error "Not found the 'system_prompt' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `embedding` field exists or not
if ! grep -q '"embedding":' $gaianet_base_dir/config.json; then
error "Not found the 'embedding' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `embedding_ctx_size` field exists or not
if ! grep -q '"embedding_ctx_size":' $gaianet_base_dir/config.json; then
error "Not found the 'embedding_ctx_size' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `snapshot` field exists or not
if ! grep -q '"snapshot":' $gaianet_base_dir/config.json; then
error "Not found the 'snapshot' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `embedding_collection_name` field exists or not
if ! grep -q '"embedding_collection_name":' $gaianet_base_dir/config.json; then
error "Not found the 'embedding_collection_name' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `qdrant_limit` field exists or not
if ! grep -q '"qdrant_limit":' $gaianet_base_dir/config.json; then
error "Not found the 'qdrant_limit' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `qdrant_score_threshold` field exists or not
if ! grep -q '"qdrant_score_threshold":' $gaianet_base_dir/config.json; then
error "Not found the 'qdrant_score_threshold' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `rag_prompt` field exists or not
if ! grep -q '"rag_prompt":' $gaianet_base_dir/config.json; then
error "Not found the 'rag_prompt' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `rag_policy` field exists or not
if ! grep -q '"rag_policy":' $gaianet_base_dir/config.json; then
error "Not found the 'rag_policy' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `domain` field exists or not
if ! grep -q '"domain":' $gaianet_base_dir/config.json; then
error "Not found the 'domain' field in $gaianet_base_dir/config.json\n"
exit 1
fi
# check if the `llamaedge_port` field exists or not
if ! grep -q '"llamaedge_port":' $gaianet_base_dir/config.json; then
error "Not found the 'llamaedge_port' field in $gaianet_base_dir/config.json\n"
exit 1
fi
}
# create or recover a qdrant collection
create_collection() {
printf "[+] Creating 'default' collection in the Qdrant instance ...\n"
qdrant_pid=0
qdrant_already_running=false
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
if lsof -Pi :6333 -sTCP:LISTEN -t >/dev/null ; then
warning " * A Qdrant instance is already running"
qdrant_already_running=true
fi
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
printf "For Windows users, please run this script in WSL.\n"
exit 1
else
printf "Only support Linux, MacOS and Windows.\n"
exit 1
fi
if [ "$qdrant_already_running" = false ]; then
printf " * Start a Qdrant instance ...\n\n"
# start qdrant
cd $gaianet_base_dir/qdrant
# check if `log` directory exists or not
if [ ! -d "$gaianet_base_dir/log" ]; then
mkdir -p -m777 $gaianet_base_dir/log
fi
log_dir=$gaianet_base_dir/log
nohup $gaianet_base_dir/bin/qdrant > $log_dir/init-qdrant.log 2>&1 &
sleep 10
qdrant_pid=$!
fi
cd $gaianet_base_dir
url_snapshot=$(awk -F'"' '/"snapshot":/ {print $4}' config.json)
url_document=$(awk -F'"' '/"document":/ {print $4}' config.json)
embedding_collection_name=$(awk -F'"' '/"embedding_collection_name":/ {print $4}' config.json)
if [[ -z "$embedding_collection_name" ]]; then
embedding_collection_name="default"
fi
printf " * Remove the existed 'default' Qdrant collection ...\n\n"
cd $gaianet_base_dir
# remove the collection if it exists
del_response=$(curl -s -X DELETE http://localhost:6333/collections/$embedding_collection_name \
-H "Content-Type: application/json")
curl_exit_status=$?
if [ $curl_exit_status -ne 0 ]; then
error " Failed to remove the $embedding_collection_name collection. Exit."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
status=$(echo "$del_response" | grep -o '"status":"[^"]*"' | cut -d':' -f2 | tr -d '"')
if [ "$status" != "ok" ]; then
error " Failed to remove the $embedding_collection_name collection. $del_response"
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
# 10.1 recover from the given qdrant collection snapshot
if [ -n "$url_snapshot" ]; then
# Regular expression for URL validation
regex='(https?|ftp)://[-[:alnum:]\+&@#/%?=~_|!:,.;]+'
# Check if $url_snapshot is a valid URL
if [[ $url_snapshot =~ $regex ]]; then
printf " * Download Qdrant collection snapshot ...\n"
if [[ $url_snapshot == *.tar.gz ]]; then
filename=$(basename $url_snapshot)
check_curl $url_snapshot $gaianet_base_dir/$filename
tar -xzOf $gaianet_base_dir/$filename > $gaianet_base_dir/default.snapshot
rm $gaianet_base_dir/$filename
else
check_curl $url_snapshot $gaianet_base_dir/default.snapshot
fi
info " The snapshot is downloaded in $gaianet_base_dir"
# Check if $url_snapshot is a local file
elif [ -f "$gaianet_base_dir/$url_snapshot" ]; then
info " * Use local snapshot: $url_snapshot"
if [[ $url_snapshot == *.tar.gz ]]; then
tar -xzOf $gaianet_base_dir/$url_snapshot > $gaianet_base_dir/default.snapshot
else
# make a copy of the original snapshot file
cp $gaianet_base_dir/$url_snapshot $gaianet_base_dir/default.snapshot
fi
else
echo "$url_snapshot is neither a valid URL nor a local file."
fi
printf " * Import the Qdrant collection snapshot ...\n"
printf " The process may take a few minutes. Please wait ...\n"
# Import the default.snapshot file
cd $gaianet_base_dir
response=$(curl -s -X POST http://localhost:6333/collections/$embedding_collection_name/snapshots/upload?priority=snapshot \
-H 'Content-Type:multipart/form-data' \
-F '[email protected]')
sleep 5
if echo "$response" | grep -q '"status":"ok"'; then
rm $gaianet_base_dir/default.snapshot
info " Recovery is done!"
else
error " * [Error] Failed to recover from the collection snapshot. $response"
if [ "$qdrant_already_running" = false ]; then
info " * Stop the Qdrant instance ..."
kill -9 $qdrant_pid
fi
exit 1
fi
# 10.2 generate a Qdrant collection from the given document
elif [ -n "$url_document" ]; then
printf " * Create 'default' Qdrant collection from the given document ...\n\n"
# Start LlamaEdge API Server
printf " * Start LlamaEdge-RAG API Server ...\n\n"
# parse cli options for chat model
cd $gaianet_base_dir
url_chat_model=$(awk -F'"' '/"chat":/ {print $4}' config.json)
# gguf filename
chat_model_name=$(basename $url_chat_model)
# Directly attempt to extract "chat_name" and fallback to extracting from "chat" if empty
chat_name=$(grep '"chat_name":' config.json | sed -E 's/.*"chat_name": *"([^"]*)".*/\1/')
if [ -z "$chat_name" ]; then
chat_model_stem=$(basename "${url_chat_model%.*}")
else
chat_model_stem=$chat_name
fi
# parse context size for chat model
chat_ctx_size=$(awk -F'"' '/"chat_ctx_size":/ {print $4}' config.json)
# parse prompt type for chat model
prompt_type=$(awk -F'"' '/"prompt_template":/ {print $4}' config.json)
# parse reverse prompt for chat model
reverse_prompt=$(awk -F'"' '/"reverse_prompt":/ {print $4}' config.json)
url_embedding_model=$(awk -F'"' '/"embedding":/ {print $4}' config.json)
# gguf filename
embedding_model_name=$(basename $url_embedding_model)
# Directly attempt to extract "embedding_name" and fallback to extracting from "embedding" if empty
embedding_name=$(grep '"embedding_name":' config.json | sed -E 's/.*"embedding_name": *"([^"]*)".*/\1/')
if [ -z "$embedding_name" ]; then
embedding_model_stem=$(basename "${url_embedding_model%.*}")
else
embedding_model_stem=$embedding_name
fi
# parse context size for embedding model
embedding_ctx_size=$(awk -F'"' '/"embedding_ctx_size":/ {print $4}' config.json)
# parse cli options for embedding vector collection name
embedding_collection_name=$(awk -F'"' '/"embedding_collection_name":/ {print $4}' config.json)
if [[ -z "$embedding_collection_name" ]]; then
embedding_collection_name="default"
fi
# parse port for LlamaEdge API Server
llamaedge_port=$(awk -F'"' '/"llamaedge_port":/ {print $4}' config.json)
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
if lsof -Pi :$llamaedge_port -sTCP:LISTEN -t >/dev/null ; then
error " It appears that the GaiaNet node is running. Please stop it first."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
error " For Windows users, please run this script in WSL."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
else
error " Only support Linux, MacOS and Windows."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
# command to start LlamaEdge API Server
cd $gaianet_base_dir
cmd="wasmedge --dir .:. \
--env NODE_VERSION=$installer_version \
--nn-preload default:GGML:AUTO:$chat_model_name \
--nn-preload embedding:GGML:AUTO:$embedding_model_name \
rag-api-server.wasm \
--prompt-template $prompt_type,embedding \
--model-name $chat_model_stem,$embedding_model_stem \
--ctx-size $chat_ctx_size,$embedding_ctx_size \
--qdrant-collection-name $embedding_collection_name \
--web-ui ./dashboard \
--socket-addr 0.0.0.0:$llamaedge_port"
nohup $cmd > $log_dir/init-qdrant-gen-collection.log 2>&1 &
sleep 5
llamaedge_pid=$!
echo $llamaedge_pid > $gaianet_base_dir/llamaedge.pid
printf " * Convert document to embeddings ...\n"
printf " The process may take a few minutes. Please wait ...\n\n"
cd $gaianet_base_dir
doc_filename=$(basename $url_document)
check_curl_silent $url_document $gaianet_base_dir/$doc_filename
if [[ $doc_filename != *.txt ]] && [[ $doc_filename != *.md ]]; then
error "The document to upload should be a file with 'txt' or 'md' extension."
# stop the api-server
if [ -f "$gaianet_base_dir/llamaedge.pid" ]; then
kill $(cat $gaianet_base_dir/llamaedge.pid)
rm $gaianet_base_dir/llamaedge.pid
fi
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
# compute embeddings
embedding_response=$(curl -s -X POST http://127.0.0.1:$llamaedge_port/v1/create/rag -F "file=@$doc_filename")
# remove the downloaded document
rm -f $gaianet_base_dir/$doc_filename
# stop the api-server
if [ -f "$gaianet_base_dir/llamaedge.pid" ]; then
# stop API server
kill $(cat $gaianet_base_dir/llamaedge.pid)
rm $gaianet_base_dir/llamaedge.pid
fi
if [ -z "$embedding_response" ]; then
error " Failed to compute embeddings. Exit."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
else
info " * Embeddings are computed successfully"
fi
else
error "Please set 'snapshot' or 'document' field in config.json. Exit."
if [ "$qdrant_already_running" = false ]; then
kill $qdrant_pid
fi
exit 1
fi
if [ "$qdrant_already_running" = false ]; then
# stop qdrant
kill $qdrant_pid
fi
# sleep for a while to make sure the qdrant instance is stopped
sleep 10
}
# * init subcommand
init() {
# check if config.json exists or not
printf "[+] Checking the config.json file ...\n"
check_config_options
printf "\n"
# download GGUF chat model file to $gaianet_base_dir
url_chat_model=$(awk -F'"' '/"chat":/ {print $4}' $gaianet_base_dir/config.json)
chat_model=$(basename $url_chat_model)
if [[ $url_chat_model =~ ^http[s]?://.* ]]; then
printf "[+] Downloading $chat_model ...\n"
if [ -f "$gaianet_base_dir/$chat_model" ]; then
warning " * Using the cached $chat_model in $gaianet_base_dir"
else
check_curl $url_chat_model $gaianet_base_dir/$chat_model
info " * $chat_model is downloaded in $gaianet_base_dir"
fi
elif [[ $url_chat_model =~ .*\.gguf$ ]]; then
printf "[+] Using local $chat_model ...\n"
if [ -f "$gaianet_base_dir/$chat_model" ]; then
warning " * Found $chat_model in $gaianet_base_dir"
else
error " * Not found $chat_model in $gaianet_base_dir. Exit ..."
exit 1
fi
else
error "Error: The 'chat' field in $gaianet_base_dir/config.json should be a url or a gguf model file. Exit ..."
exit 1
fi
# download GGUF embedding model file to $gaianet_base_dir
url_embedding_model=$(awk -F'"' '/"embedding":/ {print $4}' $gaianet_base_dir/config.json)
embedding_model=$(basename $url_embedding_model)
if [[ $url_embedding_model =~ ^http[s]?://.* ]]; then
printf "[+] Downloading $embedding_model ...\n"
if [ -f "$gaianet_base_dir/$embedding_model" ]; then
warning " * Using the cached $embedding_model in $gaianet_base_dir"
else
check_curl $url_embedding_model $gaianet_base_dir/$embedding_model
info " * $embedding_model is downloaded in $gaianet_base_dir"
fi
elif [[ $url_embedding_model =~ .*\.gguf$ ]]; then
printf "[+] Using local $embedding_model ...\n"
if [ -f "$gaianet_base_dir/$embedding_model" ]; then
warning " * Found $embedding_model in $gaianet_base_dir"
else
error " * Not found $embedding_model in $gaianet_base_dir. Exit ..."
exit 1
fi
else
error "Error: The 'embedding' field in $gaianet_base_dir/config.json should be a url or a gguf model file. Exit ..."
exit 1
fi
snapshot=$(awk -F'"' '/"snapshot":/ {print $4}' $gaianet_base_dir/config.json)
if [ -n "$snapshot" ]; then
# create or recover a qdrant collection
create_collection
fi
# Copy config to dashboard
if [ ! -f "$gaianet_base_dir/registry.wasm" ] ; then
printf "[+] Downloading the registry.wasm ...\n"
check_curl_silent https://github.com/GaiaNet-AI/gaianet-node/raw/main/utils/registry/registry.wasm $gaianet_base_dir/registry.wasm
printf "\n"
fi
printf "[+] Preparing the dashboard ...\n"
cd $gaianet_base_dir
wasmedge --dir .:. registry.wasm
printf "\n"
printf "[+] Preparing the GaiaNet domain ...\n"
# Update frpc.toml
address=$(awk -F'"' '/"address":/ {print $4}' $gaianet_base_dir/config.json)
domain=$(awk -F'"' '/"domain":/ {print $4}' $gaianet_base_dir/config.json)
llamaedge_port=$(awk -F'"' '/"llamaedge_port":/ {print $4}' $gaianet_base_dir/config.json)
sed_in_place "s/subdomain = \".*\"/subdomain = \"$address\"/g" $gaianet_base_dir/gaia-frp/frpc.toml
sed_in_place "s/name = \".*\"/name = \"$address.$domain\"/g" $gaianet_base_dir/gaia-frp/frpc.toml
sed_in_place "s/localPort = .*/localPort = $llamaedge_port/g" $gaianet_base_dir/gaia-frp/frpc.toml
sed_in_place "s/serverAddr = \".*\"/serverAddr = \"$domain\"/g" $gaianet_base_dir/gaia-frp/frpc.toml
# Remove all files in the directory except for frpc and frpc.toml
find $gaianet_base_dir/gaia-frp -type f -not -name 'frpc' -not -name 'frpc.toml' -exec rm -f {} \;
printf "\n"
printf "[+] COMPLETED! GaiaNet node is initialized successfully.\n\n"
info ">>> To start the GaiaNet node, run the command: gaianet start <<<"
}
# * config subcommand
update_config() {
key=$1
new_value=$2
file=$gaianet_base_dir/config.json
# update in place
if [ -z "$new_value" ]; then
sed_in_place "s/\(\"$key\": \s*\).*\,/\1\"$new_value\",/" $file
else
sed_in_place "/\"$key\":/ s#: \".*\"#: \"$new_value\"#" $file
fi
}
# * start subcommand
# start rag-api-server and a qdrant instance
start() {
local_only=$1
force_rag=$2
log_dir=$gaianet_base_dir/log
if ! [ -d "$log_dir" ]; then
mkdir -p -m777 $log_dir
fi
local_log_storage=1
if command -v vector > /dev/null 2>&1 && [ -f $gaianet_base_dir/vector.toml ]; then
local_log_storage=0
fi
# check if config.json exists or not
printf "[+] Checking the config.json file ...\n"
check_config_options
printf "\n"
# sync the config.json to dashboard/config_pub.json
cd $gaianet_base_dir
wasmedge --dir .:. registry.wasm
# check if supervise is installed or not
use_supervise=true
if ! command -v supervise &> /dev/null; then
use_supervise=false
fi
snapshot=$(awk -F'"' '/"snapshot":/ {print $4}' $gaianet_base_dir/config.json)
if [ -n "$snapshot" ] || [ "$force_rag" = true ]; then
# 1. start a Qdrant instance
printf "[+] Starting Qdrant instance ...\n"
qdrant_already_running=false
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
if lsof -Pi :6333 -sTCP:LISTEN -t >/dev/null ; then
qdrant_already_running=true
fi
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
printf "For Windows users, please run this script in WSL.\n"
exit 1
else
printf "Only support Linux, MacOS and Windows.\n"
exit 1
fi
if [ "$qdrant_already_running" = false ]; then
qdrant_executable="$gaianet_base_dir/bin/qdrant"
if [ -f "$qdrant_executable" ]; then
cd $gaianet_base_dir/qdrant
nohup $qdrant_executable > $log_dir/start-qdrant.log 2>&1 &
sleep 2
qdrant_pid=$!
echo $qdrant_pid > $gaianet_base_dir/qdrant.pid
info "\n Qdrant instance started with pid: $qdrant_pid"
else
error " Qdrant binary not found at $qdrant_executable\n\n"
exit 1
fi
fi
# 2. start rag-api-server
printf "[+] Starting LlamaEdge API Server ...\n\n"
# parse cli options for chat model
cd $gaianet_base_dir
url_chat_model=$(awk -F'"' '/"chat":/ {print $4}' config.json)
# gguf filename
chat_model_name=$(basename $url_chat_model)
# Directly attempt to extract "chat_name" and fallback to extracting from "chat" if empty
chat_name=$(grep '"chat_name":' config.json | sed -E 's/.*"chat_name": *"([^"]*)".*/\1/')
if [ -z "$chat_name" ]; then
chat_model_stem=$(basename "${url_chat_model%.*}")
else
chat_model_stem=$chat_name
fi
# parse context size for chat model
chat_ctx_size=$(awk -F'"' '/"chat_ctx_size":/ {print $4}' config.json)
# parse batch size for chat model
chat_batch_size=$(awk -F'"' '/"chat_batch_size":/ {print $4}' config.json)
# parse prompt type for chat model
prompt_type=$(awk -F'"' '/"prompt_template":/ {print $4}' config.json)
# parse system prompt for chat model
rag_prompt=$(awk -F'"' '/"rag_prompt":/ {print $4}' config.json)
# parse reverse prompt for chat model
reverse_prompt=$(awk -F'"' '/"reverse_prompt":/ {print $4}' config.json)
# parse rag policy
if grep -q '"rag_policy":' config.json; then
rag_policy=$(awk -F'"' '/"rag_policy":/ {print $4}' config.json)
else
rag_policy="system-message"
fi
url_embedding_model=$(awk -F'"' '/"embedding":/ {print $4}' config.json)
# gguf filename
embedding_model_name=$(basename $url_embedding_model)
# Directly attempt to extract "embedding_name" and fallback to extracting from "embedding" if empty
embedding_name=$(grep '"embedding_name":' config.json | sed -E 's/.*"embedding_name": *"([^"]*)".*/\1/')
if [ -z "$embedding_name" ]; then
embedding_model_stem=$(basename "${url_embedding_model%.*}")
else
embedding_model_stem=$embedding_name
fi
# parse cli options for embedding vector collection name
embedding_collection_name=$(awk -F'"' '/"embedding_collection_name":/ {print $4}' config.json)
if [[ -z "$embedding_collection_name" ]]; then
embedding_collection_name="default"
fi
# parse context size for embedding model
embedding_ctx_size=$(awk -F'"' '/"embedding_ctx_size":/ {print $4}' config.json)
# parse batch size for embedding model
embedding_batch_size=$(awk -F'"' '/"embedding_batch_size":/ {print $4}' config.json)
# parse port for LlamaEdge API Server
llamaedge_port=$(awk -F'"' '/"llamaedge_port":/ {print $4}' config.json)
# parse qdrant limit
qdrant_limit=$(awk -F'"' '/"qdrant_limit":/ {print $4}' config.json)
# parse qdrant score threshold
qdrant_score_threshold=$(awk -F'"' '/"qdrant_score_threshold":/ {print $4}' config.json)
# parse context window
# check if context window is present in config.json
if grep -q '"context_window":' config.json; then
context_window=$(awk -F'"' '/"context_window":/ {print $4}' config.json)
else
context_window=1
fi
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
if lsof -Pi :$llamaedge_port -sTCP:LISTEN -t >/dev/null ; then
printf " Port $llamaedge_port is in use. Exit ...\n\n"
# stop the qdrant instance
if [ "$qdrant_already_running" = false ]; then
# stop the Qdrant instance
qdrant_pid=$gaianet_base_dir/qdrant.pid
if [ -f $qdrant_pid ]; then
printf " Stopping Qdrant instance ...\n"
kill -9 $(cat $qdrant_pid)
rm $qdrant_pid
fi
fi
exit 1
fi
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
printf "For Windows users, please run this script in WSL.\n"
exit 1
else
printf "Only support Linux, MacOS and Windows.\n"
exit 1
fi
cd $gaianet_base_dir
llamaedge_wasm="$gaianet_base_dir/rag-api-server.wasm"
if [ ! -f "$llamaedge_wasm" ]; then
error "Not found rag-api-server.wasm at $$gaianet_base_dir"
exit 1
fi
# command to start LlamaEdge API Server
cd $gaianet_base_dir
cmd=(wasmedge --dir .:./dashboard \
--env NODE_VERSION=$installer_version \
--nn-preload default:GGML:AUTO:$chat_model_name \
--nn-preload embedding:GGML:AUTO:$embedding_model_name \
rag-api-server.wasm \
--model-name $chat_model_stem,$embedding_model_stem \
--ctx-size $chat_ctx_size,$embedding_ctx_size \
--batch-size $chat_batch_size,$embedding_batch_size \
--prompt-template $prompt_type,embedding \
--rag-policy $rag_policy \
--qdrant-collection-name $embedding_collection_name \
--qdrant-limit $qdrant_limit \
--qdrant-score-threshold $qdrant_score_threshold \
--context-window $context_window \
--web-ui ./ \
--socket-addr 0.0.0.0:$llamaedge_port)
if $use_supervise; then
cmd_string=""
for i in "${cmd[@]}"; do
if [[ $i == *" "* ]]; then
cmd_string+=\""$i"\"
else
cmd_string+="$i"
fi
cmd_string+=" "
done
fi
# Add rag prompt if it exists
if [ -n "$rag_prompt" ]; then
cmd+=("--rag-prompt" "$rag_prompt")
if $use_supervise; then
cmd_string+="--rag-prompt \"$rag_prompt\" "
fi
fi
# Add reverse prompt if it exists
if [ -n "$reverse_prompt" ]; then
cmd+=("--reverse-prompt" "$reverse_prompt")
if $use_supervise; then
cmd_string+="--reverse-prompt \"$reverse_prompt\" "
fi
fi
printf " Run the following command to start the LlamaEdge API Server:\n\n"
for i in "${cmd[@]}"; do
if [[ $i == *" "* ]]; then
printf "\"%s\" " "$i"
else
printf "%s " "$i"
fi
done
printf "\n\n"
if $use_supervise; then
# create `run` file for supervise
echo '#!/bin/bash' > $gaianet_base_dir/run
echo $cmd_string >> $gaianet_base_dir/run
chmod u+x $gaianet_base_dir/run
fi
# start api-server
retry_count=0
start_retry_cout=0
max_retries=3
while true; do
# start api-server
if $use_supervise; then
# start LlamaEdge API Server with supervise
if [ "$local_log_storage" -eq 1 ]; then
nohup supervise $gaianet_base_dir > $log_dir/start-llamaedge.log 2>&1 &
else
nohup supervise $gaianet_base_dir | vector --config $gaianet_base_dir/vector.toml > $log_dir/start-vector.log 2>&1 &
fi
sleep 2
supervise_pid=$!
echo $supervise_pid > $gaianet_base_dir/supervise.pid
printf "\n Daemotools-Supervise started with pid: $supervise_pid\n"
# Get the status of the service
status=$(svstat $gaianet_base_dir)
# Extract the PID from the status
llamaedge_pid=$(echo $status | awk '{print $4}' | tr -d ')')
# The reason of incrementing the PID by 1 is that the PID returned by `svstat` is less 1 than the PID returned by `pgrep`
llamaedge_pid=$((llamaedge_pid + 1))
echo $llamaedge_pid > $gaianet_base_dir/llamaedge.pid
info "\n LlamaEdge-RAG API Server started with pid: $llamaedge_pid"
else
# start LlamaEdge API Server with nohup
if [ "$local_log_storage" -eq 1 ]; then
nohup "${cmd[@]}" > $log_dir/start-llamaedge.log 2>&1 &
else
nohup "${cmd[@]}" | vector --config $gaianet_base_dir/vector.toml > $log_dir/start-vector.log 2>&1 &
fi
sleep 2
llamaedge_pid=$!
echo $llamaedge_pid > $gaianet_base_dir/llamaedge.pid
info " LlamaEdge API Server started with pid: $llamaedge_pid"
fi
sleep 10
info " Verify the LlamaEdge-RAG API Server. Please wait seconds ..."
if [[ "$prompt_type" == *"tool"* ]]; then
status_code=$(curl -o /dev/null -s -w "%{http_code}\n" \
-X POST http://localhost:$llamaedge_port/v1/chat/completions \
-H 'accept:application/json' \
-H 'Content-Type: application/json' \
-d "{\"messages\":[{\"role\":\"user\", \"content\": \"What is your name?\"}], \"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"get_name\",\"description\":\"Return your name\"}}], \"model\":\"$chat_model_stem\"}")
else
status_code=$(curl -o /dev/null -s -w "%{http_code}\n" \
-X POST http://localhost:$llamaedge_port/v1/chat/completions \
-H 'accept:application/json' \
-H 'Content-Type: application/json' \
-d "{\"messages\":[{\"role\":\"user\", \"content\": \"What is your name?\"}], \"model\":\"$chat_model_stem\"}")
fi
curl_exit_status=$?
if [ $curl_exit_status -eq 0 ] && [ "$status_code" -eq 200 ]; then
info " * LlamaEdge-RAG API Server is ready."
break
else
tail -2 $log_dir/start-llamaedge.log
# stop the api-server
pkill -9 wasmedge || true
# stop supervise if it is running
if svok $gaianet_base_dir > /dev/null 2>&1; then
svc -d $gaianet_base_dir
svc -k $gaianet_base_dir
svc -x $gaianet_base_dir
supervise_pid=$gaianet_base_dir/supervise.pid
if [ -f $supervise_pid ]; then
rm $supervise_pid
fi
rm $gaianet_base_dir/run
rm -rf $gaianet_base_dir/supervise
fi
# remove the pid file
llamaedge_pid=$gaianet_base_dir/llamaedge.pid
if [ -f $llamaedge_pid ]; then
rm $llamaedge_pid
fi
sleep 10 # wait for 10 seconds before retrying
((start_retry_cout++))
if [ $start_retry_cout -ge $((max_retries + 1)) ]; then
error " * Failed to start LlamaEdge API Server after $max_retries retries. Exiting ..."
# stop the Qdrant instance
pkill -9 qdrant || true
qdrant_pid=$gaianet_base_dir/qdrant.pid
if [ -f $qdrant_pid ]; then
rm $qdrant_pid
fi
# wait for 3 seconds before exiting
sleep 3
exit 1
else
error " * LlamaEdge API Server is not ready. Retrying ($start_retry_cout)..."
fi
fi
done
else
# 2. start llama-api-server
printf "[+] Starting LlamaEdge API Server ...\n\n"
# parse cli options for chat model
cd $gaianet_base_dir
url_chat_model=$(awk -F'"' '/"chat":/ {print $4}' config.json)
# gguf filename
chat_model_name=$(basename $url_chat_model)
# Directly attempt to extract "chat_name" and fallback to extracting from "chat" if empty
chat_name=$(grep '"chat_name":' config.json | sed -E 's/.*"chat_name": *"([^"]*)".*/\1/')
if [ -z "$chat_name" ]; then
chat_model_stem=$(basename "${url_chat_model%.*}")
else
chat_model_stem=$chat_name
fi
# parse context size for chat model
chat_ctx_size=$(awk -F'"' '/"chat_ctx_size":/ {print $4}' config.json)
# parse batch size for chat model
chat_batch_size=$(awk -F'"' '/"chat_batch_size":/ {print $4}' config.json)
# parse prompt type for chat model
prompt_type=$(awk -F'"' '/"prompt_template":/ {print $4}' config.json)
# parse reverse prompt for chat model
reverse_prompt=$(awk -F'"' '/"reverse_prompt":/ {print $4}' config.json)
url_embedding_model=$(awk -F'"' '/"embedding":/ {print $4}' config.json)
# gguf filename
embedding_model_name=$(basename $url_embedding_model)
# Directly attempt to extract "embedding_name" and fallback to extracting from "embedding" if empty
embedding_name=$(grep '"embedding_name":' config.json | sed -E 's/.*"embedding_name": *"([^"]*)".*/\1/')
if [ -z "$embedding_name" ]; then
embedding_model_stem=$(basename "${url_embedding_model%.*}")
else
embedding_model_stem=$embedding_name
fi
# parse cli options for embedding vector collection name
embedding_collection_name=$(awk -F'"' '/"embedding_collection_name":/ {print $4}' config.json)
if [[ -z "$embedding_collection_name" ]]; then
embedding_collection_name="default"
fi
# parse context size for embedding model
embedding_ctx_size=$(awk -F'"' '/"embedding_ctx_size":/ {print $4}' config.json)
# parse batch size for embedding model
embedding_batch_size=$(awk -F'"' '/"embedding_batch_size":/ {print $4}' config.json)
# parse port for LlamaEdge API Server
llamaedge_port=$(awk -F'"' '/"llamaedge_port":/ {print $4}' config.json)
# check port
if [ "$(uname)" == "Darwin" ] || [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
if lsof -Pi :$llamaedge_port -sTCP:LISTEN -t >/dev/null ; then
error " Port $llamaedge_port is in use. Exit ..."
exit 1
fi
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ]; then
error "For Windows users, please run this script in WSL. Exit ..."
exit 1
else
error "Only support Linux, MacOS and Windows. Exit ..."
exit 1
fi
cd $gaianet_base_dir
llamaedge_wasm="$gaianet_base_dir/llama-api-server.wasm"
if [ ! -f "$llamaedge_wasm" ]; then
error "Not found llama-api-server.wasm in $gaianet_base_dir\n"
exit 1
fi