-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathchatgpt.sh
executable file
·7011 lines (6468 loc) · 238 KB
/
chatgpt.sh
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
# chatgpt.sh -- Shell Wrapper for ChatGPT/DALL-E/Whisper/TTS
# v0.92.4 jan/2025 by mountaineerbr GPL+3
set -o pipefail; shopt -s extglob checkwinsize cmdhist lithist histappend;
export COLUMNS LINES; ((COLUMNS>2)) || COLUMNS=80; ((LINES>2)) || LINES=24;
# API keys
#OPENAI_API_KEY=
#GOOGLE_API_KEY=
#MISTRAL_API_KEY=
#GROQ_API_KEY=
#ANTHROPIC_API_KEY=
#GITHUB_TOKEN=
#NOVITA_API_KEY=
#XAI_API_KEY=
# DEFAULTS
# Text cmpls model
MOD="gpt-3.5-turbo-instruct"
# Chat cmpls model
MOD_CHAT="${MOD_CHAT:-gpt-4o}" #"chatgpt-4o-latest"
# Image model (generations)
MOD_IMAGE="${MOD_IMAGE:-dall-e-3}"
# Whisper model (STT)
MOD_AUDIO="${MOD_AUDIO:-whisper-1}"
MOD_AUDIO_GROQ="${MOD_AUDIO_GROQ:-whisper-large-v3}"
# Speech model (TTS)
MOD_SPEECH="${MOD_SPEECH:-tts-1}"
# LocalAI model
MOD_LOCALAI="${MOD_LOCALAI:-phi-2}"
# Ollama model
MOD_OLLAMA="${MOD_OLLAMA:-llama3.2}"
# Google AI model
MOD_GOOGLE="${MOD_GOOGLE:-gemini-2.0-flash-exp}"
# Mistral AI model
MOD_MISTRAL="${MOD_MISTRAL:-mistral-large-latest}"
# Groq model
MOD_GROQ="${MOD_GROQ:-llama-3.1-70b-versatile}"
# Enable Groq Whisper only
#WHISPER_GROQ=
# Anthropic model
MOD_ANTHROPIC="${MOD_ANTHROPIC:-claude-3-5-sonnet-latest}"
# Github Azure model
MOD_GITHUB="${MOD_GITHUB:-Phi-3-medium-128k-instruct}"
# Novita AI model
MOD_NOVITA="${MOD_NOVITA:-sao10k/l3-70b-euryale-v2.1}"
# xAI model
MOD_XAI="${MOD_XAI:-grok-2-latest}"
# Bash readline mode
READLINEOPT="emacs" #"vi"
# Stream response
STREAM=1
# Prompter flush with <CTRL-D>
#OPTCTRD=
# Temperature
#OPTT=
# Whisper temperature
OPTTW=0
# Top_p probability mass (nucleus sampling)
#OPTP=1
# Maximum response tokens
OPTMAX=1024
# Model capacity (auto)
#MODMAX=
# Presence penalty
#OPTA=
# Frequency penalty
#OPTAA=
# N responses of Best_of
#OPTB=
# Number of responses
OPTN=1
# Keep Alive (seconds, Ollama)
#OPT_KEEPALIVE=
# Seed (integer)
#OPTSEED=
# Set python tiktoken
#OPTTIK=
# Image size
#OPTS=1024x1024 #hd
#Image style
#OPTI_STYLE=natural #vivid
# Image out format
OPTI_FMT=b64_json #url
# TTS voice
OPTZ_VOICE=echo #alloy, echo, fable, onyx, nova, and shimmer
# TTS voice speed
#OPTZ_SPEED= #0.25 - 4.0
# TTS out file format
#OPTZ_FMT=opus #mp3, opus, aac, flac, wav, pcm16
# Recorder command, e.g. "sox -d"
#REC_CMD=""
# Media player command, e.g. "cvlc"
#PLAY_CMD=""
# Clipboard set command, e.g. "xsel -b", "pbcopy"
#CLIP_CMD=""
# Markdown renderer, e.g. "pygmentize -s -lmd", "glow", "mdless", "mdcat"
#MD_CMD="bat"
# Fold response (wrap at white spaces)
OPTFOLD=1
# Avoid using dialog
#NO_DIALOG=
# Inject restart text
#RESTART=""
# Inject start text
#START=""
# Chat mode of text cmpls sets "\nQ: " and "\nA:"
# Reasoning effort
#REASON_EFFORT= #low, medium, or high
# Reasoning interactive
#REASON_INTERACTIVE= #true or false
# Input and output prices (dollars per million tokens)
#MOD_PRICE="0 0"
# Currency rate against USD
# e.g. BRL is 5.66 USD, JPY is 0.006665 USD
#CURRENCY_RATE="1"
# INSTRUCTION
# Chat completions, chat mode only
# INSTRUCTION=""
INSTRUCTION_CHAT_EN="The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and friendly."
INSTRUCTION_CHAT_PT="A seguinte é uma conversa com um assistente de IA. O assistente é prestativo, criativo, sagaz e amigável."
INSTRUCTION_CHAT_ES="Lo siguiente es una conversación con un asistente de IA. El asistente es servicial, creativo, listo y amigable."
INSTRUCTION_CHAT_IT="La seguente è una conversazione con un assistente AI. L'assistente è utile, creativo, sveglio e amichevole."
INSTRUCTION_CHAT_FR="Ce qui suit est une conversation avec un assistant d'IA. L'assistant est prévenant, créatif, astucieux et amical."
INSTRUCTION_CHAT_DE="Das Folgende ist ein Gespräch mit einem KI-Assistenten. Der Assistent ist hilfsbereit, kreativ, klug und freundlich."
INSTRUCTION_CHAT_RU="Далее приводится разговор с ИИ-ассистентом. Ассистент полезный, креативный, сообразительный и дружелюбный."
INSTRUCTION_CHAT_JA="以下は、AIアシスタントとの会話です。アシスタントは、親切で、創造的で、賢く、そしてフレンドリーです。"
INSTRUCTION_CHAT_ZH="以下是对话内容与一位人工智能助手之间的对话。该助手乐于助人、富有创造力、聪明且友好。"
INSTRUCTION_CHAT_ZH_TW="以下是对话內容與一位人工智慧助手之間的對話。該助手樂於助人、富有創造力、聰明且友善。"
INSTRUCTION_CHAT_HI="निम्न एक एआई सहायक के साथ एक वार्तालाप है। सहायक मददगार, रचनात्मक, चतुर और मित्रवत है।"
INSTRUCTION_CHAT="${INSTRUCTION_CHAT-$INSTRUCTION_CHAT_EN}"
# Insert timestamp in instruction prompt
#INST_TIME=0
# Awesome-chatgpt-prompts URL
AWEURL="https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
AWEURLZH="https://raw.githubusercontent.com/PlexPt/awesome-chatgpt-prompts-zh/main/prompts-zh.json" #prompts-zh-TW.json
# CACHE AND OUTPUT DIRECTORIES
CACHEDIR="${CACHEDIR:-${XDG_CACHE_HOME:-$HOME/.cache}}/chatgptsh"
OUTDIR="${OUTDIR:-${XDG_DOWNLOAD_DIR:-$HOME/Downloads}}"
# Colour palette
# Normal Colours # Bold # Background
Black='\u001b[0;30m' BBlack='\u001b[1;30m' On_Black='\u001b[40m' \
Red='\u001b[0;31m' BRed='\u001b[1;31m' On_Red='\u001b[41m' \
Green='\u001b[0;32m' BGreen='\u001b[1;32m' On_Green='\u001b[42m' \
Yellow='\u001b[0;33m' BYellow='\u001b[1;33m' On_Yellow='\u001b[43m' \
Blue='\u001b[0;34m' BBlue='\u001b[1;34m' On_Blue='\u001b[44m' \
Purple='\u001b[0;35m' BPurple='\u001b[1;35m' On_Purple='\u001b[45m' \
Cyan='\u001b[0;36m' BCyan='\u001b[1;36m' On_Cyan='\u001b[46m' \
White='\u001b[0;37m' BWhite='\u001b[1;37m' On_White='\u001b[47m' \
Inv='\u001b[0;7m' Nc='\u001b[m' Alert=$BWhite$On_Red \
Bold='\u001b[0;1m';
HISTSIZE=256;
# Load user defaults
((${#CHATGPTRC})) || CHATGPTRC="$HOME/.chatgpt.conf"
[[ -f "${OPTF}${CHATGPTRC}" ]] && . "$CHATGPTRC";
# Set file paths
FILE="${CACHEDIR%/}/chatgpt.json"
FILESTREAM="${CACHEDIR%/}/chatgpt_stream.json"
FILECHAT="${FILECHAT:-${CACHEDIR%/}/chatgpt.tsv}"
FILEWHISPER="${FILECHAT%/*}/whisper.json"
FILEWHISPERLOG="${OUTDIR%/*}/whisper_log.txt"
FILETXT="${CACHEDIR%/}/chatgpt.txt"
FILEOUT="${OUTDIR%/}/dalle_out.png"
FILEOUT_TTS="${OUTDIR%/}/tts.${OPTZ_FMT:=opus}"
FILEIN="${CACHEDIR%/}/dalle_in.png"
FILEINW="${CACHEDIR%/}/whisper_in.${REC_FMT:=mp3}"
FILEAWE="${CACHEDIR%/}/awesome-prompts.csv"
FILEFIFO="${CACHEDIR%/}/fifo.buff"
FILEMODEL="${CACHEDIR%/}/models.txt"
USRLOG="${OUTDIR%/}/${FILETXT##*/}"
HISTFILE="${CACHEDIR%/}/history_bash"
HISTCONTROL=erasedups:ignoredups
SAVEHIST=$HISTSIZE HISTTIMEFORMAT='%F %T '
# API URL / endpoint
OPENAI_BASE_URL_DEF="https://api.openai.com/v1";
OLLAMA_BASE_URL_DEF="http://localhost:11434";
LOCALAI_BASE_URL_DEF="http://127.0.0.1:8080/v1";
MISTRAL_BASE_URL_DEF="https://api.mistral.ai/v1";
GOOGLE_BASE_URL_DEF="https://generativelanguage.googleapis.com/v1beta";
GROQ_BASE_URL_DEF="https://api.groq.com/openai/v1";
ANTHROPIC_BASE_URL_DEF="https://api.anthropic.com/v1";
GITHUB_BASE_URL_DEF="https://models.inference.ai.azure.com";
NOVITA_BASE_URL_DEF="https://api.novita.ai/v3/openai";
XAI_BASE_URL_DEF="https://api.x.ai/v1";
OPENAI_API_KEY_DEF=$OPENAI_API_KEY;
BASE_URL=$OPENAI_BASE_URL_DEF;
# Def hist, txt chat types
Q_TYPE="\\nQ: "
A_TYPE="\\nA:"
S_TYPE="\\n\\nSYSTEM: "
I_TYPE_STR="[insert]"
I_TYPE="\\[[Ii][Nn][Ss][Ee][Rr][Tt]\\]"
# Globs
SPC="*([$IFS])"
SPC1="*(\\\\[ntrvf]|[$IFS])"
NL=$'\n' BS=$'\b'
UAG='user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' #chrome on win10
PLACEHOLDER='sk-CbCCb0CC0bbbCbb0CCCbC0CbbbCC00bC00bbCbbCbbbCbb0C'
TIME_ISO8601_FMT='%Y-%m-%dT%H:%M:%S%z'
TIME_RFC5322_FMT='%a, %d %b %Y %H:%M:%S %z'
HELP="Name
${0##*/} -- Wrapper for ChatGPT / DALL-E / Whisper / TTS
Synopsis
${0##*/} [-cc|-dd|-qq] [opt..] [PROMPT|TEXT_FILE|PDF_FILE]
${0##*/} -i [opt..] [X|L|P][hd] [PROMPT] #dall-e-3
${0##*/} -i [opt..] [S|M|L] [PROMPT]
${0##*/} -i [opt..] [S|M|L] [PNG_FILE]
${0##*/} -i [opt..] [S|M|L] [PNG_FILE] [MASK_FILE] [PROMPT]
${0##*/} -w [opt..] [AUDIO_FILE|.] [LANG] [PROMPT]
${0##*/} -W [opt..] [AUDIO_FILE|.] [PROMPT-EN]
${0##*/} -z [OUTFILE|FORMAT|-] [VOICE] [SPEED] [PROMPT]
${0##*/} -ccWwz [opt..] -- [PROMPT] -- [whisper_arg..] -- [tts_arg..]
${0##*/} -l [MODEL]
${0##*/} -TTT [-v] [-m[MODEL|ENCODING]] [INPUT|TEXT_FILE|PDF_FILE]
${0##*/} -HPP [/HIST_NAME|.]
${0##*/} -HPw
Description
Wraps ChatGPT, DALL-E, Whisper, and TTS endpoints from various
providers.
Defaults to single-turn native chat completions. Handles multi-turn
chat, text completions, image generation/editing, speech-to-text,
and text-to-speech models.
Positional arguments are read as a single PROMPT. Some functions
such as Whisper and TTS may handle optional positional parameters
before the prompt itself.
Chat Completion Mode
Set option -c to start multi-turn chat mode via text completions
(instruct models) or -cc for native chat completions (gpt-3.5+
models) with interactive history support.
In chat mode, some options are automatically set to un-lobotomise
the bot.
Option -C resumes last history session. To exit on first response,
set option -E.
Text Completion Mode
Option -d initiates a single-turn session of plain text completions.
Further options (e.g., instructions, temperature, stop sequences)
must be set explicitly at the command line.
Text completions in multi-turn mode with history support is set
with options -dd. Use models as gpt-3.5-turbo-instruct.
Insert Mode (FIM)
Set option -qq for multi turn insert mode, and add tag \`[insert]'
to the prompt at the location to be filled in (instruct models).
Instruction Prompts
The SYSTEM INSTRUCTION prompt may be set with option -S or via
envars \`\$INSTRUCTION' and \`\$INSTRUCTION_CHAT'.
If a plain text or PDF file path is set as the argument to \`-S',
the text of the file is loaded as the INSTRUCTION.
To create and reuse a custom prompt, set the prompt name you wish
as the option argument preceded by dot or comma, such as
\`-S .[prompt_name]' or \`-S ,[prompt_name]'.
Alternatively, set the first positional argument with the operator
dot \`.' and the prompt name, such as \`${0##*/} -cc .[prompt]'.
To insert the current date and time to the instruction prompt, set
command line option \`--time'.
Image Generations and Edits (Dall-E)
Option -i generates or edits images. A text prompt is required for
generations. An image file is required for variations. Edits need
an image file, a mask (or the image must have a transparent layer),
and a text prompt to direct the editing.
Size of output image may be set as the first positional parameter,
options are: \`256x256' (S), \`512x512' (M), \`1024x1024' (L),
\`1792x1024' (X), and \`1024x1792' (P). The parameter \`hd' may also
be set for quality (Dall-E-3), such as \`Xhd', or \`1792x1024hd'.
For Dalle-3, optionally set the generation style as either \"natural\"
or \"vivid\" as a positional parameter.
Speech-To-Text (Whisper)
Option -w transcribes audio to any language, and option -W translates
audio to English text. Set these options twice to have phrasal-
level timestamps, options -ww, and -WW. Set thrice for word-level
timestamps.
Text-To-Voice (TTS)
Option -z synthesises voice from text (TTS models). Set a voice as
the first positional parameter (\`alloy', \`echo', \`fable', \`onyx',
\`nova', or \`shimmer'). Set the second positional parameter as the
speed (0.25 - 4.0), and, finally the output file name or the format,
such as \`./new_audio.mp3' (\`mp3', \`opus', \`aac', and \`flac'),
or \`-' for stdout. Set options -vz to not play received output.
Environment
BLOCK_USR
BLOCK_USR_TTS Extra options for the request JSON block
(e.g. \`\"seed\": 33, \"dimensions\": 1024').
CACHEDIR Script cache directory base.
CHATGPTRC Path to the user configuration file.
Defaults=${CHATGPTRC/"$HOME"/"~"}
FILECHAT Path to a history / session TSV file.
INSTRUCTION Initial instruction message.
INSTRUCTION_CHAT
Initial instruction or system message (chat mode).
LC_ALL
LANG Default instruction language (chat mode).
MOD_CHAT MOD_IMAGE MOD_AUDIO
MOD_SPEECH MOD_LOCALAI MOD_OLLAMA
MOD_MISTRAL MOD_GOOGLE MOD_GROQ
MOD_AUDIO_GROQ MOD_ANTHROPIC MOD_GITHUB
MOD_NOVITA MOD_XAI
Set default model for each endpoint / provider.
OPENAI_BASE_URL
OPENAI_URL_PATH Main Base URL setting. Alternatively, provide the
URL_PATH parameter to disable endpoint auto-selection.
[PROVIDER]_BASE_URL
Base URLs for providers: LOCALAI, OLLAMA,
MISTRAL, GOOGLE, GROQ, ANTHROPIC, and GITHUB.
OPENAI_API_KEY [PROVIDER]_API_KEY
GITHUB_TOKEN Keys for OpenAI, Gemini, Mistral, Groq,
Anthropic, GitHub Models, Novita, and xAI APIs.
OUTDIR Output directory for received image and audio.
RESTART
START Restart and start sequences. May be set to null.
VISUAL
EDITOR Text editor for external prompt editing.
Defaults=\"${VISUAL:-${EDITOR:-vim}}\"
CLIP_CMD Clipboard set command, e.g. \`xsel -b', \`pbcopy'.
PLAY_CMD Audio player command, e.g. \`mpv --no-video --vo=null'.
REC_CMD Audio recorder command, e.g. \`sox -d'.
Notes
Input sequences \`\\n' and \`\\t' are only treated specially in
restart, start and stop sequences in chat mode!
Online documentation and usage examples:
<https://gitlab.com/fenixdragao/shellchatgpt>.
Command Interface
When the first positional argument starts with the command operator
\`/' on script invocation, the command \`/session [HIST_NAME]' is
assumed. This changes to or creates a history file (with -ccCdPP).
To append image and audio file paths at the end of the prompt with
multimodal and reasoning models. All models work with PDF, DOC, and
URL text dump, provided required software is installed. Make sure
file paths containing spaces are backslash-escaped.
In multi-turn interactions, prompts starting with a colon \`:' are
appended as user messages to the request block, while double colons
\`::' append the prompt as instruction / system without initiating
a new API request.
Command List
In chat mode, commands are invoked with either \`!' or \`/' as
operators. The following modify settings and manage sessions.
------- ---------- -----------------------------------------
--- Misc Commands ------------------------------------------------
-S :, :: [PROMPT] Append user/system prompt to request.
-S. -. [NAME] Load and edit custom prompt.
-S/ !awe [NAME] Load and edit awesome prompt (en).
-S% !awe-zh [NAME] Load and edit awesome prompt (zh).
-Z !last Print last response JSON.
!# !save [PROMPT] Save current prompt to shell history. ‡
! !r, !regen Regenerate last response.
!! !rr Regenerate response, edit prompt first.
!g: !!g: [PROMPT] Ground prompt, insert search results. ‡
!i !info Info on model and session settings.
!!i !!info Monthly usage stats (OpenAI).
!j !jump Jump to request, append response primer.
!!j !!jump Jump to request, no response priming.
!cat - Cat prompter (one-shot, ctrl-d).
!cat !cat: [TXT|URL|PDF] Cat text or PDF file, dump URL.
!dialog - Toggle the \`dialog' interface.
!img !media [FILE|URL] Append image, media, or URL to prompt.
!md !markdown [SOFTW] Toggle markdown support in response.
!!md !!markdown [SOFTW] Render last response in markdown.
!rep !replay Replay last TTS audio response.
!res !resubmit Resubmit last STT recorded audio input.
!p !pick [PROMPT] File picker, appends filepath to prompt. ‡
!pdf !pdf: [FILE] Dump PDF text.
!photo !!photo [INDEX] Take a photo, camera index (Termux). ‡
!sh !shell [CMD] Run shell or command, and edit output. ‡
!sh: !shell: [CMD] Same as !sh but apppend output as user.
!!sh !!shell [CMD] Run interactive shell (w/ cmd) and exit.
!url !url: [URL] Dump URL text or YouTube transcript.
--- Script Settings and UX ---------------------------------------
!fold !wrap Toggle response wrapping.
-g !stream Toggle response streaming.
-h !help [REGEX] Print help, optionally set regex.
-l !models [NAME] List language models or model details.
-o !clip Copy responses to clipboard.
-u !multi Toggle multiline, ctrl-d flush.
-uu !!multi Multiline, one-shot, ctrl-d flush.
-U -UU Toggle cat prompter or set one-shot.
-V !debug Dump raw request block and confirm.
-v !ver Toggle verbose modes.
-x !ed Toggle text editor interface.
-xx !!ed Single-shot text editor.
-y !tik Toggle python tiktoken use.
!q !quit Exit. Bye.
--- Model Settings -----------------------------------------------
!Nill -Nill Unset max response tkns (chat cmpls).
!NUM -M [NUM] Max response tokens.
!!NUM -N [NUM] Model token capacity.
-a !pre [VAL] Presence penalty.
-A !freq [VAL] Frequency penalty.
-b !best [NUM] Best-of n results.
-j !seed [NUM] Seed number (integer).
-K !topk [NUM] Top_k.
-m !mod [MOD] Model by name or pick from list.
-n !results [NUM] Number of results.
-p !topp [VAL] Top_p.
-r !restart [SEQ] Restart sequence.
-R !start [SEQ] Start sequence.
-s !stop [SEQ] One stop sequence.
-t !temp [VAL] Temperature.
-w !rec [ARGS] Toggle voice chat mode (Whisper).
-z !tts [ARGS] Toggle TTS chat mode (speech out).
!blk !block [ARGS] Set and add options to JSON request.
!effort - [MODE] Reasoning effort: high, medium, or low.
!interactive - Toggle reasoning interactive mode.
!ka !keep-alive [NUM] Set duration of model load in memory
!vision !audio Toggle model multimodality type.
--- Session Management -------------------------------------------
-H !hist Edit raw history file in editor.
-P -HH, !print Print session history.
-L !log [FILEPATH] Save to log file (pretty-print).
!br !break, !new Start new session (session break).
!ls !list [GLOB] List Hist files with glob in name. All: \`.'.
Instruction prompts: \`pr'. Awesome: \`awe'.
!grep !sub [REGEX] Search sessions and copy to tail.
!c !copy [SRC_HIST] [DEST_HIST]
Copy session from source to destination.
!f !fork [DEST_HIST] Fork current session to destination.
!k !kill [NUM] Comment out n last entries in hist file.
!!k !!kill [[0]NUM] Dry-run of command !kill.
!s !session [HIST_NAME]
Change to, search for, or create hist file.
!!s !!session [HIST_NAME]
Same as !session, break session.
------- ---------- -----------------------------------------
: Commands with a colon have their output appended to the prompt.
‡ Commands with double dagger may be invoked at the very end of
the prompt.
Examples
\`/temp 0.7', \`!modgpt-4', \`-p 0.2',
\`[PROMPT] /pick', \`[PROMPT] /sh'.
Notes
To change to a specific history file, run \`/session [HIST_NAME]',
or simply \`/[HIST_NAME]' at script invocation.
In order to resume an old session, execute command \`sub' or the
alias \`/.'. On script invocation, resuming is aliased to \`.'
when a dot is set as the first positional parameter.
To regenerate a response, type in the command \`!regen' or a single
exclamation mark or forward slash in the new empty prompt. In order
to edit the prompt before the request, try \`!!' (or \`//').
Press <CTRL-X CTRL-E> to edit command line in text editor (readline).
Press <CTRL-J> or <CTRL-V CTRL-J> for newline (readline).
Press <CTRL-L> to redraw readline buffer (user input) on screen.
Press <CTRL-C> during cURL requests to interrupt the call.
Press <CTRL-\\> to terminate the script at any time (QUIT signal),
or \`Q' in user confirmation prompts.
Options
Service Providers
--anthropic
Anthropic integration (cmpls/chat).
--github
GitHub Models integration (chat).
--google
Google Gemini integration (cmpls/chat).
--groq Groq AI integration (chat).
--localai
LocalAI integration (cmpls/chat).
--mistral
Mistral AI integration (chat).
--novita
Novita AI integration (cmpls/chat).
--openai
Reset service integrations.
-O, --ollama
Ollama server integration (cmpls/chat).
--xai xAI's Grok integration (cmpls/chat).
Configuration File
-f, --no-conf
Ignore user configuration file.
-F Edit configuration file, if it exists.
\$CHATGPTRC=${CHATGPTRC/"$HOME"/"~"}.
-FF Dump template configuration file to stdout.
Sessions and History Files
-H, --hist [/HIST_NAME]
Edit history file with text editor or pipe to stdout.
A hist file name can be optionally set as argument.
-P, -PP, --print [/HIST_NAME] (aliases to -HH and -HHH)
Print out last history session. Set twice to print
commented out entries, too. Heeds -ccdrR.
Input Modes
-u, --multiline
Toggle multiline prompter, <CTRL-D> flush.
-U, --cat
Cat prompter, <CTRL-D> flush.
-x, -xx, --editor
Edit prompt in text editor. Set twice for single-shot.
Options -eex to edit last text buffer from cache.
Interface Modes
-c, --chat
Chat mode in text completions (used with -wzvv).
-cc Chat mode in chat completions (used with -wzvv).
-C, --continue, --resume
Continue from (resume) last session (cmpls/chat).
-d, --text
Single-turn session of plain text completions.
-dd Same as -d, multi-turn and history support.
-e, --edit
Edit the first input before request. (cmpls/chat).
With options -eex, edit the last text editor buffer.
-E, -EE, --exit
Exit on first run (even with -cc).
-g, --stream (defaults)
Response streaming.
-G, --no-stream
Unset response streaming.
-i, --image [PROMPT]
Generate images given a prompt.
-i [PNG]
Create variations of a given image.
-i [PNG] [MASK] [PROMPT]
Edit image with mask, and prompt (required).
-q, -qq, --insert
Insert text mode. Use \`[insert]' tag within the prompt.
Set twice for multi-turn (\`instruct', Mistral \`code' models).
-S .[PROMPT_NAME], -.[PROMPT_NAME]
-S ,[PROMPT_NAME], -,[PROMPT_NAME]
Load, search for, or create custom prompt.
Set \`.[prompt]' to load prompt silently.
Set \`,[prompt]' to single-shot edit prompt.
Set \`,,[prompt]' to edit the prompt template.
Set \`.?' to list all prompt template files.
-S, --awesome /[AWESOME_PROMPT_NAME]
-S, --awesome-zh %[AWESOME_PROMPT_NAME_ZH]
Set or search an awesome-chatgpt-prompt(-zh).
Set \`//' or \`%%' to refresh cache.
-T, -TT, -TTT, --tiktoken
Count input tokens with Tiktoken. Set twice to print
tokens, thrice to available encodings. Set the model
or encoding with option -m. It heeds options -ccm.
-w, --transcribe [AUD] [LANG] [PROMPT]
Transcribe audio file into text (whisper models).
LANG is optional. A prompt that matches the audio language
is optional. Set twice to phrase or thrice for word-level
timestamps (-www). With -vv, stop voice recorder on silence.
-W, --translate [AUD] [PROMPT-EN]
Translate audio file into English text (whisper models).
Set twice to phrase or thrice for word-level timestamps (-WWW).
-z, --tts [OUTFILE|FORMAT|-] [VOICE] [SPEED] [PROMPT]
Synthesise speech from text prompt, set -v to not play.
Model Settings
-@, --alpha [[VAL%]COLOUR]
Transparent colour of image mask. Def=black.
Fuzz intensity can be set with [VAL%]. Def=0%.
-Nill
Unset model max response tokens (chat cmpls only).
-NUM
-M, --max [NUM[-NUM]]
Maximum number of \`response tokens'. Def=$OPTMAX.
A second number in the argument sets model capacity.
-N, --modmax [NUM]
Model capacity token value. Def=_auto_, Fallback=8000.
-a, --presence-penalty [VAL]
Presence penalty (cmpls/chat, -2.0 - 2.0).
-A, --frequency-penalty [VAL]
Frequency penalty (cmpls/chat, -2.0 - 2.0).
-b, --best-of [NUM]
Best of, must be greater than opt -n (cmpls). Def=1.
-B, --logprobs [NUM]
Request log probabilities, see -Z (cmpls, 0 - 5),
--effort [ high | medium | low ]
Amount of effort in reasoning models (OpenAI).
--interactive, --no-interactive
Reasoning model output style.
-j, --seed [NUM]
Seed for deterministic sampling (integer).
-K, --top-k [NUM]
Top_k value (local-ai, ollama, google).
--keep-alive, --ka [NUM]
How long the model will stay loaded into memory (Ollama).
-m, --model [MOD]
Language MODEL name or set it as \`.' to pick
from the list. Def=$MOD, $MOD_CHAT.
--multimodal, --vision, --audio
Model multimodal mode.
-n, --results [NUM]
Number of results. Def=$OPTN.
-p, --top-p [VAL]
Top_p value, nucleus sampling (cmpls/chat, 0.0 - 1.0).
-r, --restart [SEQ]
Restart sequence string (cmpls).
-R, --start [SEQ]
Start sequence string (cmpls).
-s, --stop [SEQ]
Stop sequences, up to 4. Def=\"<|endoftext|>\".
-S, --instruction [INSTRUCTION|FILE]
Set an instruction prompt. It may be a text file.
--time, --no-time
Insert the current date and time to the instruction prompt.
-t, --temperature [VAL]
Temperature value (cmpls/chat/whisper),
Def=${OPTT:-0} (0.0 - 2.0), Whisper=${OPTTW:-0} (0.0 - 1.0).
Miscellanous Settings
--api-key [KEY]
The API key to use.
--fold (defaults), --no-fold
Set or unset response folding (wrap at white spaces).
-h, --help
Print this help page.
--info Print OpenAI usage status (envar \`\$OPENAI_ADMIN_KEY\`).
-k, --no-colour
Disable colour output. Def=auto.
-l, --list-models [MOD]
List models or print details of MODEL.
-L, --log [FILEPATH]
Log file. FILEPATH is required.
--md, --markdown, --markdown=[SOFTWARE]
Enable markdown rendering in response. Software is optional:
\`bat', \`pygmentize', \`glow', \`mdcat', or \`mdless'.
--no-md, --no-markdown
Disable markdown rendering.
-o, --clipboard
Copy response to clipboard.
-v, --verbose
Less verbose. With -ccwv, sleep after response. With
-ccwzvv, stop recording voice input on silence and play
TTS response right away. May be set multiple times.
-V Dump raw request block to stderr (debug).
--version
Print script version.
-y, --tik
Tiktoken for token count (cmpls/chat).
-Y, --no-tik (defaults)
Unset tiktoken use (cmpls/chat).
-Z, -ZZ, -ZZZ, --last
Print data from the last JSON responses."
ENDPOINTS=(
/completions #0
/moderations #1
/edits #2 -> chat/completions
/images/generations #3
/images/variations #4
/embeddings #5
/chat/completions #6
/audio/transcriptions #7
/audio/translations #8
/images/edits #9
/audio/speech #10
/models #11
/organization #12
#/realtime #
)
#https://platform.openai.com/docs/{deprecations/,models/,model-index-for-researchers/}
#https://help.openai.com/en/articles/{6779149,6643408}
#set model endpoint based on its name
function set_model_epnf
{
unset OPTEMBED TKN_ADJ EPN6 MULTIMODAL
typeset -l model; model=${1##*/};
set -- "${model##ft:}";
if is_amodelf "$1"
then set -- "audio";
elif is_visionf "$1"
then set -- "vision";
fi;
case "${1##ft:}" in
*dalle-e*|*stable*diffusion*)
# 3 generations 4 variations 9 edits
((OPTII)) && EPN=4 || EPN=3;
((OPTII_EDITS)) && EPN=9;;
tts-*|*-tts-*) EPN=10;;
*whisper*) ((OPTWW)) && EPN=8 || EPN=7;;
code-*) case "$1" in
*search*) EPN=5 OPTEMBED=1;;
*) EPN=0;;
esac;;
text-*|*turbo-instruct*|*davinci*|*babbage*|ada|*moderation*|*embed*|*similarity*|*search*)
case "$1" in
*embed*|*similarity*|*search*) EPN=5 OPTEMBED=1;;
*moderation*) EPN=1 OPTEMBED=1;;
*) EPN=0;;
esac;;
o[1-9]*|chatgpt-*|gpt-[4-9]*|gpt-3.5*|gpt-*|*turbo*|*vision*|*audio*)
EPN=6 EPN6=6 OPTB= OPTBB=
((OPTC)) && OPTC=2
#set token adjustment per message
case "$MOD" in
gpt-3.5-turbo-0301) ((TKN_ADJ=4+1));;
gpt-3.5-turbo*|gpt-4*|*) ((TKN_ADJ=3+1));;
esac #https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
#also: <https://tiktokenizer.vercel.app/>
;;
*) #fallback
case "$1" in
*embed*|*similarity*|*search*)
EPN=5 OPTEMBED=1;;
*)
if ((OPTZ && !(MTURN+CHAT_ENV) ))
then OPTCMPL= OPTC= EPN=10;
elif ((OPTW && !(MTURN+CHAT_ENV) ))
then OPTCMPL= OPTC= EPN=7;
elif ((OPTI && !(MTURN+CHAT_ENV) ))
then # 3 generations 4 variations 9 edits
((OPTII)) && EPN=4 || EPN=3;
((OPTII_EDITS)) && EPN=9;
elif ((OPTEMBED))
then OPTCMPL= OPTC= EPN=1;
elif ((OPTCMPL || OPTSUFFIX))
then OPTC= EPN=0;
elif ((OPTC>1 || GROQAI || MISTRALAI || GOOGLEAI || GITHUBAI))
then OPTCMPL= EPN=6;
elif ((OPTC))
then OPTCMPL= EPN=0;
else EPN=0; #defaults
fi;;
esac
return 1;;
esac
}
#set ``model capacity''
function model_capf
{
typeset -l model; model=${1##*/};
case "${model##ft:}" in #ft: fine-tune models
open-codestral-mamba*|codestral-mamba*|ai21-jamba-1.5*|ai21-jamba-instruct)
MODMAX=256000;;
open-mixtral-8x22b)
MODMAX=64000;;
claude-[3-9]*|claude-2.1*)
MODMAX=200000;;
claude-2.0*|claude-instant*)
MODMAX=100000;;
*llama-3-8b-instruct|*llama-3-70b-instruct|*gemma-2-9b-it|\
*hermes-2-pro-llama-3-8b|llama3*|gemma-*|text-embedding-ada-002|\
*embedding*-002|*search*-002|grok-2-vision-1212|grok-vision-beta)
MODMAX=8191;; #8192
davinci|curie|babbage|ada)
MODMAX=2049;;
meta-llama-3-70b-instruct|meta-llama-3-8b-instruct|\
code-davinci-00[2-9]*|mistral-embed*|-8k*)
MODMAX=8001;;
gemini*-thinking*-exp*)
MODMAX=32768;;
gemini*-flash*)
MODMAX=1048576;; #std: 128000
gemini*-1.[5-9]*|gemini*-[2-9].[0-9]*|gemini-exp*)
MODMAX=2097152;; #std: 128000
*qwen-2.5-72b-instruct|learnlm-1.5-pro*)
MODMAX=32000;;
*l3-70b-euryale-v2.1|*l31-70b-euryale-v2.2|*dolphin-mixtral-8x22b)
MODMAX=16000;;
*llama-3.1-8b-instruct|davinci-00[2-9]|babbage-00[2-9]|gpt-3.5*16k*|\
*turbo*16k*|gpt-3.5-turbo-1106|gemini*-vision*|*-16k*)
MODMAX=16384;;
*llama-3.1-70b-instruct|*mistral-7b-instruct|*wizardlm-2-7b|*qwen-2-7*b-instruct*|\
gpt-4*32k*|*32k|*mi[sx]tral*|*codestral*|mistral-small|*mathstral*|*moderation*)
MODMAX=32768;;
o[1-9]*|gpt-4o*|chatgpt-*|gpt-[5-9]*|gpt-4-1106*|\
gpt-4-*preview*|gpt-4-vision*|gpt-4-turbo|gpt-4-turbo-202[4-9]-*|\
mistral-3b*|*mistral-nemo*|*mistral-large*|open-mistral-nemo*|\
phi-3.5-mini-instruct|phi-3.5-moe-instruct|phi-3.5-vision-instruct|\
*llama-[3-9].[1-9]*|*llama[4-9]-*|\
*llama[4-9]*|*ministral*|*pixtral*|*-128k*)
MODMAX=128000;;
grok*|*llama-3.1-405b-instruct|cohere-command-r*|grok-beta|grok-2-1212|grok-2*)
MODMAX=131072;;
*openchat-7b|*mythomax-l2-13b|*airoboros-l2-70b|*lzlv_70b|*nous-hermes-llama2-13b|\
*openhermes-2.5-mistral-7b|*midnight-rose-70b|\
gpt-4*|*-bison*|*-unicorn|text-davinci-002-render-sha|\
*wizardlm-2-8x22b)
MODMAX=65535;;
gemini*-pro*) MODMAX=32760;;
*turbo*|*davinci*|teknium/openhermes-2.5-mistral-7b|openchat/openchat-7b) MODMAX=4096;;
cohere-embed-v3-*) MODMAX=1000;;
*embedding-gecko*) MODMAX=3072;;
*embed*|*search*) MODMAX=2046;;
aqa) MODMAX=7168;;
*-4k*) MODMAX=4000;;
*) MODMAX=8192;;
esac
}
#novita: model names: [provider]/[model]
#groq: 3.1 models to max_tokens of 8k and 405b to 16k input tokens.
#pixtral: maximum number images per request is 8.
#https://blog.google/technology/ai/google-gemini-next-generation-model-february-2024/
#make cmpls request
function __promptf
{
if curl "$@" ${FAIL} -L "${BASE_URL}${ENDPOINTS[EPN]}" \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${MISTRAL_API_KEY:-$OPENAI_API_KEY}" \
-d "$BLOCK" $CURLTIMEOUT
then [[ \ $*\ = *\ -s\ * ]] || _clr_lineupf;
else return $?; #E#
fi
}
function _promptf
{
typeset str
json_minif;
if ((STREAM))
then set -- -s "$@" -S --no-buffer;
[[ -s $FILE ]] && mv -f -- "$FILE" "${FILE%.*}.2.${FILE##*.}"; : >"$FILE" #clear buffer asap
if ((OPTC))
then str='"text"'; ((GOOGLEAI)) ||
if ((EPN==0)) && ((OLLAMA))
then str='"response"';
elif ((EPN==6))
then str='"content"';
fi;
fi
if ((GOOGLEAI))
then __promptf "$@" | { tee -- "$FILESTREAM" "$FILE" || cat ;}
else
__promptf "$@" | { tee -- "$FILESTREAM" || cat ;} |
if ((ANTHROPICAI))
then sed -n -e 's/^[[:space:]]*//' \
-e 's/^[[:space:]]*[Dd][Aa][Tt][Aa]:[[:space:]]*//p' \
-e '/^[[:space:]]*\[[A-Za-z_][A-Za-z_]*\]/d' \
-e '/^[[:space:]]*$/d';
else sed -e 's/^[[:space:]]*//' \
-e 's/^[[:space:]]*[Dd][Aa][Tt][Aa]:[[:space:]]*//' \
-e '/^[[:space:]]*[A-Za-z_][A-Za-z_]*:/d' \
-e '/^[[:space:]]*\[[A-Za-z_][A-Za-z_]*\]/d' \
-e '/^[[:space:]]*$/d';
fi |
if ((OPTC))
then sed -e "1s/${str}:[[:space:]]*\"[[:space:]]*/${str}: \"/" | tee -- "$FILE";
else tee -- "$FILE";
fi;
fi
else
{ test_cmplsf || ((OPTV>1)) ;} && set -- -s "$@"
set -- -\# "$@" -o "$FILE"
__promptf "$@"
fi
}
function promptf
{
typeset pid ret
if ((OPTVV)) && ((!OPTII))
then block_printf || {
REPLY=${REPLY_CMD:-$REPLY} REGEN= JUMP= PSKIP=;
REPLY_CMD_DUMP= REPLY_CMD_BLOCK= SKIP_SH_HIST= WSKIP= SKIP=; #E#
return 200 ;}
fi
if ((STREAM))
then : >"$FILETXT"; RET_APRF=;
test_cmplsf || ((OPTV>1)) || printf "${BYELLOW}%s\\b${NC}" "C" >&2;
{ _promptf || exit ;} | #!#
{ prompt_printf; ret=$?; printf '%s' "${RET_APRF##0}" >"$FILETXT"; exit $ret ;}
else
test_cmplsf || ((OPTV>1)) || printf "${BYELLOW}%*s\\r${YELLOW}" "$COLUMNS" "C" >&2;
COLUMNS=$((COLUMNS-1)) _promptf || exit; #!#
printf "${NC}" >&2;
if ((OPTI))
then prompt_imgprintf
else prompt_printf
fi
fi & pid=$! PIDS+=($!) #catch <CTRL-C>
trap "trap 'exit' INT; kill -- $pid 2>/dev/null; echo >&2;" INT;
wait $pid; echo >&2;
trap 'exit' INT; RET_APRF=;
[[ -s $FILETXT ]] && { RET_APRF=$(<$FILETXT); : >"$FILETXT" ;}
if ((OPTCLIP)) || [[ ! -t 1 ]]
then typeset out; out=$(
((STREAM)) && set -- -j "$@"
prompt_pf -r "$@" "$FILE"
)
((!OPTCLIP)) || (${CLIP_CMD:-false} <<<"$out" &) #clipboard
[[ -t 1 ]] || printf '%s\n' "$out" >&2 #pipe + stderr
fi
wait $pid; #curl exit code
}
#print tokens from response
function response_tknf
{
jq -r '(.usage.prompt_tokens)//"0",
(.usage.completion_tokens)//"0",
(.usage.completion_tokens_details|(.reasoning_tokens//.audio_tokens))//"0",
(.created//empty|strflocaltime("%Y-%m-%dT%H:%M:%S%Z"))' "$@";
}
#https://community.openai.com/t/usage-stats-now-available-when-using-streaming-with-the-chat-completions-api-or-completions-api/738156
#position cursor at end of screen
function _clr_dialogf
{
printf "${NC}\\n\\n\\033[${LINES};1H" >&2;
}
function __clr_dialogf { ((DIALOG_CLR)) && _clr_dialogf ;}
#clear impending stream (tty)
function _clr_ttystf
{
typeset REPLY n;
while IFS= read -r -n 1 -t 0.002;
do ((++n)); ((n<8192)) || break;
done </dev/tty;
}
#clear n lines up as needed (assumes one `new line').
function _clr_lineupf
{
typeset chars n
chars="${1:-1}" ;((COLUMNS))||COLUMNS=80
for ((n=0;n<((chars+(COLUMNS-1))/COLUMNS);++n))
do printf '\e[A\e[K' >&2
done
}
#https://www.zsh.org/mla/workers//1999/msg01550.html
#https://superchlorine.com/2013/08/kill-winch-to-fix-bash-prompt-wrapping-to-the-same-line/
# spin.bash -- provide a `spinning wheel' to show progress
# Copyright 1997 Chester Ramey (adapted)