-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathollama_bash_lib.sh
More file actions
executable file
·2527 lines (2230 loc) · 82.3 KB
/
ollama_bash_lib.sh
File metadata and controls
executable file
·2527 lines (2230 loc) · 82.3 KB
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
#
# Ollama Bash Lib - A Bash Library to interact with Ollama
#
OBL_NAME='Ollama Bash Lib'
OBL_VERSION='0.48.0'
OBL_URL='https://github.com/attogram/ollama-bash-lib'
OBL_DISCORD='https://discord.gg/BGQJCbYVBa'
OBL_LICENSE='MIT'
OBL_COPYRIGHT='Copyright (c) 2025 Attogram Project <https://github.com/attogram>'
OBL_API="${OLLAMA_HOST:-http://localhost:11434}" # Ollama API URL, No slash at end
OBL_DEBUG="${OBL_DEBUG:-0}" # 0 = debug off, 1 = debug, 2 = verbose debug
OBL_MESSAGES=() # Array of messages, in JSON format
OBL_STREAM=0 # Streaming mode: 0 = No streaming, 1 = Yes streaming
OBL_THINKING="${OBL_THINKING:-off}" # Thinking mode: off, on, hide
OBL_TIMEOUT="${OBL_TIMEOUT:-300}" # Curl timeout in seconds
if (set -o pipefail 2>/dev/null); then # If pipefail is supported
set -o pipefail # Exit the pipeline if any command fails (instead of only the last one)
fi
# Internal Functions
# Redact private information from string
#
# Usage: _redact "string"
# Input: 1 - the string to be redacted
# Output: redacted string to stdout
# Requires: none
# return 0 on success, 1 on error
_redact() {
local msg="$1"
if [[ -n "${OBL_TURBO_KEY}" ]]; then
msg=${msg//"${OBL_TURBO_KEY}"/'[REDACTED]'} # never show the private api key
fi
printf '%s' "$msg"
}
# Debug message
#
# Usage: _debug "message"
# Input: 1 - the debug message
# Output: message to stderr
# Requires: none
# Returns: 0 on success, 1 on error
_debug() {
(( OBL_DEBUG )) || return 0 # DEBUG must be 1 or higher to show debug messages
local date_string # some date implementations do not support %N nanoseconds
date_string="$(if ! date '+%H:%M:%S:%N' 2>/dev/null; then date '+%H:%M:%S'; fi)"
printf '[DEBUG] %s: %s\n' "$date_string" "$(_redact "$1")" >&2
}
# Error message
#
# Usage: _error "message"
# Input: 1 - the error message
# Output: message to stderr
# Requires: none
# Returns: 0 on success, 1 on error
_error() {
printf '[ERROR] %s\n' "$(_redact "$1")" >&2
}
# Does a command exist?
#
# Usage: _exists "command"
# Input: 1 - the command (ollama, curl, etc)
# Output: none
# Requires: command
# Returns: 0 if command exists, non-zero if command does not exist
_exists() {
command -v "$1" >/dev/null 2>&1
return $?
}
# Is a string a valid URL?
#
# Usage: _is_valid_url "string"
# Input: 1 - the string to be tested
# Output: none
# Requires: none
# Returns: 0 if valid, 1 if not valid
_is_valid_url() {
local url_regex='^(https?)://[A-Za-z0-9.-]+(:[0-9]+)?$'
if [[ "$1" =~ $url_regex ]]; then
return 0
else
return 1
fi
}
# Is a string valid JSON?
#
# Usage: _is_valid_json "string"
# Input: 1 - the string to be tested
# Output: none
# Requires: jq
# Returns: 0 if valid, 1 or higher if not valid
_is_valid_json() {
if [[ -z "$1" ]]; then # empty string is not valid json
_debug '_is_valid_json: empty string'
return 1
fi
if ! _exists 'jq'; then _error '_is_valid_json: jq Not Found'; return 1; fi
printf '%s' "$1" | jq -e '.' >/dev/null 2>&1 # use -e for jq exit-status mode
local return_code=$?
case $return_code in
0) # Exit code 0: The JSON is valid and "truthy"
#_debug '_is_valid_json: success'
return 0
;;
1) # (Failure) The last value output was either false or null.
_error '_is_valid_json: FAILURE jq: output false or null: return 1'
return 1
;;
2) # (Usage Error): There was a problem with how the jq command was used, such as incorrect command-line options.
_error '_is_valid_json: USAGE ERROR jq: incorrect command-line options: return 2'
return 2
;;
3) # (Compile Error): The jq filter program itself had a syntax error.
_error '_is_valid_json: COMPILE ERROR jq: filter syntax error: return 3'
return 3
;;
4) # (No Output): No valid result was ever produced. This can happen if the filter's output is empty.
_error '_is_valid_json: NO OUTPUT jq: result empty: return 4'
return 4
;;
5) # (Halt Error)
_error '_is_valid_json: HALT_ERROR jq: return 5'
return 5
;;
*) # (Unknown)
_error "_is_valid_json: UNKNOWN jq error: return $return_code"
return "$return_code"
;;
esac
}
# API Functions
# Call curl
#
# Input: 1 - method (GET or POST)
# Input: 2 - endpoint (/api/path) (optional)
# Input: 3 - { json body } (optional)
# Output: curl result body to stdout
# Requires: curl
# Returns: 0 on success, 1 or higher on error
_call_curl() {
_debug "_call_curl: [${1:0:42}] [${2:0:42}] ${3:0:120}"
if ! _exists 'curl'; then _error '_call_curl: curl Not Found'; return 1; fi
local method="$1"
if [[ -z "$method" || ( "$method" != "GET" && "$method" != "POST" ) ]]; then
_error '_call_curl: Method Not Found. Usage: _call_curl "GET|POST" "/api/path" "{ optional json content }"'
return 1
fi
local endpoint="$2"
if [[ -n "$endpoint" && ( "$endpoint" != /* || "$endpoint" == *" "* || "$endpoint" == *"\\"* ) ]]; then
_error "_call_curl: Invalid API Path: [${endpoint:0:120}]"
return 1
fi
local json_body="$3"
if [[ -n "$json_body" ]] && ! _is_valid_json "$json_body"; then
_error "_call_curl: JSON body is invalid: [${json_body:0:120}]"
return 1
fi
_debug "_call_curl: OBL_API: $OBL_API"
local curl_args=(
-s
-N
--max-time "$OBL_TIMEOUT"
-H 'Content-Type: application/json'
-w 'HTTP_CODE_DELIMITER%{http_code}'
)
if [[ -n "${OBL_TURBO_KEY}" ]]; then
_debug '_call_curl: Turbo Mode'
curl_args+=( -H "Authorization: Bearer ${OBL_TURBO_KEY}" )
fi
curl_args+=( -X "$method" )
curl_args+=( "${OBL_API}${endpoint}" )
local response
local curl_exit_code
if [[ -n "$json_body" ]]; then
_debug "_call_curl: json_body: ${json_body:0:120}"
curl_args+=( -d "@-" )
_debug "_call_curl: piping json_body | curl ${curl_args[*]}"
response="$(printf '%s' "$json_body" | curl "${curl_args[@]}")"
curl_exit_code=$?
else
_debug "_call_curl: args: ${curl_args[*]}"
response="$(curl "${curl_args[@]}")"
curl_exit_code=$?
fi
if (( curl_exit_code )); then
_error "_call_curl: curl command failed with exit code $curl_exit_code"
return "$curl_exit_code"
fi
local http_code
http_code="${response##*HTTP_CODE_DELIMITER}"
local body
body="${response%HTTP_CODE_DELIMITER*}"
if (( http_code >= 400 )); then
_error "_call_curl: HTTP error ${http_code}: ${body}"
return 1
fi
printf '%s' "$body"
return 0
}
# GET request to the Ollama API
#
# Usage: ollama_api_get '/api/path'
# Input: 1 = API URL path
# Output: API call result, to stdout
# Requires: curl
# Returns: 0 on success, curl return status on error
ollama_api_get() {
local usage='Usage: ollama_api_get [-P <path>] [-h] [-v]'
local description
description=$(cat <<'EOF'
GET request to the Ollama API.
-P <path> API path to send the GET request to (optional).
-h Show this help and exit.
-v Show version information and exit.
This is a fundamental function used by many other functions in this library to communicate with the Ollama API, such as 'ollama_list_json' and 'ollama_api_ping'.
It relies on the '_call_curl' function to perform the actual HTTP request.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG api_path
while getopts ":P:hv" opt; do
case $opt in
P) api_path=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_api_get version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
_debug "ollama_api_get: [${api_path:0:42}]"
_call_curl "GET" "$api_path"
local error_curl=$?
if (( error_curl )); then
_error "ollama_api_get: curl error: $error_curl"
return "$error_curl"
fi
_debug 'ollama_api_get: success'
return 0
}
# POST request to the Ollama API
#
# Usage: ollama_api_post '/api/path' "{ json content }"
# Input: 1 - API URL path
# Input: 2 - JSON content
# Output: API call result, to stdout
# Requires: curl
# Returns: 0 on success, curl return status on error
ollama_api_post() {
local usage='Usage: ollama_api_post -P <path> -d <data> [-h] [-v]'
local description
description=$(cat <<'EOF'
POST request to the Ollama API.
-P <path> API path to send the POST request to.
-d <data> JSON content to send in the request body.
-h Show this help and exit.
-v Show version information and exit.
This is a core function for sending data to the Ollama API, used by functions like 'ollama_generate_json', 'ollama_chat_json', and 'ollama_show_json'.
It relies on the '_call_curl' function to perform the actual HTTP request.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG api_path json_content
while getopts ":P:d:hv" opt; do
case $opt in
P) api_path=$OPTARG ;;
d) json_content=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_api_post version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [[ -z "$api_path" || -z "$json_content" ]]; then
printf 'Error: Missing required arguments\n\n' >&2
printf '%s\n' "$usage" >&2
return 2
fi
_debug "ollama_api_post: [${api_path:0:42}] ${json_content:0:120}"
_call_curl "POST" "$api_path" "$json_content"
local error_curl=$?
if (( error_curl )); then
_error "ollama_api_post: curl error: $error_curl"
return "$error_curl"
fi
_debug 'ollama_api_post: success'
return 0
}
# Ping the Ollama API
#
# Usage: ollama_api_ping
# Input: none
# Output: none
# Requires: curl
# Returns: 0 if API is reachable, 1 if API is not reachable
ollama_api_ping() {
local usage='Usage: ollama_api_ping [-h] [-v]'
local description
description=$(cat <<'EOF'
Ping the Ollama API to check for availability.
-h Show this help and exit.
-v Show version information and exit.
This function sends a request to the root of the Ollama API to verify that it is running and accessible.
It is useful for health checks and ensuring connectivity before attempting to use other API functions.
This function relies on 'ollama_api_get' to make the request.
EOF
)
OPTIND=1 # start parsing at $1 again
while getopts ":hv" opt; do
case $opt in
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_api_ping version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [[ $# -gt 0 ]]; then
_error "ollama_api_ping: Unknown argument(s): $*"
printf '%s\n' "$usage" >&2
return 1
fi
_debug 'ollama_api_ping'
if [[ -n "${OBL_TURBO_KEY}" ]]; then
# TODO - support for turbo mode pings
_debug 'ollama_api_ping: function not available in Turbo Mode'
return 0 # we return success for now, to keep outputs clean of other errors
fi
local result
if ! result="$(ollama_api_get -P "")"; then
_debug 'ollama_api_ping: ollama_api_get failed'
return 1
fi
if [[ "$result" == 'Ollama is running' ]]; then # Valid as of Ollama 0.11
return 0
fi
_debug "ollama_api_ping: unknown result: [${result:0:42}]"
return 1
}
# Generate Functions
# Create a JSON payload for the generate endpoint
#
# Usage: _ollama_generate_json_payload "model" "prompt"
# Input: 1 - The model to use
# Input: 2 - The prompt
# Output: json payload to stdout
# Requires: jq
# Returns: 0 on success, 1 on error
_ollama_generate_json_payload() {
local model="$1"
local prompt="$2"
local stream=true
(( OBL_STREAM == 0 )) && stream=false
local thinking=false
[[ "$OBL_THINKING" == 'on' || "$OBL_THINKING" == 'hide' ]] && thinking=true
local payload
payload="$(jq -c -n \
--arg model "$model" \
--arg prompt "$prompt" \
--argjson stream "$stream" \
--argjson thinking "$thinking" \
'{model: $model, prompt: $prompt, stream: $stream, thinking: $thinking}')"
printf '%s' "$payload"
}
# Generate a completion as json
#
# Usage: ollama_generate_json "model" "prompt"
# Input: 1 - The model to use to generate a response
# Input: 2 - The prompt
# Output: json (or a stream of json objects) on stdout
# Requires: curl, jq
# Returns: 0 on success, 1 on error
ollama_generate_json() {
local usage='Usage: ollama_generate_json -m <model> [-p <prompt>] [-h] [-v]'
local description
description=$(cat <<'EOF'
Generate a completion from a model as JSON.
-m <model> Name of the model to use (required).
-p <prompt> Prompt text. If omitted, the function reads from STDIN.
-h Show this help and exit.
-v Show version information and exit.
This function sends a prompt to a specified model and returns the model's response as a raw JSON object.
If streaming is enabled via the global 'OBL_STREAM' variable, it will return a stream of JSON objects.
This is a foundational function for 'ollama_generate' and 'ollama_generate_stream', which process this JSON output into plain text.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG model prompt
while getopts ":m:p:hv" opt; do
case $opt in
m) model=$OPTARG ;;
p) prompt=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_generate_json version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if ! _exists 'jq'; then _error 'ollama_generate_json: Not Found: jq'; return 1; fi
if [ -z "$model" ]; then
model="$(_is_valid_model "")"
if [ -z "$model" ]; then
printf 'Error: -m <model> is required\n\n' >&2
printf '%s\n' "$usage" >&2
return 2
fi
fi
if [ -z "$prompt" ] && [ ! -t 0 ]; then
prompt=$(cat -)
fi
if [ -z "$prompt" ]; then
_error 'ollama_generate_json: Not Found: prompt.'
printf '%s\n' "$usage" >&2
return 1
fi
_debug "ollama_generate_json: [${model:0:42}] [${prompt:0:42}]"
local json_payload
json_payload="$(_ollama_generate_json_payload "$model" "$prompt")"
_debug "ollama_generate_json: json_payload: ${json_payload:0:120}"
if ! ollama_api_post -P '/api/generate' -d "$json_payload"; then
_error 'ollama_generate_json: ollama_api_post failed'
return 1
fi
_debug 'ollama_generate_json: success'
return 0
}
# Generate a completion as text
#
# Usage: ollama_generate "model" "prompt"
# Input: 1 - The model to use to generate a response
# Input: 2 - The prompt
# Output: text, to stdout
# Requires: curl, jq
# Returns: 0 on success, 1 on error
ollama_generate() {
_debug "ollama_generate: [${1:0:42}] [${2:0:42}] [${3:0:42}] [${4:0:42}]"
local usage='Usage: ollama_generate -m <model> [-p <prompt>] [-h] [-v]'
#_debug "ollama_generate: usage: $usage"
local description
description=$(cat <<'EOF'
Generate a completion from a model as plain text.
-m <model> Name of the model to use (required).
-p <prompt> Prompt text. If omitted, the function reads from STDIN.
-h Show this help and exit.
-v Show version information and exit.
This function is a wrapper around 'ollama_generate_json'. It takes the raw JSON output and extracts the 'response' field, returning it as a single string.
This is useful for when you only need the generated text and don't want to parse the JSON yourself.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG model prompt
_debug "ollama_generate: init: model: [${model:0:120}] prompt: [${prompt:0:120}]"
while getopts ":m:p:hv" opt; do
_debug "ollama_generate: while getopts: OPTARG: [$OPTARG] opt: [$opt]"
case $opt in
m) model=$OPTARG ;;
p) prompt=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_generate version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [ -z "$prompt" ] && [ ! -t 0 ]; then
prompt=$(cat -)
fi
_debug "ollama_generate: final: model: [${model:0:120}] prompt: [${prompt:0:120}]"
if ! _exists 'jq'; then _error 'ollama_generate: jq Not Found'; return 1; fi
_debug "ollama_generate: checking: model: [${model:0:120}]"
if [ -z "$model" ]; then
model="$(ollama_model_random)"
if [ -z "$model" ]; then
printf 'Error: -m <model> is required\n\n' >&2
printf '%s\n' "$usage" >&2
return 2
fi
fi
_debug "ollama_generate: checked: model: [${model:0:120}]"
if [ -z "$prompt" ]; then
_error 'ollama_generate: Not Found: prompt.'
printf '%s\n' "$usage" >&2
return 1
fi
OBL_STREAM=0 # Turn off streaming
local result
result="$(ollama_generate_json -m "$model" -p "$prompt")"
local error_ollama_generate_json=$?
_debug "ollama_generate: result: $(echo "$result" | wc -c | tr -d ' ') bytes: ${result:0:120}"
if (( error_ollama_generate_json )); then
_error "ollama_generate: error_ollama_generate_json: $error_ollama_generate_json"
return 1
fi
if ! _is_valid_json "$result"; then
_error 'ollama_generate: model response is not valid JSON'
return 1
fi
if error_msg=$(printf '%s' "$result" | jq -r '.error // empty'); then
if [[ -n $error_msg ]]; then
_error "ollama_generate: $error_msg"
return 1
fi
fi
_debug "ollama_generate: thinking: $OBL_THINKING"
if [[ "$OBL_THINKING" != 'hide' ]]; then
local thinking
thinking="$(printf '%s' "$result" | jq -r '.thinking // empty')"
if [[ -n "$thinking" ]]; then
_debug 'ollama_generate: thinking FOUND'
printf '#### <thinking>\n#### %s\n#### </thinking>\n\n' "$thinking" >&2 # send thinking to stderr
fi
fi
local result_response
result_response="$(printf '%s' "$result" | jq -r '.response')"
if [[ -z "$result_response" ]]; then
_error 'ollama_generate: jq failed to get .response'
return 1
fi
printf '%s\n' "$result_response"
_debug 'ollama_generate: success'
return 0
}
# Generate a completion, as streaming json
#
# Input: 1 - The model to use to generate a response
# Input: 2 - The prompt
# Usage: ollama_generate_stream_json "model" "prompt"
# Output: json, to stdout
# Requires: curl, jq
# Returns: 0 on success, 1 on error
ollama_generate_stream_json() {
local usage='Usage: ollama_generate_stream_json -m <model> [-p <prompt>] [-h] [-v]'
local description
description=$(cat <<'EOF'
Generate a completion from a model as a stream of JSON objects.
-m <model> Name of the model to use (required).
-p <prompt> Prompt text. If omitted, the function reads from STDIN.
-h Show this help and exit.
-v Show version information and exit.
This function sets the global 'OBL_STREAM' variable to 1 and then calls 'ollama_generate_json'.
It is the basis for 'ollama_generate_stream', which further processes the output into a continuous stream of text.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG model prompt
while getopts ":m:p:hv" opt; do
case $opt in
m) model=$OPTARG ;;
p) prompt=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_generate_stream_json version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [ -z "$model" ]; then
model="$(_is_valid_model "")"
if [ -z "$model" ]; then
printf 'Error: -m <model> is required\n\n' >&2
printf '%s\n' "$usage" >&2
return 2
fi
fi
if [ -z "$prompt" ] && [ ! -t 0 ]; then
prompt=$(cat -)
fi
if [ -z "$prompt" ]; then
_error 'ollama_generate_stream_json: Not Found: prompt.'
printf '%s\n' "$usage" >&2
return 1
fi
_debug "ollama_generate_stream_json: [${model:0:42}] [${prompt:0:42}]"
OBL_STREAM=1 # Turn on streaming
if ! ollama_generate_json -m "$model" -p "$prompt"; then
_error "ollama_generate_stream_json: ollama_generate_json failed"
OBL_STREAM=0 # Turn off streaming
return 1
fi
OBL_STREAM=0 # Turn off streaming
_debug 'ollama_generate_stream_json: success'
return 0
}
# Wraps a stream of text with <thinking> tags
#
# Usage: <stream> | _ollama_thinking_stream
# Input: stream of text from stdin
# Output: wrapped text to stderr
# Requires: none
# Returns: 0
_ollama_thinking_stream() {
local chunk
if read -r -n 1 chunk && [[ -n "$chunk" ]]; then
printf '#### <thinking>\n' >&2
printf '#### %s' "$chunk" >&2
cat >&2
printf '\n#### </thinking>\n\n' >&2
fi
}
# Generate a completion as streaming text
#
# Usage: ollama_generate_stream -m <model> [-p <prompt>] [-h] [-v]
# Input: 1 - The model to use to generate a response
# Input: 2 - The prompt
# Output: text, to stdout
# Requires: curl, jq
# Returns: 0 on success, 1 on error
ollama_generate_stream() {
local usage='Usage: ollama_generate_stream -m <model> [-p <prompt>] [-h] [-v]'
local description='Generate a completion from a model as a stream of text.
-m <model> Name of the model to use (required).
-p <prompt> Prompt text. If omitted, the function reads from STDIN.
-h Show this help and exit.
-v Show version information and exit.
This function calls ollama_generate_stream_json and pipes the output to jq to extract the response field from each JSON object, providing a continuous stream of text.
It is ideal for displaying real-time generation in interactive scripts.'
OPTIND=1
local opt OPTARG model prompt
while getopts ":m:p:hv" opt; do
case $opt in
m) model=$OPTARG ;;
p) prompt=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_generate_stream version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if ! _exists 'jq'; then
_error 'ollama_generate_stream: jq Not Found'
return 1
fi
if [ -z "$model" ]; then
model="$(ollama_model_random)" || return 1
fi
if [ -z "$prompt" ]; then
[[ -t 0 ]] || prompt=$(cat -)
fi
if [ -z "$prompt" ]; then
_error 'ollama_generate_stream: No prompt supplied'
printf '%s\n' "$usage" >&2
return 1
fi
_debug "ollama_generate_stream: model='$model' prompt='${prompt:0:40}'"
OBL_STREAM=1
local is_thinking=false
local is_responding=false
ollama_generate_json -m "$model" -p "$prompt" |
while IFS= read -r line; do
#_debug "ollama_generate_stream: line: [${line:0:1000}]"
thinking="$(jq '.thinking // empty' <<<"$line")"
thinking=${thinking#\"} # strip first "
thinking=${thinking%\"} # strip last "
if [[ -n "$thinking" ]]; then
if [[ "$is_thinking" == 'false' ]]; then
# first thinking input received
is_thinking=true
printf '\n#### %b' "$thinking"
else
# subsequent thinking input received
printf '%b' "$thinking"
fi
fi
response="$(jq '.response // empty' <<<"$line")"
response=${response#\"} # strip first "
response=${response%\"} # strip last "
if [[ -n "$response" ]]; then
printf '%b' "$response"
fi
done
rc=$? # exit status of the whole pipeline
OBL_STREAM=0
# Final newline (only on success)
(( rc == 0 )) && printf '\n'
_debug "ollama_generate_stream: exit=$rc"
return $rc
}
# Messages Functions
# Get all messages
#
# Usage: messages="$(ollama_messages)"
# Output: a valid json array of message objects, to stdout
# Env: OBL_MESSAGES
# Requires: none
# Returns: 0 on success, 1 on error
ollama_messages() {
local usage='Usage: ollama_messages [-h] [-v]'
local description
description=$(cat <<'EOF'
Get all messages in the current session.
-h Show this help and exit.
-v Show version information and exit.
This function returns a JSON array of all messages that have been added to the current session via 'ollama_messages_add'.
The output of this function is suitable for use in the 'messages' field of a chat completion request.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG
while getopts ":hv" opt; do
case $opt in
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_messages version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [[ $# -gt 0 ]]; then
_error "ollama_messages: Unknown argument(s): $*"
printf '%s\n' "$usage" >&2
return 1
fi
if [[ ${#OBL_MESSAGES[@]} -eq 0 ]]; then
_debug 'ollama_messages: no messages'
printf '[]'
return 1
fi
printf '[%s]' "$(printf '%s,' "${OBL_MESSAGES[@]}" | sed 's/,$//')"
return 0
}
# Add a message
#
# Usage: ollama_messages_add -r <role> -c <content>
# Input: 1 - role (user/assistant/system)
# Input: 2 - the message content
# Output: none
# Env: OBL_MESSAGES
# Requires: jq
# Returns: 0
ollama_messages_add() {
local usage='Usage: ollama_messages_add -r <role> -c <content> [-h] [-v]'
local description
description=$(cat <<'EOF'
Add a message to the current session's message history.
-r <role> The role of the message sender (user, assistant, system).
-c <content> The content of the message.
-h Show this help and exit.
-v Show version information and exit.
This function appends a new message object to the \'OBL_MESSAGES\' array.
This history is then used by \'ollama_chat\' and related functions to maintain a conversation with the model.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG role content
while getopts ":r:c:hv" opt; do
case $opt in
r) role=$OPTARG ;;
c) content=$OPTARG ;;
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_messages_add version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
:) printf 'Error: -%s requires an argument\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if ! _exists 'jq'; then _error 'ollama_messages_add: jq Not Found'; return 1; fi
if [ -z "$role" ] || [ -z "$content" ]; then
printf 'Error: Missing required arguments\n\n' >&2
printf '%s\n' "$usage" >&2
return 2
fi
_debug "ollama_messages_add: [${role:0:42}] [${content:0:42}]"
local json_payload
json_payload="$(jq -c -n \
--arg role "$role" \
--arg content "$content" \
'{role: $role, content: $content}')"
OBL_MESSAGES+=("$json_payload")
}
# Clear all messages
#
# Usage: ollama_messages_clear
# Output: none
# Env: OBL_MESSAGES
# Requires: none
# Returns: 0
ollama_messages_clear() {
local usage='Usage: ollama_messages_clear [-h] [-v]'
local description
description=$(cat <<'EOF'
Clear all messages from the current session.
-h Show this help and exit.
-v Show version information and exit.
This function resets the \'OBL_MESSAGES\' array, effectively deleting the entire conversation history for the current session.
This is useful for starting a new conversation without restarting the script.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG
while getopts ":hv" opt; do
case $opt in
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_messages_clear version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [[ $# -gt 0 ]]; then
_error "ollama_messages_clear: Unknown argument(s): $*"
printf '%s\n' "$usage" >&2
return 1
fi
_debug 'ollama_messages_clear'
OBL_MESSAGES=()
}
# Messages count
#
# Usage: ollama_messages_count
# Output: number of messages, to stdout
# Env: OBL_MESSAGES
# Requires: none
# Returns: 0
ollama_messages_count() {
local usage='Usage: ollama_messages_count [-h] [-v]'
local description
description=$(cat <<'EOF'
Get the number of messages in the current session.
-h Show this help and exit.
-v Show version information and exit.
This function returns the current number of messages stored in the 'OBL_MESSAGES' array.
It can be used to check if a conversation has started or to monitor the length of the conversation history.
EOF
)
OPTIND=1 # start parsing at $1 again
local opt OPTARG
while getopts ":hv" opt; do
case $opt in
h) printf '%s\n\n%s\n' "$usage" "$description"; return 0 ;;
v) printf 'ollama_messages_count version %s\n' "$OBL_VERSION"; return 0 ;;
\?) printf 'Error: unknown option -%s\n\n' "$OPTARG" >&2
printf '%s\n' "$usage" >&2; return 2 ;;
esac
done
shift $((OPTIND-1))
if [[ $# -gt 0 ]]; then
_error "ollama_messages_count: Unknown argument(s): $*"
printf '%s\n' "$usage" >&2
return 1
fi
echo "${#OBL_MESSAGES[@]}"
}
# Get Last Message, JSON format
#
# Usage: ollama_messages_last_json [-h] [-v]
# Output: last element of message history, in JSON format
# Env: OBL_MESSAGES
# Requires: none
# Returns 0 on success, 1 on error
ollama_messages_last_json() {
local usage='Usage: ollama_messages_last_json [-h] [-v]'