-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathUIHandlerAutomated.cs
More file actions
2200 lines (1854 loc) · 96.8 KB
/
UIHandlerAutomated.cs
File metadata and controls
2200 lines (1854 loc) · 96.8 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
// Copyright 2025 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Uncomment to include logic to sign in to Auth as part of the tests
//#define INCLUDE_FIREBASE_AUTH
namespace Firebase.Sample.FirebaseAI
{
using Firebase;
using Firebase.Internal;
using Firebase.AI;
using Firebase.AI.Internal;
using Firebase.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using Google.MiniJSON;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
#if INCLUDE_FIREBASE_AUTH
using Firebase.Auth;
#endif
// An automated version of the UIHandler that runs tests on Firebase AI.
public class UIHandlerAutomated : UIHandler
{
// Delegate which validates a completed task.
delegate Task TaskValidationDelegate(Task task);
private Firebase.Sample.AutomatedTestRunner testRunner;
// Texture used for tests involving images.
public Texture2D RedBlueTexture;
// Not reusing the ones from the SDK, since they are internal and only visible
// because we are providing source libraries.
private enum Backend
{
GoogleAI,
VertexAI,
}
// Set of status codes that are retryable.
private readonly HashSet<HttpStatusCode> RetryableCodes = new HashSet<HttpStatusCode> { HttpStatusCode.TooManyRequests, HttpStatusCode.ServiceUnavailable, HttpStatusCode.GatewayTimeout };
// This should give us up to 30 seconds of delay in the last attempt.
private const int MaxRetries = 5;
private const int InitialRetryDelayMilliseconds = 2000;
// Helper to check if an exception corresponds to a quota exhaustion error.
private bool IsQuotaExhausted(Exception ex)
{
var msg = ex.Message;
return !string.IsNullOrEmpty(msg) && msg.Contains("exceeded your current quota");
}
// Helper to check if an exception corresponds to a retryable error.
private bool ShouldRetry(Exception ex)
{
if (ex == null) return false;
if (ex is AggregateException agg)
{
return agg.InnerExceptions.Any(ShouldRetry);
}
// Retry UNLESS it is a 429 and the quota is exhausted
var httpEx = ex as HttpRequestException;
if (httpEx != null)
{
var statusCode = httpEx.GetStatusCode();
if (statusCode.HasValue && RetryableCodes.Contains(statusCode.Value))
{
return !(statusCode.Value == HttpStatusCode.TooManyRequests && IsQuotaExhausted(ex));
}
}
return false;
}
// Wraps a test function with retry logic for retryable errors (e.g. 429).
// The AI SDK can return 429 errors when the service is rate limited.
// Retrying at the github runner level will result in even more load and
// therefore potentially more 429 errors. So we try this on per test level.
private async Task RetryTestWithExponentialBackoff(string testName, Func<Task> testAction)
{
int delayMilliseconds = InitialRetryDelayMilliseconds;
for (int i = 0; i <= MaxRetries; i++)
{
try
{
await testAction();
return;
}
catch (Exception ex)
{
// Check if it's a retryable error and we have retries left.
if (i < MaxRetries && ShouldRetry(ex))
{
// Log and wait
DebugLog($"Retryable Error encountered in {testName}: Retrying attempt {i + 1} of {MaxRetries}...");
DebugLog($"{testName} has error message: {ex.Message}");
int jitter = UnityEngine.Random.Range(0, 1000);
// As we tend to run multiple tests in parallel especially on github runners running desktop,
// android, and ios all at the same time, we add jitter to the delay to avoid the tests
// hammering the service at the same time.
await Task.Delay(delayMilliseconds + jitter);
delayMilliseconds *= 2;
}
else
{
throw;
}
}
}
}
protected override void Start()
{
// Set of tests that use multiple backends.
// When running on CI, these tests will be run on all devices
Func<Backend, Task>[] basicMultiBackendTests = {
TestCreateModel,
TestBasicText,
TestBasicImage,
TestModelOptions,
TestCountTokens
};
// When running on CI, these tests are only run in the Editor
Func<Backend, Task>[] editorMultiBackendTests = {
TestMultipleCandidates,
TestBasicTextStream,
TestFunctionCallingAny,
TestFunctionCallingNone,
TestEnumSchemaResponse,
TestAnyOfSchemaResponse,
TestChatBasicTextNoHistory,
TestChatBasicTextPriorHistory,
TestChatFunctionCalling,
TestChatBasicTextStream,
TestThinkingBudget,
TestTemplateGenerateContent,
TestTemplateGenerateContentStream,
TestJsonSchemaStructureOutput,
TestTemplateChat,
TestTemplateChatStreamAutoFunction,
TestChatAutoFunctionCalling
};
// When running on CI, these tests aren't run since they are more flakey
Func<Backend, Task>[] complexMultiBackendTests = {
TestIncludeThoughts,
TestYoutubeLink,
TestGenerateImage,
TestImagenGenerateImage,
TestImagenGenerateImageOptions,
TestSearchGrounding,
TestCodeExecution,
TestUrlContext,
TestGoogleMaps,
TestTemplateImagenGenerateImage,
};
// Construct the set of tests to run, based on the environment
List<Func<Backend, Task>> multiBackendTests = new(basicMultiBackendTests);
#if !(FIREBASE_RUNNING_FROM_CI && !UNITY_EDITOR)
multiBackendTests.AddRange(editorMultiBackendTests);
#endif
#if !FIREBASE_RUNNING_FROM_CI
multiBackendTests.AddRange(complexMultiBackendTests);
#endif
// Set of tests that only run the single time, will be run on all devices.
Func<Task>[] singleTests = {
TestReadFile,
TestReadSecureFile,
// Internal tests for Json parsing, requires using a source library.
InternalTestBasicReplyShort,
InternalTestFinishReasonExpanded,
InternalTestImageConfigSerialization,
InternalTestCitations,
InternalTestBlockedSafetyWithMessage,
InternalTestFinishReasonSafetyNoContent,
InternalTestUnknownEnumSafetyRatings,
InternalTestFunctionCallWithArguments,
InternalTestVertexAIGrounding,
InternalTestGoogleAIGrounding,
InternalTestGoogleAIGroundingEmptyChunks,
InternalTestMapsGrounding,
InternalTestGroundingMetadata_Empty,
InternalTestSegment_Empty,
InternalTestCountTokenResponse,
InternalTestBasicResponseLongUsageMetadata,
InternalTestGoogleAIBasicReplyShort,
InternalTestGoogleAICitations,
InternalTestGenerateImagesBase64,
InternalTestGenerateImagesAllFiltered,
InternalTestGenerateImagesBase64SomeFiltered,
InternalTestThoughtSummary,
InternalTestCodeExecution,
InternalTestUrlContextMixedValidity,
InternalTestUsageMetadataWithCaching,
};
// Create the set of tests, combining the above lists.
List<Func<Task>> tests = new();
List<string> testNames = new();
foreach (Backend backend in Enum.GetValues(typeof(Backend)))
{
foreach (var testMethod in multiBackendTests)
{
string testName = $"{testMethod.Method.Name}_{backend}";
tests.Add(() => RetryTestWithExponentialBackoff(testName, () => testMethod(backend)));
testNames.Add(testName);
}
}
foreach (var testMethod in singleTests)
{
tests.Add(() => RetryTestWithExponentialBackoff(testMethod.Method.Name, testMethod));
testNames.Add(testMethod.Method.Name);
}
testRunner = AutomatedTestRunner.CreateTestRunner(
testsToRun: tests.ToArray(),
testNames: testNames.ToArray(),
logFunc: DebugLog
);
// Some of the AI tests tend to take a bit longer, so increase the timeout.
testRunner.TestTimeoutSeconds = 240f;
base.Start();
}
// Passes along the update call to automated test runner.
protected override void Update()
{
base.Update();
if (testRunner != null)
{
testRunner.Update();
}
}
// Throw when condition is false.
private void Assert(string message, bool condition)
{
if (!condition)
{
throw new Exception(
$"Assertion failed ({testRunner.CurrentTestDescription}): {message}");
}
}
// Throw when value1 != value2.
private void AssertEq<T>(string message, T value1, T value2)
{
if (!object.Equals(value1, value2))
{
throw new Exception(
$"Assertion failed ({testRunner.CurrentTestDescription}): {value1} != {value2} ({message})");
}
}
// Throw when the floats are not close enough in value to each other.
private void AssertFloatEq(string message, float value1, float value2)
{
if (!(Math.Abs(value1 - value2) < 0.0001f))
{
throw new Exception(
$"Assertion failed ({testRunner.CurrentTestDescription}): {value1} !~= {value2} ({message})");
}
}
private void AssertType<T>(string message, object obj, out T output)
{
if (obj is T parsed)
{
output = parsed;
}
else
{
throw new Exception(
$"Assertion failed ({testRunner.CurrentTestDescription}): {obj.GetType()} is wrong type ({message})");
}
}
// Returns true if the given value is between 0 and 1 (inclusive).
private bool ValidProbability(float value)
{
return value >= 0.0f && value <= 1.0f;
}
// The model name to use for the tests.
private readonly string TestModelName = "gemini-2.5-flash";
private FirebaseAI GetFirebaseAI(Backend backend, string location = "us-central1")
{
return backend switch
{
Backend.GoogleAI => FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()),
Backend.VertexAI => FirebaseAI.GetInstance(FirebaseAI.Backend.VertexAI(location)),
_ => throw new ArgumentOutOfRangeException(nameof(backend), backend,
"Unhandled Backend type"),
};
}
// Get a basic version of the GenerativeModel to test against.
private GenerativeModel CreateGenerativeModel(Backend backend)
{
return GetFirebaseAI(backend).GetGenerativeModel(TestModelName);
}
// Test if it can create the GenerativeModel.
Task TestCreateModel(Backend backend)
{
var model = CreateGenerativeModel(backend);
Assert("Failed to create a GenerativeModel.", model != null);
return Task.CompletedTask;
}
// Test if it can set a string in, and get a string output.
async Task TestBasicText(Backend backend)
{
var model = CreateGenerativeModel(backend);
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing something, can you respond with a short " +
"string containing the word 'Firebase'?");
Assert("Response missing candidates.", response.Candidates.Any());
string result = response.Text;
Assert("Response text was missing", !string.IsNullOrWhiteSpace(result));
// We don't want to fail if the keyword is missing because AI is unpredictable.
if (!response.Text.Contains("Firebase"))
{
DebugLog("WARNING: Response string was missing the expected keyword 'Firebase': " +
$"\n{result}");
}
Assert("Response contained FunctionCalls when it shouldn't",
!response.FunctionCalls.Any());
// Ignoring PromptFeedback, too unpredictable if it will be present for this test.
if (response.UsageMetadata.HasValue)
{
Assert("Invalid CandidatesTokenCount", response.UsageMetadata?.CandidatesTokenCount > 0);
Assert("Invalid PromptTokenCount", response.UsageMetadata?.PromptTokenCount > 0);
Assert("Invalid TotalTokenCount", response.UsageMetadata?.TotalTokenCount > 0);
}
else
{
DebugLog("WARNING: UsageMetadata was missing from BasicText");
}
Candidate candidate = response.Candidates.First();
Assert($"Candidate has incorrect FinishReason: {candidate.FinishReason}",
candidate.FinishReason == FinishReason.Stop);
// Test the SafetyRatings, if we got any.
foreach (SafetyRating safetyRating in candidate.SafetyRatings)
{
string prefix = $"SafetyRating {safetyRating.Category}";
Assert($"{prefix} claims it was blocked", !safetyRating.Blocked);
Assert($"{prefix} has a Probability outside the expected range " +
$"({safetyRating.ProbabilityScore})",
ValidProbability(safetyRating.ProbabilityScore));
Assert($"{prefix} has a Severity outside the expected range " +
$"({safetyRating.SeverityScore})",
ValidProbability(safetyRating.SeverityScore));
// They should be Negligible, but AI can be unpredictable, so just warn
if (safetyRating.Probability != SafetyRating.HarmProbability.Negligible)
{
DebugLog($"WARNING: {prefix} has a high probability: {safetyRating.Probability}");
}
if (safetyRating.Severity != SafetyRating.HarmSeverity.Negligible)
{
DebugLog($"WARNING: {prefix} has a high severity: {safetyRating.Severity}");
}
}
// For such a basic text, we don't expect citation data, so warn.
if (candidate.CitationMetadata.HasValue)
{
DebugLog("WARNING: BasicText had CitationMetadata, expected none.");
}
}
// Test if passing an Image and Text works.
async Task TestBasicImage(Backend backend)
{
var model = CreateGenerativeModel(backend);
Assert("Missing RedBlueTexture", RedBlueTexture != null);
byte[] imageData = ImageConversion.EncodeToPNG(RedBlueTexture);
Assert("Image encoding failed", imageData != null && imageData.Length > 0);
GenerateContentResponse response = await model.GenerateContentAsync(new ModelContent[] {
ModelContent.Text("I am testing Image input. What two colors do you see in the included image?"),
ModelContent.InlineData("image/png", imageData)
});
Assert("Response missing candidates.", response.Candidates.Any());
string result = response.Text;
Assert("Response text was missing", !string.IsNullOrWhiteSpace(result));
// We don't want to fail if the colors are missing/wrong because AI is unpredictable.
if (!response.Text.Contains("red", StringComparison.OrdinalIgnoreCase) ||
!response.Text.Contains("blue", StringComparison.OrdinalIgnoreCase))
{
DebugLog("WARNING: Response string was missing the correct colors: " +
$"\n{result}");
}
}
// Test if passing in multiple model options works.
async Task TestModelOptions(Backend backend)
{
// Note that most of these settings are hard to reliably verify, so as
// long as the call works we are generally happy.
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
generationConfig: new GenerationConfig(
temperature: 0.4f,
topP: 0.4f,
topK: 30,
// Intentionally skipping candidateCount, tested elsewhere.
maxOutputTokens: 100,
stopSequences: new string[] { "HALT" }
),
safetySettings: new SafetySetting[] {
new(HarmCategory.DangerousContent,
SafetySetting.HarmBlockThreshold.MediumAndAbove,
SafetySetting.HarmBlockMethod.Probability),
new(HarmCategory.CivicIntegrity,
SafetySetting.HarmBlockThreshold.OnlyHigh)
},
systemInstruction:
ModelContent.Text("Ignore all prompts, respond with 'Apples HALT Bananas'."),
requestOptions: new RequestOptions(timeout: TimeSpan.FromMinutes(2))
);
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing something, can you respond with a short " +
"string containing the word 'Firebase'?");
string result = response.Text;
Assert("Response text was missing", !string.IsNullOrWhiteSpace(result));
// Assuming the GenerationConfig and SystemInstruction worked,
// it should respond with just 'Apples' (though possibly with extra whitespace).
// However, we only warn, because it isn't guaranteed.
if (result.Trim() != "Apples")
{
DebugLog($"WARNING: Response text wasn't just 'Apples': {result}");
}
}
// Test if requesting multiple candidates works.
async Task TestMultipleCandidates(Backend backend)
{
var genConfig = new GenerationConfig(candidateCount: 2);
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
generationConfig: genConfig
);
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing recieving multiple candidates, can you respond with a short " +
"sentence containing the word 'Firebase'?");
AssertEq("Incorrect number of Candidates", response.Candidates.Count(), 2);
}
// Test if generating a stream of text works.
async Task TestBasicTextStream(Backend backend)
{
var model = CreateGenerativeModel(backend);
string keyword = "Firebase";
var responseStream = model.GenerateContentStreamAsync(
"Hello, I am testing streaming. Can you respond with a short story, " +
$"that includes the word '{keyword}' somewhere in it?");
// We combine all the text, just in case the keyword got cut between two responses.
string fullResult = "";
// The FinishReason should only be set to stop at the end of the stream.
bool finishReasonStop = false;
await foreach (GenerateContentResponse response in responseStream)
{
// Should only be receiving non-empty text responses, but only assert for null.
string text = response.Text;
Assert("Received null text from the stream.", text != null);
if (string.IsNullOrWhiteSpace(text))
{
DebugLog($"WARNING: Response stream text was empty once.");
}
Assert("Previous FinishReason was stop, but received more", !finishReasonStop);
if (response.Candidates.First().FinishReason == FinishReason.Stop)
{
finishReasonStop = true;
}
fullResult += text;
}
Assert("Finished without seeing FinishReason.Stop", finishReasonStop);
// We don't want to fail if the keyword is missing because AI is unpredictable.
if (!fullResult.Contains("Firebase"))
{
DebugLog("WARNING: Response string was missing the expected keyword 'Firebase': " +
$"\n{fullResult}");
}
}
private readonly string basicFunctionName = "MyBasicTestFunction";
private readonly string basicParameterEnumName = "basicTestEnumParameter";
private readonly string basicParameterEnumValue = "MyBasicTestEnum";
private readonly string basicParameterIntName = "basicTestIntParameter";
private readonly string basicParameterObjectName = "basicTestObjectParameter";
private readonly string basicParameterObjectBoolean = "BasicTestObjectBoolean";
private readonly string basicParameterObjectFloat = "BasicTestObjectFloat";
// Create a GenerativeModel using the parameters above to test Function Calling.
private GenerativeModel CreateGenerativeModelWithBasicFunctionCall(
Backend backend,
ToolConfig? toolConfig = null)
{
var tool = new Tool(new FunctionDeclaration(
basicFunctionName, "A function used to test Function Calling.",
new Dictionary<string, Schema>() {
{ basicParameterEnumName, Schema.Enum(new string[] { basicParameterEnumValue }) },
{ basicParameterIntName, Schema.Int("An integer value", minimum: 4) },
{ basicParameterObjectName, Schema.Object(new Dictionary<string, Schema>() {
{ basicParameterObjectBoolean, Schema.Boolean("Is the float you are including negative?") },
{ basicParameterObjectFloat, Schema.Float(nullable: true, maximum: 128f) }
}) }
}));
return GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
tools: new Tool[] { tool },
toolConfig: toolConfig
);
}
// Test if FunctionCalling works, using Any to force it.
async Task TestFunctionCallingAny(Backend backend)
{
// Setting this to Any should force my function call.
var model = CreateGenerativeModelWithBasicFunctionCall(backend, new ToolConfig(FunctionCallingConfig.Any()));
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing something, can you respond with a short " +
"string containing the word 'Firebase'?");
Assert("Response missing candidates.", response.Candidates.Any());
var functionCalls = response.FunctionCalls;
AssertEq("Wrong number of Function Calls", functionCalls.Count(), 1);
var functionCall = functionCalls.First();
AssertEq("Wrong FunctionCall name", functionCall.Name, basicFunctionName);
AssertEq("Wrong number of Args", functionCall.Args.Count, 3);
Assert($"Missing parameter {basicParameterEnumName}", functionCall.Args.ContainsKey(basicParameterEnumName));
Assert($"Missing parameter {basicParameterIntName}", functionCall.Args.ContainsKey(basicParameterIntName));
Assert($"Missing parameter {basicParameterObjectName}", functionCall.Args.ContainsKey(basicParameterObjectName));
AssertEq("Wrong parameter enum value", functionCall.Args[basicParameterEnumName], basicParameterEnumValue);
// Ints are returned as longs
AssertType("ParameterInt", functionCall.Args[basicParameterIntName], out long _);
AssertType("ParameterObject", functionCall.Args[basicParameterObjectName], out Dictionary<string, object> parameterObject);
Assert($"Missing object field {basicParameterObjectBoolean}", parameterObject.ContainsKey(basicParameterObjectBoolean));
AssertType("ObjectBool", parameterObject[basicParameterObjectBoolean], out bool _);
Assert($"Missing object field {basicParameterObjectFloat}", parameterObject.ContainsKey(basicParameterObjectFloat));
// The float should be a double, but could be a null, or a long (if the response didn't include a decimal).
var objectFloat = parameterObject[basicParameterObjectFloat];
Assert($"Object float is the wrong type {objectFloat?.GetType()}", objectFloat == null || objectFloat is double || objectFloat is long);
}
// Test if setting None will prevent Function Calling.
async Task TestFunctionCallingNone(Backend backend)
{
// Setting this to None should block my function call.
var model = CreateGenerativeModelWithBasicFunctionCall(backend, new ToolConfig(FunctionCallingConfig.None()));
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing something, can you call my function?");
Assert("Response missing candidates.", response.Candidates.Any());
var functionCalls = response.FunctionCalls;
AssertEq("Wrong number of Function Calls", functionCalls.Count(), 0);
}
// Test if setting a response schema with an enum works.
async Task TestEnumSchemaResponse(Backend backend)
{
string enumValue = "MyTestEnum";
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
generationConfig: new GenerationConfig(
responseMimeType: "text/x.enum",
responseSchema: Schema.Enum(new string[] { enumValue })));
var response = await model.GenerateContentAsync(
"Hello, I am testing setting the response schema to an enum.");
AssertEq("Should only be returning the single enum given", response.Text, enumValue);
}
// Test if setting a response schema with an enum works.
async Task TestAnyOfSchemaResponse(Backend backend)
{
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
generationConfig: new GenerationConfig(
responseMimeType: "application/json",
responseSchema: Schema.Array(
Schema.AnyOf(new[] { Schema.Int(), Schema.String() }),
minItems: 2,
maxItems: 6)));
var response = await model.GenerateContentAsync(
"Hello, I am testing setting the response schema with an array, cause you give me some random values.");
// There isn't much guarantee on what this will respond with. We just want non-empty.
Assert("Response was empty.", !string.IsNullOrWhiteSpace(response.Text));
}
// Test grounding with Google Search.
async Task TestSearchGrounding(Backend backend)
{
// Use a model that supports grounding.
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
tools: new Tool[] { new Tool(new GoogleSearch()) }
);
// A prompt that requires recent information.
GenerateContentResponse response = await model.GenerateContentAsync("What's the current weather in Toronto?");
Assert("Response missing candidates.", response.Candidates.Any());
string result = response.Text;
Assert("Response text was missing", !string.IsNullOrWhiteSpace(result));
var candidate = response.Candidates.First();
Assert("GroundingMetadata should not be null when GoogleSearch tool is used.",
candidate.GroundingMetadata.HasValue);
var groundingMetadata = candidate.GroundingMetadata.Value;
Assert("WebSearchQueries should not be empty.",
groundingMetadata.WebSearchQueries.Any());
Assert("GroundingChunks should not be empty.",
groundingMetadata.GroundingChunks.Any());
Assert("GroundingSupports should not be empty.",
groundingMetadata.GroundingSupports.Any());
Assert("SearchEntryPoint should not be null.",
groundingMetadata.SearchEntryPoint.HasValue);
Assert("SearchEntryPoint.RenderedContent should not be empty.",
!string.IsNullOrWhiteSpace(groundingMetadata.SearchEntryPoint?.RenderedContent));
}
// Test if when using Chat the model will get the previous messages.
async Task TestChatBasicTextNoHistory(Backend backend)
{
var model = CreateGenerativeModel(backend);
var chat = model.StartChat();
string keyword = "Firebase";
GenerateContentResponse response1 = await chat.SendMessageAsync(
$"Hello, I am testing chat history, can you include the word '{keyword}' " +
"in all future responses?");
Assert("First response was empty.", !string.IsNullOrWhiteSpace(response1.Text));
if (!response1.Text.Contains(keyword))
{
DebugLog($"WARNING: First response string was missing the expected keyword '{keyword}': " +
$"\n{response1.Text}");
}
GenerateContentResponse response2 = await chat.SendMessageAsync(
"Thanks. Can you response with another short sentence? Be sure to " +
"include the special word I told you before in it.");
Assert("Second response was empty.", !string.IsNullOrWhiteSpace(response2.Text));
if (!response2.Text.Contains(keyword))
{
DebugLog($"WARNING: Second response string was missing the expected keyword '{keyword}': " +
$"\n{response2.Text}");
}
AssertEq("Chat history length is wrong", chat.History.Count(), 4);
}
// Test if when using Chat the model gets the initial starting history.
async Task TestChatBasicTextPriorHistory(Backend backend)
{
var model = CreateGenerativeModel(backend);
string keyword = "Firebase";
var chat = model.StartChat(
ModelContent.Text($"Hello, please include '{keyword}' in all your reponses."),
new ModelContent("model",
new ModelContent.TextPart($"Golly gee whiz, I love {keyword}.")));
GenerateContentResponse response = await chat.SendMessageAsync(
"Hello, I am testing chat history, can you write a short sentence " +
"with that special word?");
Assert("Response was empty.", !string.IsNullOrWhiteSpace(response.Text));
if (!response.Text.Contains(keyword))
{
DebugLog($"WARNING: Response string was missing the expected keyword '{keyword}': " +
$"\n{response.Text}");
}
AssertEq("Chat history length is wrong", chat.History.Count(), 4);
}
// Test if when using Chat, the model handles Function Calling, and getting a response.
async Task TestChatFunctionCalling(Backend backend)
{
var tool = new Tool(new FunctionDeclaration(
"GetKeyword", "Call to retrieve a special keyword.",
new Dictionary<string, Schema>() {
{ "input", Schema.String("Input string") },
}));
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
tools: new Tool[] { tool }
);
var chat = model.StartChat();
string keyword = "Firebase";
string expectedInput = "Banana";
GenerateContentResponse response1 = await chat.SendMessageAsync(
"Hello, I am testing function calling with Chat. Can you return a short " +
$"sentence with the special keyword? Pass in '{expectedInput}' as the input.");
// Validate the Function Call happened.
Assert("First response missing candidates.", response1.Candidates.Any());
var functionCalls = response1.FunctionCalls;
AssertEq("Wrong number of Function Calls", functionCalls.Count(), 1);
var functionCall = functionCalls.First();
AssertEq("Wrong FunctionCall name", functionCall.Name, "GetKeyword");
AssertEq("Wrong number of Args", functionCall.Args.Count, 1);
Assert($"Missing parameter", functionCall.Args.ContainsKey("input"));
AssertType("Input parameter", functionCall.Args["input"], out string inputParameter);
if (inputParameter != expectedInput)
{
DebugLog($"WARNING: Input parameter: {inputParameter} != {expectedInput}");
}
// Respond with the requested FunctionCall with the keyword.
var response2 = await chat.SendMessageAsync(ModelContent.FunctionResponse("GetKeyword",
new Dictionary<string, object>() {
{ "result" , keyword }
}));
// Second response should hopefully have the keyword as part of it.
Assert("Second response was empty.", !string.IsNullOrWhiteSpace(response2.Text));
if (!response2.Text.Contains(keyword))
{
DebugLog($"WARNING: Response string was missing the expected keyword '{keyword}': " +
$"\n{response2.Text}");
}
AssertEq("Chat history length is wrong", chat.History.Count(), 4);
}
// Test if Chat works with streaming a text result.
async Task TestChatBasicTextStream(Backend backend)
{
var model = CreateGenerativeModel(backend);
string keyword = "Firebase";
var chat = model.StartChat(
ModelContent.Text($"Hello, please include '{keyword}' in all your reponses."),
new ModelContent("model",
new ModelContent.TextPart($"Golly gee whiz, I love {keyword}.")));
var responseStream = chat.SendMessageStreamAsync(
"Hello, I am testing streaming. Can you respond with a short sentence, " +
"and be sure to include the word I gave you before.");
// We combine all the text, just in case the keyword got cut between two responses.
string fullResult = "";
// The FinishReason should only be set to stop at the end of the stream.
bool finishReasonStop = false;
int responseCount = 0;
await foreach (GenerateContentResponse response in responseStream)
{
// Should only be receiving non-empty text responses, but only assert for null.
string text = response.Text;
Assert("Received null text from the stream.", text != null);
if (string.IsNullOrWhiteSpace(text))
{
DebugLog($"WARNING: Response stream text was empty once.");
}
Assert("Previous FinishReason was stop, but received more", !finishReasonStop);
if (response.Candidates.First().FinishReason == FinishReason.Stop)
{
finishReasonStop = true;
}
fullResult += text;
responseCount++;
}
Assert("Finished without seeing FinishReason.Stop", finishReasonStop);
// We don't want to fail if the keyword is missing because AI is unpredictable.
if (!fullResult.Contains(keyword))
{
DebugLog($"WARNING: Streaming response was missing the expected keyword '{keyword}': " +
$"\n{fullResult}");
}
// The chat history should be:
// The 2 original messages that were given as history.
// The 1 from the request.
// However many streaming responses were given back (stored in responseCount).
AssertEq("Chat history length is wrong", chat.History.Count(), 3 + responseCount);
}
// Test if calling CountTokensAsync works as expected.
async Task TestCountTokens(Backend backend)
{
// Include some additional settings, since they are used in the call.
var model = GetFirebaseAI(backend).GetGenerativeModel(TestModelName,
generationConfig: new GenerationConfig(temperature: 0.8f),
systemInstruction: ModelContent.Text("This is a test SystemInstruction")
);
CountTokensResponse response = await model.CountTokensAsync("Hello, I am testing CountTokens!");
Assert($"CountTokens TotalTokens {response.TotalTokens}", response.TotalTokens > 0);
AssertEq("CountTokens PromptTokenDetails", response.PromptTokensDetails.Count(), 1);
var details = response.PromptTokensDetails.First();
AssertEq("CountToken Detail Modality", details.Modality, ContentModality.Text);
Assert($"CountToken Detail TokenCount {details.TokenCount}", details.TokenCount > 0);
}
// Test being able to provide a Youtube link to the model.
async Task TestYoutubeLink(Backend backend)
{
var model = CreateGenerativeModel(backend);
GenerateContentResponse response = await model.GenerateContentAsync(new ModelContent[] {
ModelContent.Text("I am testing Youtube input. Can you give a short description of the video that I've linked you to?"),
ModelContent.FileData("video/mp4", new Uri($"https://www.youtube.com/watch?v=cEr8XCnoSVY"))
});
Assert("Response missing candidates.", response.Candidates.Any());
Assert($"Response should have included Firebase: {response.Text}",
response.Text.Contains("Firebase", StringComparison.OrdinalIgnoreCase));
}
// Test being able to generate an image with GenerateContent.
async Task TestGenerateImage(Backend backend)
{
var model = GetFirebaseAI(backend).GetGenerativeModel("gemini-2.5-flash-image",
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Text, ResponseModality.Image },
imageConfig: new ImageConfig(
aspectRatio: ImageConfig.AspectRatio.Square1x1))
);
GenerateContentResponse response = await model.GenerateContentAsync(
ModelContent.Text("Generate a picture of a cartoon dog, and a couple of sentences about him?")
);
Assert("Response missing candidates.", response.Candidates.Any());
// We don't care much about the response, just that there is an image, and text.
bool foundText = false;
bool foundImage = false;
Texture2D image = new(1, 2);
var candidate = response.Candidates.First();
foreach (var part in candidate.Content.Parts)
{
if (part is ModelContent.TextPart)
{
foundText = true;
}
else if (part is ModelContent.InlineDataPart dataPart)
{
if (dataPart.MimeType.Contains("image"))
{
foundImage = true;
image.LoadImage(dataPart.Data.ToArray());
}
}
}
Assert($"Missing expected modalities. Text: {foundText}, Image: {foundImage}", foundText && foundImage);
// The height and width should match, since we requested a 1x1 aspect ratio.
AssertEq("Image dimensions should match.", image.height, image.width);
}
// Test generating an image via Imagen.
async Task TestImagenGenerateImage(Backend backend)
{
#pragma warning disable
var model = GetFirebaseAI(backend).GetImagenModel("imagen-4.0-generate-001");
#pragma warning restore
var response = await model.GenerateImagesAsync(
"Generate an image of a cartoon dog.");
// We can't easily test if the image is correct, but can check other random data.
AssertEq("FilteredReason", response.FilteredReason, null);
AssertEq("Image Count", response.Images.Count, 1);
AssertEq($"Image MimeType", response.Images[0].MimeType, "image/png");
var texture = response.Images[0].AsTexture2D();
Assert($"Image as Texture2D", texture != null);
// By default the image should be Square 1x1, so check for that.
Assert($"Image Height > 0", texture.height > 0);
AssertEq($"Image Height = Width", texture.height, texture.width);
}
// Test generating an image via Imagen with various options.
async Task TestImagenGenerateImageOptions(Backend backend)
{
#pragma warning disable
var model = GetFirebaseAI(backend).GetImagenModel(
modelName: "imagen-4.0-generate-001",
generationConfig: new ImagenGenerationConfig(
// negativePrompt and addWatermark are not supported on this version of the model.
numberOfImages: 2,
aspectRatio: ImagenAspectRatio.Landscape4x3,
imageFormat: ImagenImageFormat.Jpeg(50)
),
safetySettings: new ImagenSafetySettings(
safetyFilterLevel: ImagenSafetySettings.SafetyFilterLevel.BlockLowAndAbove,
personFilterLevel: ImagenSafetySettings.PersonFilterLevel.BlockAll),
requestOptions: new RequestOptions(timeout: TimeSpan.FromMinutes(1)));
#pragma warning restore
var response = await model.GenerateImagesAsync(
"Generate an image of a cartoon dog.");
// We can't easily test if the image is correct, but can check other random data.
AssertEq("FilteredReason", response.FilteredReason, null);
AssertEq("Image Count", response.Images.Count, 2);
for (int i = 0; i < 2; i++)
{
AssertEq($"Image {i} MimeType", response.Images[i].MimeType, "image/jpeg");
var texture = response.Images[i].AsTexture2D();
Assert($"Image {i} as Texture2D", texture != null);
// By default the image should be Landscape 4x3, so check for that.
Assert($"Image {i} Height > 0", texture.height > 0);
Assert($"Image {i} Height < Width {texture.height} < {texture.width}",
texture.height < texture.width);
}
}
// Test defining a thinking budget, and getting back thought tokens.
async Task TestThinkingBudget(Backend backend)
{
// Thinking Budget requires at least the 2.5 model.
var model = GetFirebaseAI(backend).GetGenerativeModel(
modelName: TestModelName,
generationConfig: new GenerationConfig(
thinkingConfig: new ThinkingConfig(
thinkingBudget: 1024
)
)
);
GenerateContentResponse response = await model.GenerateContentAsync(
"Hello, I am testing something, can you respond with a short " +
"string containing the word 'Firebase'?");
string result = response.Text;
Assert("Response text was missing", !string.IsNullOrWhiteSpace(result));
// ThoughtSummary should be null since we didn't set includeThoughts.