-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathGoogleAi_GeminiPro_Should.cs
1641 lines (1471 loc) · 67.6 KB
/
GoogleAi_GeminiPro_Should.cs
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
#if NET472_OR_GREATER || NETSTANDARD2_0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
#endif
#if NET9_0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
#endif
using FluentAssertions;
using Mscc.GenerativeAI;
using System.IO;
using Xunit;
using Xunit.Abstractions;
namespace Test.Mscc.GenerativeAI
{
[Collection(nameof(ConfigurationFixture))]
public class GoogleAiGeminiProShould(ITestOutputHelper output, ConfigurationFixture fixture)
{
private readonly string _model = Model.Gemini15Pro;
[Fact]
public void Initialize_GoogleAI()
{
// Arrange
// Act
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
// Assert
googleAi.Should().NotBeNull();
}
[Fact]
public void Initialize_Using_GoogleAI()
{
// Arrange
var expected = Environment.GetEnvironmentVariable("GOOGLE_AI_MODEL") ?? Model.Gemini15Pro;
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
// Act
var model = googleAi.GenerativeModel();
// Assert
model.Should().NotBeNull();
model.Name.Should().Be($"{expected.SanitizeModelName()}");
}
[Fact]
public void Initialize_EnvVars()
{
// Arrange
Environment.SetEnvironmentVariable("GOOGLE_API_KEY", fixture.ApiKey);
var expected = Environment.GetEnvironmentVariable("GOOGLE_AI_MODEL") ?? Model.Gemini15Pro;
// Act
var model = new GenerativeModel();
// Assert
model.Should().NotBeNull();
model.Name.Should().Be($"{expected.SanitizeModelName()}");
}
[Fact]
public void Initialize_Default_Model()
{
// Arrange
var expected = Environment.GetEnvironmentVariable("GOOGLE_AI_MODEL") ?? Model.Gemini15Pro;
// Act
var model = new GenerativeModel(apiKey: fixture.ApiKey);
// Assert
model.Should().NotBeNull();
model.Name.Should().Be($"{expected.SanitizeModelName()}");
}
[Fact]
public void Initialize_Model()
{
// Arrange
var expected = _model;
// Act
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
// Assert
model.Should().NotBeNull();
model.Name.Should().Be($"{expected.SanitizeModelName()}");
}
[Fact]
public async Task List_Models()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey);
// Act
var sut = await model.ListModels();
// Assert
sut.Should().NotBeNull();
sut.Should().NotBeNull().And.HaveCountGreaterThanOrEqualTo(1);
sut.ForEach(x =>
{
output.WriteLine($"Model: {x.DisplayName} ({x.Name})");
x.SupportedGenerationMethods.ForEach(m => output.WriteLine($" Method: {m}"));
});
}
[Fact]
public async Task List_Models_Using_OAuth()
{
// Arrange
var model = new GenerativeModel { AccessToken = fixture.AccessToken };
// Act
var sut = await model.ListModels();
// Assert
sut.Should().NotBeNull();
sut.Should().NotBeNull().And.HaveCountGreaterThanOrEqualTo(1);
sut.ForEach(x =>
{
output.WriteLine($"Model: {x.DisplayName} ({x.Name})");
x.SupportedGenerationMethods.ForEach(m => output.WriteLine($" Method: {m}"));
});
}
[Fact]
public async Task List_Tuned_Models()
{
// Arrange
var model = new GenerativeModel { AccessToken = fixture.AccessToken };
// Act
var sut = await model.ListModels(true);
// var sut = await model.ListTunedModels();
// Assert
sut.Should().NotBeNull();
sut.Should().NotBeNull().And.HaveCountGreaterThanOrEqualTo(1);
sut.ForEach(x =>
{
output.WriteLine($"Model: {x.DisplayName} ({x.Name})");
x.TuningTask.Snapshots.ForEach(m => output.WriteLine($" Snapshot: {m}"));
});
}
[Theory]
[InlineData(Model.Gemini10Pro001)]
[InlineData(Model.GeminiProVision)]
[InlineData(Model.BisonText)]
[InlineData(Model.BisonChat)]
[InlineData("tunedModels/number-generator-model-psx3d3gljyko")]
public async Task Get_Model_Information(string modelName)
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey);
// Act
var sut = await model.GetModel(model: modelName);
// Assert
sut.Should().NotBeNull();
// sut.Name.Should().Be($"{modelName.SanitizeModelName()}");
output.WriteLine($"Model: {sut.DisplayName} ({sut.Name})");
sut.SupportedGenerationMethods.ForEach(m => output.WriteLine($" Method: {m}"));
}
[Theory]
[InlineData("tunedModels/number-generator-model-psx3d3gljyko")]
public async Task Get_TunedModel_Information_Using_ApiKey(string modelName)
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey);
// Act & Assert
await Assert.ThrowsAsync<NotSupportedException>(() => model.GetModel(model: modelName));
}
[Theory]
[InlineData(Model.Gemini10Pro001)]
[InlineData(Model.GeminiProVision)]
[InlineData(Model.BisonText)]
[InlineData(Model.BisonChat)]
[InlineData("tunedModels/number-generator-model-psx3d3gljyko")]
public async Task Get_Model_Information_Using_OAuth(string modelName)
{
// Arrange
var model = new GenerativeModel { AccessToken = fixture.AccessToken };
var expected = modelName;
if (!expected.Contains("/"))
expected = $"{expected.SanitizeModelName()}";
// Act
var sut = await model.GetModel(model: modelName);
// Assert
sut.Should().NotBeNull();
sut.Name.Should().Be(expected);
output.WriteLine($"Model: {sut.DisplayName} ({sut.Name})");
if (sut.State is null)
{
sut?.SupportedGenerationMethods?.ForEach(m => output.WriteLine($" Method: {m}"));
}
else
{
output.WriteLine($"State: {sut.State}");
}
}
[Fact]
public async Task Generate_Content()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task GenerateContent_WithEmptyPrompt_ThrowsArgumentNullException()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
string prompt = null;
// Act & Assert
await Assert.ThrowsAsync<ArgumentNullException>(() => model.GenerateContent(prompt));
}
[Fact]
public async Task GenerateContent_WithInvalidAPIKey_ChangingBeforeRequest()
{
// Arrange
var prompt = "Tell me 4 things about Taipei. Be short.";
var googleAi = new GoogleAI(apiKey: "WRONG_API_KEY");
var model = googleAi.GenerativeModel(model: Model.Gemini10Pro001);
model.ApiKey = fixture.ApiKey;
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task GenerateContent_WithInvalidAPIKey_ChangingAfterRequest()
{
// Arrange
var prompt = "Tell me 4 things about Taipei. Be short.";
var googleAi = new GoogleAI(apiKey: "WRONG_API_KEY");
var model = googleAi.GenerativeModel(model: Model.Gemini10Pro001);
await Assert.ThrowsAsync<HttpRequestException>(() => model.GenerateContent(prompt));
// Act
model.ApiKey = fixture.ApiKey;
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task Generate_Content_MaxTokens()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
var model = googleAi.GenerativeModel(model: Model.Gemini10Pro001);
var generationConfig = new GenerationConfig() { MaxOutputTokens = 20 };
// Act
var response = await model.GenerateContent(prompt, generationConfig);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().BeEmpty();
// output.WriteLine(response?.Text);
}
[Fact]
public async Task Generate_Content_Stream_MaxTokens()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
var model = googleAi.GenerativeModel(model: Model.Gemini10Pro001);
var generationConfig = new GenerationConfig() { MaxOutputTokens = 20 };
// Act
var responseStream = model.GenerateContentStream(prompt, generationConfig);
// Assert
responseStream.Should().NotBeNull();
await foreach (var response in responseStream)
{
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
if (response.Candidates[0].FinishReason is FinishReason.MaxTokens)
output.WriteLine("...");
else
output.WriteLine(response?.Text);
}
}
[Fact]
public async Task Generate_Content_MultiplePrompt()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var parts = new List<IPart>
{
new TextData { Text = "What is x multiplied by 2?" },
new TextData { Text = "x = 42" }
};
// Act
var response = await model.GenerateContent(parts);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
output.WriteLine(response?.Text);
response.Text.Should().Be("84");
}
[Fact]
public async Task Generate_Content_Request()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var request = new GenerateContentRequest { Contents = new List<Content>() };
request.Contents.Add(new Content
{
Role = Role.User,
Parts = new List<IPart> { new TextData { Text = prompt } }
});
// Act
var response = await model.GenerateContent(request);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task GenerateContent_WithRequest_MultipleCandidates_ThrowsHttpRequestException()
{
// Arrange
var prompt = "Write a short poem about koi fish.";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var request = new GenerateContentRequest
{
Contents = new List<Content>(),
GenerationConfig = new GenerationConfig()
{
CandidateCount = 3
}
};
request.Contents.Add(new Content
{
Role = Role.User,
Parts = new List<IPart> { new TextData { Text = prompt } }
});
// Act & Assert
await Assert.ThrowsAsync<HttpRequestException>(() => model.GenerateContent(request));
}
[Fact]
public async Task GenerateContent_WithNullRequest_ThrowsArgumentNullException()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
GenerateContentRequest request = null;
// Act & Assert
await Assert.ThrowsAsync<ArgumentNullException>(() => model.GenerateContent(request));
}
[Fact]
public async Task Generate_Content_RequestConstructor()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var request = new GenerateContentRequest(prompt);
request.Contents[0].Role = Role.User;
// Act
var response = await model.GenerateContent(request);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task GenerateContent_WithRequest_UseServerSentEvents()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
var model = googleAi.GenerativeModel(model: _model);
model.UseServerSentEventsFormat = true;
var request = new GenerateContentRequest(prompt);
// Act
var response = await model.GenerateContent(request);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task GenerateContent_Stream_WithRequest_ServerSentEvents()
{
// Arrange
var prompt = "Write a story about a magic backpack.";
var googleAi = new GoogleAI(apiKey: fixture.ApiKey);
var model = googleAi.GenerativeModel(model: _model);
model.UseServerSentEventsFormat = true;
var request = new GenerateContentRequest(prompt);
// Act
var responseEvents = model.GenerateContentStream(request);
// Assert
responseEvents.Should().NotBeNull();
await foreach (var response in responseEvents)
{
output.WriteLine($"{response.Text}");
}
}
[Fact]
public async Task Generate_Content_Stream()
{
// Arrange
var prompt = "How are you doing today?";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
// Act
var responseStream = model.GenerateContentStream(prompt);
// Assert
responseStream.Should().NotBeNull();
await foreach (var response in responseStream)
{
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine($"{response.Text}");
// response.UsageMetadata.Should().NotBeNull();
// output.WriteLine($"PromptTokenCount: {response?.UsageMetadata?.PromptTokenCount}");
// output.WriteLine($"CandidatesTokenCount: {response?.UsageMetadata?.CandidatesTokenCount}");
// output.WriteLine($"TotalTokenCount: {response?.UsageMetadata?.TotalTokenCount}");
}
}
[Fact]
public async Task Generate_Content_Stream_Request()
{
// Arrange
var prompt = "How are you doing today?";
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var request = new GenerateContentRequest { Contents = new List<Content>() };
request.Contents.Add(new Content
{
Role = Role.User,
Parts = new List<IPart> { new TextData { Text = prompt } }
});
// Act
var responseStream = model.GenerateContentStream(request);
// Assert
responseStream.Should().NotBeNull();
await foreach (var response in responseStream)
{
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine($"{response.Text}");
// response.UsageMetadata.Should().NotBeNull();
// output.WriteLine($"PromptTokenCount: {response?.UsageMetadata?.PromptTokenCount}");
// output.WriteLine($"CandidatesTokenCount: {response?.UsageMetadata?.CandidatesTokenCount}");
// output.WriteLine($"TotalTokenCount: {response?.UsageMetadata?.TotalTokenCount}");
}
}
[Fact]
public async Task GenerateAnswer_WithValidRequest_ReturnsAnswerResponse()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: Model.AttributedQuestionAnswering);
var request = new GenerateAnswerRequest("What is the capital of France?", AnswerStyle.Abstractive);
// Act
var response = await model.GenerateAnswer(request);
// Assert
response.Should().NotBeNull();
response.Answer.Should().NotBeNull();
response.Text.Should().Be("Paris");
}
[Theory]
[InlineData("How are you doing today?", 6)]
[InlineData("What kind of fish is this?", 7)]
[InlineData("Write a story about a magic backpack.", 8)]
[InlineData("Write an extended story about a magic backpack.", 9)]
public async Task Count_Tokens(string prompt, int expected)
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
// Act
var response = await model.CountTokens(prompt);
// Assert
response.Should().NotBeNull();
response.TotalTokens.Should().BeGreaterThanOrEqualTo(expected);
output.WriteLine($"Tokens: {response?.TotalTokens}");
}
[Theory]
[InlineData("How are you doing today?", 7)]
[InlineData("What kind of fish is this?", 8)]
[InlineData("Write a story about a magic backpack.", 9)]
[InlineData("Write an extended story about a magic backpack.", 10)]
public async Task Count_Tokens_Request(string prompt, int expected)
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var request = new GenerateContentRequest { Contents = new List<Content>() };
request.Contents.Add(new Content
{
Role = Role.User,
Parts = new List<IPart> { new TextData { Text = prompt } }
});
// Act
var response = await model.CountTokens(request);
// Assert
response.Should().NotBeNull();
response.TotalTokens.Should().BeGreaterOrEqualTo(expected);
output.WriteLine($"Tokens: {response?.TotalTokens}");
}
[Fact]
public async Task Start_Chat()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
var prompt = "How can I learn more about C#?";
// Act
var response = await chat.SendMessage(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}
[Fact]
public async Task Start_Chat_With_History()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var history = new List<ContentResponse>
{
new() { Role = Role.User, Text = "Hello" },
new() { Role = Role.Model, Text = "Hello! How can I assist you today?"}
};
var chat = model.StartChat(history);
var prompt = "How does electricity work?";
// Act
var response = await chat.SendMessage(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(prompt);
output.WriteLine(response?.Text);
//output.WriteLine(response?.PromptFeedback);
}
[Fact]
// Refs:
// https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/send-chat-prompts-gemini
public async Task Start_Chat_Multiple_Prompts()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
// Act
var prompt = "Hello, let's talk a bit about nature.";
var response = await chat.SendMessage(prompt);
output.WriteLine(prompt);
output.WriteLine(response?.Text);
prompt = "What are all the colors in a rainbow?";
response = await chat.SendMessage(prompt);
output.WriteLine(prompt);
output.WriteLine(response?.Text);
prompt = "Why does it appear when it rains?";
response = await chat.SendMessage(prompt);
output.WriteLine(prompt);
output.WriteLine(response?.Text);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
}
[Fact]
// Refs:
// https://ai.google.dev/tutorials/python_quickstart#chat_conversations
public async Task Start_Chat_Conversations()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
// Act
_ = await chat.SendMessage("Hello, fancy brainstorming about IT?");
_ = await chat.SendMessage("In one sentence, explain how a computer works to a young child.");
_ = await chat.SendMessage("Okay, how about a more detailed explanation to a high schooler?");
_ = await chat.SendMessage("Lastly, give a thorough definition for a CS graduate.");
// Assert
chat.History.ForEach(c =>
{
output.WriteLine($"{new string('-', 20)}");
output.WriteLine($"{c.Role}: {c.Text}");
});
}
[Fact]
// Refs:
// https://ai.google.dev/tutorials/python_quickstart#chat_conversations
public async Task Start_Chat_Rewind_Conversation()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
_ = await chat.SendMessage("Hello, fancy brainstorming about IT?");
_ = await chat.SendMessage("In one sentence, explain how a computer works to a young child.");
_ = await chat.SendMessage("Okay, how about a more detailed explanation to a high school kid?");
_ = await chat.SendMessage("Lastly, give a thorough definition for a CS graduate.");
// Act
var entries = chat.Rewind();
// Assert
entries.Should().NotBeNull();
entries.Sent.Should().NotBeNull();
entries.Received.Should().NotBeNull();
output.WriteLine("------ Rewind ------");
output.WriteLine($"{entries.Sent.Role}: {entries.Sent.Text}");
output.WriteLine($"{new string('-', 20)}");
output.WriteLine($"{entries.Received.Role}: {entries.Received.Text}");
output.WriteLine($"{new string('-', 20)}");
chat.History.Count.Should().Be(6);
output.WriteLine("------ History -----");
chat.History.ForEach(c =>
{
output.WriteLine($"{new string('-', 20)}");
output.WriteLine($"{c.Role}: {c.Text}");
});
}
[Fact]
// Refs:
// https://ai.google.dev/tutorials/python_quickstart#chat_conversations
public async Task Start_Chat_Conversations_Get_Last()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
_ = await chat.SendMessage("Hello, fancy brainstorming about IT?");
_ = await chat.SendMessage("In one sentence, explain how a computer works to a young child.");
_ = await chat.SendMessage("Okay, how about a more detailed explanation to a high school kid?");
_ = await chat.SendMessage("Lastly, give a thorough definition for a CS graduate.");
// Act
var sut = chat.Last;
// Assert
sut.Should().NotBeNull();
output.WriteLine($"{sut.Role}: {sut.Text}");
}
[Fact]
public async Task Start_Chat_With_Multimodal_Content()
{
// Arrange
var systemInstruction = new Content("You are an expert analyzing transcripts.");
var genAi = new GoogleAI(apiKey: fixture.ApiKey);
var model = genAi.GenerativeModel(_model, systemInstruction: systemInstruction);
var chat = model.StartChat();
var filePath = Path.Combine(Environment.CurrentDirectory, "payload", "a11.txt");
var document = await genAi.UploadFile(filePath);
var request = new GenerateContentRequest("Hi, could you summarize this transcript?");
request.AddMedia(document.File);
// Act
var response = await chat.SendMessage(request);
output.WriteLine($"model: {response.Text}");
output.WriteLine("----------");
response = await chat.SendMessage("Okay, could you tell me more about the trans-lunar injection");
output.WriteLine($"model: {response.Text}");
// Assert
model.Should().NotBeNull();
chat.History.Count.Should().Be(4);
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeNull();
output.WriteLine($"model: {response.Text}");
}
[Fact]
public async Task Start_Chat_Streaming()
{
// Arrange
var model = new GenerativeModel(apiKey: fixture.ApiKey, model: _model);
var chat = model.StartChat();
var prompt = "How can I learn more about C#?";
// Act
var responseStream = chat.SendMessageStream(prompt);
// Assert
responseStream.Should().NotBeNull();
await foreach (var response in responseStream)
{
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine($"{response.Text}");
// response.UsageMetadata.Should().NotBeNull();
// output.WriteLine($"PromptTokenCount: {response?.UsageMetadata?.PromptTokenCount}");
// output.WriteLine($"CandidatesTokenCount: {response?.UsageMetadata?.CandidatesTokenCount}");
// output.WriteLine($"TotalTokenCount: {response?.UsageMetadata?.TotalTokenCount}");
}
chat.History.Count.Should().Be(2);
output.WriteLine($"{new string('-', 20)}");
output.WriteLine("------ History -----");
chat.History.ForEach(c =>
{
output.WriteLine($"{new string('-', 20)}");
output.WriteLine($"{c.Role}: {c.Text}");
});
}
[Fact]
// Ref: https://ai.google.dev/api/generate-content#code-execution
public async Task Generate_Content_Code_Execution()
{
// Arrange
var prompt = "What is the sum of the first 50 prime numbers?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel(Model.Gemini15Flash,
tools: [new Tool { CodeExecution = new() }]);
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates[0].Content.Parts.Select(x =>
x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/grounding
public async Task Generate_Content_Grounding_Search()
{
// Arrange
var prompt = "What is the current Google stock price?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel("gemini-1.5-pro-002");
model.UseGrounding = true;
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Candidates![0].GroundingMetadata.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.SearchEntryPoint.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.WebSearchQueries.Should().NotBeNull();
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].Content!.Parts
.Select(x => x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
response.Candidates![0].GroundingMetadata!.GroundingChunks?
.ForEach(c =>
output.WriteLine($"{c!.Web!.Title} - {c!.Web!.Uri}"));
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].GroundingMetadata!.WebSearchQueries!
.Select(w => w)
.ToArray()));
output.WriteLine(response.Candidates![0].GroundingMetadata!.SearchEntryPoint!.RenderedContent);
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/grounding
public async Task Generate_Content_Grounding_Search_by_String()
{
// Arrange
var prompt = "Who won Wimbledon this year?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel("gemini-1.5-pro-002",
tools: [new Tool { GoogleSearchRetrieval = new() }]);
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Candidates![0].GroundingMetadata.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.SearchEntryPoint.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.WebSearchQueries.Should().NotBeNull();
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].Content!.Parts
.Select(x => x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
response.Candidates![0].GroundingMetadata!.GroundingChunks?
.ForEach(c =>
output.WriteLine($"{c!.Web!.Title} - {c!.Web!.Uri}"));
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].GroundingMetadata!.WebSearchQueries!
.Select(w => w)
.ToArray()));
output.WriteLine(response.Candidates![0].GroundingMetadata!.SearchEntryPoint!.RenderedContent);
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/grounding
public async Task Generate_Content_Grounding_Search_by_Dictionary()
{
// Arrange
var prompt = "Who won Wimbledon this year?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel("gemini-1.5-pro-002",
tools: [new Tool { GoogleSearchRetrieval =
new(DynamicRetrievalConfigMode.ModeUnspecified, 0.06f) }]);
model.UseGrounding = true;
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].Content!.Parts
.Select(x => x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
response.Candidates![0].GroundingMetadata!.GroundingChunks?
.ForEach(c =>
output.WriteLine($"{c!.Web!.Title} - {c!.Web!.Uri}"));
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].GroundingMetadata!.WebSearchQueries!
.Select(w => w)
.ToArray()));
output.WriteLine(response.Candidates![0].GroundingMetadata!.SearchEntryPoint!.RenderedContent);
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/grounding
public async Task Generate_Content_Grounding_Search_Default()
{
// Arrange
var prompt = "Who won Wimbledon this year?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel("gemini-1.5-pro-002",
tools: [new Tool { GoogleSearchRetrieval = new() }]);
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].Content!.Parts
.Select(x => x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
response.Candidates![0].GroundingMetadata!.GroundingChunks?
.ForEach(c =>
output.WriteLine($"{c!.Web!.Title} - {c!.Web!.Uri}"));
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].GroundingMetadata!.WebSearchQueries!
.Select(w => w)
.ToArray()));
output.WriteLine(response.Candidates![0].GroundingMetadata!.SearchEntryPoint!.RenderedContent);
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/models/gemini-v2#search-tool
public async Task Generate_Content_with_Google_Search()
{
// Arrange
var prompt = "When is the next total solar eclipse in Mauritius?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel(Model.Gemini20FlashExperimental);
model.UseGoogleSearch = true;
// Act
var response = await model.GenerateContent(prompt);
// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Candidates![0].GroundingMetadata.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.SearchEntryPoint.Should().NotBeNull();
response.Candidates![0].GroundingMetadata!.WebSearchQueries.Should().NotBeNull();
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].Content!.Parts
.Select(x => x.Text)
// .Where(t => !string.IsNullOrEmpty(t))
.ToArray()));
response.Candidates![0].GroundingMetadata!.GroundingChunks?
.ForEach(c =>
output.WriteLine($"{c!.Web!.Title} - {c!.Web!.Uri}"));
output.WriteLine(string.Join(Environment.NewLine,
response.Candidates![0].GroundingMetadata!.WebSearchQueries!
.Select(w => w)
.ToArray()));
output.WriteLine(response.Candidates![0].GroundingMetadata!.SearchEntryPoint!.RenderedContent);
}
[Fact]
// Ref: https://ai.google.dev/gemini-api/docs/models/gemini-v2#search-tool
public async Task Generate_Content_with_GoogleSearch_ResponseModalities()
{
// Arrange
var prompt = "When is the next total solar eclipse in Mauritius?";
var genAi = new GoogleAI(fixture.ApiKey);
var model = genAi.GenerativeModel(Model.Gemini20FlashExperimental);
model.UseGoogleSearch = true;
// Act