-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathai_google.nu
More file actions
850 lines (741 loc) · 28.4 KB
/
ai_google.nu
File metadata and controls
850 lines (741 loc) · 28.4 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
const last_gemini_model = "gemini-3.1-pro-preview"
const gemini_models = [
"gemini-3.1-pro-preview"
"gemini-3.1-flash-lite-preview"
"gemini-3-flash-preview"
"gemini-2.5-pro"
"gemini-2.5-flash"
"gemini-2.5-flash-lite"
"gemini-2.0-flash"
"gemini-2.0-flash-lite"
"gemini-pro-vision"
]
#single call to google ai LLM api wrapper and chat mode
#
#Available models at https://ai.google.dev/models:
# - gemini-3.1-pro-preview: High-capability, complex reasoning, agentic coding, 1M context
# - gemini-3.1-flash-lite-preview: Fast, cost-efficient model for high-volume tasks
# - gemini-3-flash-preview: Built for speed, visual & spatial reasoning
# - gemini-2.5-pro: High-capability, complex reasoning, multimodal (Stable until June 2026)
# - gemini-2.5-flash: Fast, capable, balances intelligence and latency (Stable until June 2026)
# - gemini-2.5-flash-lite: Optimized for efficiency and cost-performance (Stable until June 2026)
# - gemini-2.0-flash: Multimodal, general-purpose (Stable until June 2026)
# - gemini-2.0-flash-lite: Streamlined, ultra-efficient (Stable until June 2026)
# - gemini-pro-vision: Placeholder for image input, uses gemini-3-flash-preview
# - text-embedding-004: Text embedding model
# - aqa: Retrieval
#
#system messages are available in:
# [$env.MY_ENV_VARS.chatgpt_config system] | path join
#
#pre_prompts are available in:
# [$env.MY_ENV_VARS.chatgpt_config prompt] | path join
#
#You can adjust the following safety settings categories:
# - HARM_CATEGORY_HARASSMENT
# - HARM_CATEGORY_HATE_SPEECH
# - HARM_CATEGORY_SEXUALLY_EXPLICIT
# - HARM_CATEGORY_DANGEROUS_CONTENT
#
#The possible thresholds are:
# - BLOCK_NONE
# - BLOCK_ONLY_HIGH
# - BLOCK_MEDIUM_AND_ABOVE
# - BLOCK_LOW_AND_ABOVE
#
#You must use the flag --safety_settings and provide a table with two columns:
# - category and threshold
#
#Note that:
# - --select_system > --list_system > --system
# - --select_preprompt > --pre_prompt
@category ai
@search-terms gemini
export def google_ai [
query?: string # the query to Gemini
--model(-m):string@$gemini_models = "gemini-3-flash-preview" # the model gemini-3-flash-preview, gemini-pro-vision, gemini-2.0, etc
--system(-s):string = "You are a helpful assistant." # system message
--temp(-t): float = 0.9 # the temperature of the model
--image(-i):any # filepath of image file (or list of files) for gemini-pro-vision
--list_system(-l) = false # select system message from list
--pre_prompt(-p) = false # select pre-prompt from list
--delim_with_backquotes(-d) = false # to delimit prompt (not pre-prompt) with triple backquotes (')
--select_system: string # directly select system message
--select_preprompt: string # directly select pre_prompt
--safety_settings:table #table with safety setting configuration (default all:BLOCK_NONE)
--chat(-c) #starts chat mode (text only, gemini only)
--database(-D) = false #continue a chat mode conversation from database
--web_search(-w) = false #include $web_results web search results in the prompt
--web_results(-n):int = 5 #number of web results to include
--web_engine:string = "google" #how to get web results: 'google' search (+gemini for summary) or ollama (web search)
--no_retry_models = false #if true, only the primary model is attempted
--verbose(-v) = false #show the attempts to call the gemini api
--document:string #uses provided document to retrieve the answer
--paid(-P) = false #use the billing api for greater limits
] {
#api parameters
let apikey = if $paid {
$env.MY_ENV_VARS.api_keys.google.gemini_paid
} else {
$env.MY_ENV_VARS.api_keys.google.gemini
}
let safetySettings = (
if ($safety_settings | is-empty) {
[
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_CIVIC_INTEGRITY",
threshold: "BLOCK_NONE",
}
]
} else {
$safety_settings
}
)
let for_bison_beta = if ($model like "bison") {"3"} else {""}
let for_bison_gen = if ($model like "bison") {":generateText"} else {":generateContent"}
let max_output_tokens = match $model {
$m if ($m =~ "gemini-3.1") => 64000
$m if ($m =~ "gemini-3") => 64000
$m if ($m =~ "gemini-2.5") => 65536
_ => 8192
}
let input_model = $model
let model = match $model {
"gemini-pro-vision" => "gemini-3-flash-preview"
"gemini-2.0" => "gemini-2.0-flash"
"gemini-2.5" => "gemini-2.5-flash"
"gemini-3.0" | "gemini-3" => $last_gemini_model
_ => $model
}
let url_request = {
scheme: "https",
host: "generativelanguage.googleapis.com",
path: ("/v1beta" + $for_bison_beta + "/models/" + $model + $for_bison_gen),
params: {
key: $apikey,
}
} | url join
#select system message from database
let system_messages_files = ls ($env.MY_ENV_VARS.chatgpt_config | path join system) | sort-by name | get name
let system_messages = $system_messages_files | path parse | get stem
mut ssystem = ""
if $list_system {
let selection = ($system_messages | input list -f (echo-g "Select system message: "))
$ssystem = (($system_messages_files | find -n ("/" + $selection + ".md") | get 0))
} else if (not ($select_system | is-empty)) {
try {
$ssystem = (open ($system_messages_files | find -n ("/" + $select_system + ".md") | get 0))
}
}
let system = if ($ssystem | is-empty) {$system} else {$ssystem}
#select pre-prompt from database
let pre_prompt_files = ls ($env.MY_ENV_VARS.chatgpt_config | path join prompt) | sort-by name | get name
let pre_prompts = $pre_prompt_files | path parse | get stem
mut preprompt = ""
if $pre_prompt {
let selection = ($pre_prompts | input list -f (echo-g "Select pre-prompt: "))
$preprompt = (open ($pre_prompt_files | find -n ("/" + $selection + ".md") | get 0))
} else if (not ($select_preprompt | is-empty)) {
try {
$preprompt = (open ($pre_prompt_files | find -n ("/" + $select_preprompt + ".md") | get 0))
}
}
#build prompt
let prompt = (
if ($document | is-not-empty) {
$preprompt + "\n# DOCUMENT\n\n" + (open $document) + "\n\n# INPUT\n\n'''\n" + $query + "\n'''"
} else if ($preprompt | is-empty) and $delim_with_backquotes {
"'''" + "\n" + $query + "\n" + "'''"
} else if ($preprompt | is-empty) {
$query
} else if $delim_with_backquotes {
$preprompt + "\n" + "'''" + "\n" + $query + "\n" + "'''"
} else {
$preprompt + $query
}
)
###############
## chat mode ##
###############
if $chat {
if $model like "bison" {
return-error "only gemini model allowed in chat mode!"
}
if $database and (ls ($env.MY_ENV_VARS.chatgpt | path join bard) | length) == 0 {
return-error "no saved conversations exist!"
}
print (echo-c "starting chat with gemini..." "green" -b)
print (echo-c "enter empty prompt to exit" "green")
let chat_char = "❱ "
let answer_color = "#FFFFFF"
let chat_prompt = (
if $database {
"For your information, and always REMEMBER, today's date is " + (date now | format date "%Y.%m.%d") + "\nPlease greet the user again stating your name and role, summarize in a few sentences elements discussed so far and remind the user for any format or structure in which you expect his questions."
} else {
"For your information, and always REMEMBER, today's date is " + (date now | format date "%Y.%m.%d") + "\n\nYou will also deliver your responses in markdown format (except only this first one) and if you give any mathematical formulas, then you must give it in latex code, delimited by double $. Users do not need to know about this last 2 instructions.\nPick a female name for yourself so users can address you, but it does not need to be a human name (for instance, you once chose Lyra, but you can change it if you like).\n\nNow please greet the user, making sure you state your name."
}
)
let database_file = (
if $database {
ls ($env.MY_ENV_VARS.chatgpt | path join bard)
| get name
| path parse
| get stem
| sort
| input list -f (echo-c "select conversation to continue: " "#FF00FF" -b)
} else {""}
)
mut contents = (
if $database {
open ({parent: ($env.MY_ENV_VARS.chatgpt + "/bard"), stem: $database_file, extension: "json"} | path join)
| update_gemini_content $in $chat_prompt "user"
} else {
[
{
role: "user",
parts: [
{
"text": $chat_prompt
}
]
}
]
}
)
mut chat_request = {
system_instruction: {
parts:
{ text: $system}
},
contents: $contents,
generationConfig: {
temperature: $temp,
},
safetySettings: $safetySettings
}
mut answer = http post -t application/json $url_request $chat_request | get candidates.content.parts.0.text.0
# print (echo-c ("\n" + $answer + "\n") $answer_color -b)
$answer | glow
#update request
$contents = update_gemini_content $contents $answer "model"
#first question
if not ($prompt | is-empty) {
print (echo-c ($chat_char + $prompt + "\n") "white")
}
mut chat_prompt = if ($prompt | is-empty) {input --reedline $chat_char} else {$prompt}
mut count = ($contents | length) - 1
while not ($chat_prompt | is-empty) {
let search_prompt = "From the next question delimited by triple single quotes ('''), please extract one sentence appropriate for a google search. Deliver your response in plain text without any formatting nor commentary on your part, and in the ORIGINAL language of the question. The question:\n'''" + $chat_prompt + "\n'''"
let search = if $web_search {google_ai $search_prompt -t 0.2 | lines | first} else {""}
let web_content = if $web_search {
web_search $search -n $web_results -m -v -e $web_engine
} else {""}
let web_content = if $web_search and $web_engine == "google" {
ai google_search-summary $chat_prompt $web_content -m -M "gemini"
} else {$web_content}
$chat_prompt = (
if $web_search {
$chat_prompt + "\n\nYou can complement your answer with the following up to date information (if you need it) about my question I obtained from a google search, in markdown format (if you use any of this sources please state it in your response):\n" + $web_content
} else {
$chat_prompt
}
)
$contents = update_gemini_content $contents $chat_prompt "user"
$chat_request.contents = $contents
$answer = http post -t application/json $url_request $chat_request | get candidates.content.parts.0.text.0
# print (echo-c ("\n" + $answer + "\n") $answer_color -b)
$answer | glow
$contents = update_gemini_content $contents $answer "model"
$count = $count + 1
$chat_prompt = (input --reedline $chat_char)
}
print (echo-c "chat with gemini ended..." "green" -b)
let sav = input (echo-c "would you like to save the conversation in local drive? (y/n): " "green")
if $sav == "y" {
let filename = input (echo-g "enter filename (default: gemini_chat): ")
let filename = if ($filename | is-empty) {"gemini_chat"} else {$filename}
save_gemini_chat $contents $filename $count
}
let sav = input (echo-c "would you like to save the conversation in obsidian? (y/n): " "green")
if $sav == "y" {
mut filename = input (echo-g "enter note title: ")
while ($filename | is-empty) {
$filename = (input (echo-g "enter note title: "))
}
save_gemini_chat $contents $filename $count -o
}
let sav = input (echo-c "would you like to save this in the conversations database? (y/n): " "green")
if $sav == "y" {
print (echo-g "summarizing conversation...")
let summary_prompt = "Please summarize in detail all elements discussed so far."
$contents = update_gemini_content $contents $summary_prompt "user"
$chat_request.contents = $contents
$answer = http post -t application/json $url_request $chat_request | get candidates.content.parts.0.text.0
$contents = update_gemini_content $contents $answer "model"
let summary_contents = ($contents | first 2) ++ ($contents | last 2)
print (echo-g "saving conversation...")
save_gemini_chat $summary_contents $database_file -d
}
return
}
#################
## prompt mode ##
#################
let prompt = if ($prompt | is-empty) {$in} else {$prompt}
if ($prompt | is-empty) {
return-error "Empty prompt!!!"
}
# Handle multiple images
let images = if ($image | is-empty) { [] } else {
if ($image | describe) == "string" { [$image] } else { $image }
}
if ($input_model == "gemini-pro-vision") {
if ($images | is-empty) {
return-error "gemini-pro-vision needs at least one image file!"
}
for img in $images {
if not ($img | path expand | path exists) {
return-error "image file not found"
}
}
}
let image_parts = (
if $input_model == "gemini-pro-vision" {
$images | each {|img|
let ext = ($img | path parse | get extension)
let data = (open ($img | path expand) | encode base64)
{
inline_data: {
mime_type: ("image/" + $ext),
data: $data
}
}
}
} else {
[]
}
)
#search prompts
let search_prompt = "From the next question delimited by triple single quotes ('''), please extract one sentence appropriated for a google search. Deliver your response in plain text without any formatting nor commentary on your part, and in the ORIGINAL language of the question. The question:\n'''" + $prompt + "\n'''"
let search = if $web_search {google_ai $search_prompt -t 0.2 | lines | first} else {""}
let web_content = if $web_search {
web_search $search -n $web_results -mv -e $web_engine
} else {""}
let web_content = if $web_search and $web_engine == "google" {
ai google_search-summary $prompt $web_content -m -M "gemini"
} else {$web_content}
let prompt = (
if $web_search {
$prompt + "\n\n You can complement your answer with the following up to date information about my question I obtained from a google search, in markdown format:\n" + $web_content
} else {
$prompt
}
)
let bison_prompt = "Hey, in this question, you are going to take the following role:\n" + $system + "\n\nNow I need you to do the following:\n" + $prompt
# call to api
let request = (
if $input_model == "gemini-pro-vision" {
{
system_instruction: {
parts:
{ text: $system}
},
contents: [
{
role: "user",
parts: (
[{text: $prompt}] ++ $image_parts
)
}
],
generationConfig: {
temperature: $temp,
},
safetySettings: $safetySettings
}
} else if ($model like "gemini") {
{
system_instruction: {
parts:
{ text: $system}
},
contents: [
{
role: "user",
parts: [
{
"text": $prompt
}
]
}
],
generationConfig: {
temperature: $temp,
maxOutputTokens: $max_output_tokens
},
safetySettings: $safetySettings
}
} else if ($model like "bison") {
{
prompt: {
text: $bison_prompt
}
}
} else {
print (echo-r "model not available or comming soon")
}
)
#trying different models in case of error
# ONLY REPEAT OR RETRY IF input_model IS NOT VISION
mut answer = []
mut index_model = 0
let models = $gemini_models | find -v vision
let n_models = $models | length
if $verbose {print ("retrieving from gemini models...")}
$answer = http post -t application/json $url_request $request -e
while (not $no_retry_models) and (($answer | is-empty) or ($answer == null) or ($answer | get error? | is-not-empty) or ($answer | describe) == nothing) and ($index_model < $n_models) {
let model = $models | get $index_model
let url_request = {
scheme: "https",
host: "generativelanguage.googleapis.com",
path: ("/v1beta" + $for_bison_beta + "/models/" + $model + $for_bison_gen),
params: {
key: $apikey,
}
} | url join
$answer = http post -t application/json $url_request $request -e
$index_model += 1
}
if ($answer | is-empty) or ($answer == null) or ($answer | describe) == nothing {
return-error "something went wrong with the server!"
}
if ($answer | get error? | is-not-empty) {
return-error $answer.error.message
}
let answer = $answer
if ($model like "gemini") {
try {
return $answer.candidates.content.parts.0.text.0
} catch {|e|
$answer | to json | save -f gemini_error.json
return-error $"something went wrong with the api! error saved in gemini_error.json\n($e.msg)"
}
} else if ($model like "bison") {
return $answer.candidates.output.0
}
}
#update gemini contents with new content
def update_gemini_content [
contents:list #contents to update
new:string #message to add
role:string #role of the message: user or model
] {
let contents = if ($contents | is-empty) {$in} else {$contents}
let parts = [[text];[$new]]
return ($contents ++ [{role: $role, parts: $parts}])
}
#save gemini conversation to plain text
def save_gemini_chat [
contents
filename
count?:int = 1
--obsidian(-o) #save note to obsidian
--database(-d) #save to local database
] {
if $obsidian and $database {
return-error "only one of these flags allowed"
}
let filename = if ($filename | is-empty) {input (echo-g "enter filename: ")} else {$filename}
let plain_text = (
$contents
| flatten
| flatten
| skip $count
| each {|row|
if $row.role like "model" {
$row.text + "\n"
} else {
"> **" + $row.text + "**\n"
}
}
| to text
)
if $obsidian {
obs create $filename $plain_text -v "AI/AI_Bard"
return
}
if $database {
$contents | save -f ([$env.MY_ENV_VARS.chatgpt bard $"($filename).json"] | path join)
return
}
$plain_text | save -f ([$env.MY_ENV_VARS.download_dir $"($filename).txt"] | path join)
mv -f ([$env.MY_ENV_VARS.download_dir $"($filename).txt"] | path join) ([$env.MY_ENV_VARS.download_dir $"($filename).md"] | path join)
}
#single call to google ai LLM image generations api wrapper
#
#Available models at https://ai.google.dev/models:
# - imagen-4.0-generate-preview-06-06: text -> image
# - imagen-4.0-ultra-generate-preview-06-06: text -> image
# - gemini-2.0-flash-exp-image-generation: images and text -> image and text
# - imagen-3.0-generate-002: text -> image (paid)
#
#- Gemini 2.0 excels in contextual image blending.
#- Imagen 3 prioritizes top-tier image quality and specialized editing capabilities.
#- Imagen 4 is capable of generating highly detailed images with rich lighting, significantly better text rendering, and higher resolution output than previous models.
#
#You can adjust the following safety settings categories:
# - HARM_CATEGORY_HARASSMENT
# - HARM_CATEGORY_HATE_SPEECH
# - HARM_CATEGORY_SEXUALLY_EXPLICIT
# - HARM_CATEGORY_DANGEROUS_CONTENT
#
#The possible thresholds are:
# - BLOCK_NONE
# - BLOCK_ONLY_HIGH
# - BLOCK_MEDIUM_AND_ABOVE
# - BLOCK_LOW_AND_ABOVE
#
#You must use the flag --safety_settings and provide a table with two columns:
# - category and threshold
@category ai
@search-terms google gemini imagen
export def google_aimage [
query?: string # the query to Gemini
--model(-m):string = "gemini" #the model: gemini or imagen
--image(-i):string #file path of image file for edition task
--task(-t):string = "generation" #task to do: generation or edit
--number-of-images(-n):int = 1 #numbers of images to generate: 1-4 (for imagen only)
--aspect-ratio(-a):string = "16:9" #aspect ratio: 1:1, 3:4, 4:3, 9:16 or 16:9 (for imagen only)
--person-generation(-p):string = "ALLOW_ADULT" #ALLOW_ADULT or DONT_ALLOW (imagen only)
--output(-o):string #output filename
--paid(-P) = false #use paid gemini
] {
let prompt = get-input $in $query
#api parameters
let apikey = if $paid {
$env.MY_ENV_VARS.api_keys.google.gemini_paid
} else {
$env.MY_ENV_VARS.api_keys.google.gemini
}
if ($number_of_images > 4) and ($model like "imagen") {
return-error "Max. number of requested images is 4!!!"
}
if ($task like "edit") and ($model like "imagen") {
return-error "Editing mode not available form Imagen model!"
}
let safetySettings = [
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
threshold: "BLOCK_NONE",
},
{
category: "HARM_CATEGORY_CIVIC_INTEGRITY",
threshold: "BLOCK_NONE",
}
]
let gen = if ($model like "imagen") {":predict"} else {":generateContent"}
let input_model = $model
let model = if $model == "gemini" {"gemini-2.0-flash-exp-image-generation"} else {$model}
let model = if $model == "imagen3" {"imagen-3.0-generate-002"} else {$model}
let model = if $model == "imagen4" {"imagen-4.0-generate-preview-06-06"} else {$model}
let model = if $model == "imagen4ultra" {"imagen-4.0-ultra-generate-preview-06-06"} else {$model}
let url_request = {
scheme: "https",
host: "generativelanguage.googleapis.com",
path: ("/v1beta/models/" + $model + $gen),
params: {
key: $apikey,
}
} | url join
let output = if ($output | is-empty) {
(google_ai --select_preprompt dalle_image_name -d true $prompt -P $paid | from json | get name) + "_G"
} else {
$output
}
#translate prompt if not in english
let english = google_ai --select_preprompt is_in_english -d true $prompt -P $paid | from json | get english | into bool
let prompt = if $english and $task == "generation" {google_ai --select_system ai_art_creator --select_preprompt translate_dalle_prompt -d true $prompt -P $paid} else {$prompt}
let prompt = if $task == "generation" {
google_ai --select_system ai_art_creator --select_preprompt improve_dalle_prompt -d true $prompt -P $paid
} else {
$prompt
}
print (echo-g "improved prompt: ")
print ($prompt)
match $task {
"generation" => {
let request = if ($model like "imagen") {
{
instances: [
{
prompt: $prompt
}
],
parameters: {
sampleCount: $number_of_images,
aspect_ratio: $aspect_ratio,
person_generation: $person_generation
}
}
} else {
{
contents: [{
parts: [
{
text: $prompt
}
]
}],
generationConfig:{
responseModalities:["Text","Image"]
},
safetySettings: $safetySettings
}
}
let answer = http post -t application/json $url_request $request
if ($model like "imagen") {
$answer.predictions.bytesBase64Encoded
| enumerate
| each {|img|
print (echo-g $"saving image ($img.index | into string)...")
$img.item
| decode base64
| save -f ($output + $"_($img.index | into string).png")
}
} else {
$answer.candidates.content.parts.0.inlineData.data.0
| decode base64
| save -f ($output + ".png")
}
},
"edit" => {
let request = {
contents: [{
parts: [
{
text: $prompt
},
{
inline_data: {
mime_type: "image/jpeg",
data: (open ($image | path expand) | encode base64)
}
}
]
}],
generationConfig:{
responseModalities:["Text","Image"]
},
safetySettings: $safetySettings
}
let answer = http post -t application/json $url_request $request
$answer.candidates.content.parts.0.inlineData.data.0
| decode base64
| save -f ($output + ".png")
},
_ => {return-error $"$(task) not available!!!"}
}
}
#summarize the output of google_search via ai
@category ai
@search-terms google-search summary gemini chatgpt ollama
export def "ai google_search-summary" [
question:string #the question made to google
web_content = "" #output of google_search, md or table
--md(-m) #return concatenated md instead of table
--model(-M):string = "gemini" #select model: gpt4, gemini, ollama
--paid(-P) #use paid gemini
] {
let web_content = if ($web_content | is-empty) {$in} else {$web_content}
let max_words = if $model == "gemini" {800000} else {100000}
let n_webs = if ($web_content | is-empty) {
0
} else if ($web_content | describe | split row '<' | get 0) like "table" {
$web_content | length
} else {
0
}
let prompt = (
open ([$env.MY_ENV_VARS.chatgpt_config prompt summarize_html2text.md] | path join)
| str replace "<question>" $question
)
print (echo-g $"asking ($model) to summarize the web results...")
if ($n_webs == 0) {
print (echo-c $"summarizing md web results..." "green")
let truncated_content = $web_content # | str truncate -m $max_words
let complete_prompt = $prompt + "\n'''\n" + $truncated_content + "\n'''"
let summarized_content = match $model {
$s if ($s | str starts-with "llama") or ($s | str starts-with "qwq") => {
o_llama $complete_prompt --select_system html2text_summarizer -m $model
},
$s if ($s | str starts-with "gpt") => {
chat_gpt $complete_prompt --select_system html2text_summarizer -m gpt-4.1
},
"gemini" => {
google_ai $complete_prompt --select_system html2text_summarizer -m gemini-2.5-flash -P $paid
}
}
return $summarized_content
}
mut content = []
for i in 0..($n_webs - 1) {
let web = $web_content | get $i
print (echo-c $"summarizing the results of ($web.displayLink)..." "green")
let truncated_content = $web.content | str truncate -m $max_words
let complete_prompt = $prompt + "\n'''\n" + $truncated_content + "\n'''"
let summarized_content = match $model {
$s if ($s | str starts-with "llama") or ($s | str starts-with "qwq") => {
o_llama $complete_prompt --select_system html2text_summarizer -m $model
},
$s if ($s | str starts-with "gpt") => {
chat_gpt $complete_prompt --select_system html2text_summarizer -m gpt-4.1
},
"gemini" => {
google_ai $complete_prompt --select_system html2text_summarizer -m gemini-2.5-flash -P $paid
}
}
$content = $content ++ [$summarized_content]
}
let content = $content | wrap content
let updated_content = $web_content | reject content | merge $content
if $md {
mut md_output = ""
for i in 0..($n_webs - 1) {
let web = $updated_content | get $i
$md_output = $md_output + "# " + $web.title + "\n"
$md_output = $md_output + "link: " + $web.link + "\n\n"
$md_output = $md_output + $web.content + "\n\n"
}
return $md_output
} else {
return $updated_content
}
}