-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathtest_generative_models.py
More file actions
1941 lines (1774 loc) · 71.2 KB
/
test_generative_models.py
File metadata and controls
1941 lines (1774 loc) · 71.2 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
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# 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.
#
# pylint: disable=protected-access,bad-continuation
import io
import pytest
from typing import Dict, Iterable, List, MutableSequence, Optional
from unittest import mock
from google.api_core import operation as ga_operation
import vertexai
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform_v1 import types as types_v1
from google.cloud.aiplatform_v1.services import (
prediction_service as prediction_service_v1,
)
from google.cloud.aiplatform_v1beta1 import types as types_v1beta1
from google.cloud.aiplatform_v1beta1.services import endpoint_service
from vertexai import generative_models
from vertexai.preview import (
generative_models as preview_generative_models,
rag,
)
from vertexai.generative_models._generative_models import (
prediction_service,
gapic_prediction_service_types,
gapic_content_types,
gapic_tool_types,
_fix_schema_dict_for_gapic_in_place,
)
from google.cloud.aiplatform_v1.types.cached_content import (
CachedContent as GapicCachedContent,
)
from google.cloud.aiplatform_v1.services import (
gen_ai_cache_service,
)
from vertexai.generative_models import _function_calling_utils
from vertexai.caching import CachedContent
from google.protobuf import field_mask_pb2
_TEST_PROJECT = "test-project"
_TEST_PROJECT2 = "test-project2"
_TEST_LOCATION = "us-central1"
_TEST_LOCATION2 = "europe-west4"
_RESPONSE_TEXT_PART_STRUCT = {
"text": "The sky appears blue due to a phenomenon called Rayleigh scattering."
}
_RESPONSE_FUNCTION_CALL_PART_STRUCT = {
"function_call": {
"name": "get_current_weather",
"args": {
"location": "Boston",
},
}
}
_RESPONSE_SAFETY_RATINGS_STRUCT = [
{"category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE"},
]
_RESPONSE_CITATION_STRUCT = {
"start_index": 528,
"end_index": 656,
"uri": "https://www.quora.com/What-makes-the-sky-blue-during-the-day",
}
_REQUEST_TOOL_STRUCT = {
"function_declarations": [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit",
],
},
},
"required": ["location"],
},
}
]
}
_REQUEST_FUNCTION_PARAMETER_SCHEMA_STRUCT = {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit",
],
},
},
"required": ["location"],
}
_REQUEST_FUNCTION_RESPONSE_SCHEMA_STRUCT = {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit",
],
},
"weather": {
"type": "string",
},
},
}
# Input and expected output schema for renaming tests.
_RENAMING_INPUT_SCHEMA = {
"type": "object",
"min_properties": 1,
"maxProperties": 3,
"properties": {
"names": {
"type": "ArRaY",
"minItems": 2,
"max_items": 4,
"items": {
"type": "String",
"minLength": 3,
"maxLength": 5,
},
},
"date": {
"any_of": [
{
"type": "strinG",
"format": "date",
},
{
"anyOf": [
{
"type": "inTegEr",
"minimum": 20241001,
},
],
},
],
},
"ordered": {
"type": "OBJECT",
"properties": {
"a": {"type": "stRIng"},
"b": {"type": "Integer"},
"c": {
"type": "objeCT",
"properties": {
"x": {"type": "string"},
"y": {"type": "number"},
"z": {"type": "integer"},
},
"property_ordering": ["z", "y", "x"],
},
},
"propertyOrdering": ["b", "a", "c"],
},
},
}
_RENAMING_EXPECTED_SCHEMA = {
"type": "OBJECT",
"min_properties": "1", # NB: int64 is converted to string
"max_properties": "3",
"properties": {
"names": {
"type": "ARRAY",
"min_items": "2",
"max_items": "4",
"items": {
"type": "STRING",
"min_length": "3",
"max_length": "5",
},
},
"date": {
"any_of": [
{
"type": "STRING",
"format": "date",
},
{
"any_of": [
{
"type": "INTEGER",
"minimum": 20241001,
},
],
},
],
},
"ordered": {
"type": "OBJECT",
"properties": {
"a": {"type": "STRING"},
"b": {"type": "INTEGER"},
"c": {
"type": "OBJECT",
"properties": {
"x": {"type": "STRING"},
"y": {"type": "NUMBER"},
"z": {"type": "INTEGER"},
},
"property_ordering": ["z", "y", "x"], # explicit order kept
},
},
"property_ordering": ["b", "a", "c"], # explicit order kept
},
},
"property_ordering": ["names", "date", "ordered"], # implicit order added
}
def mock_generate_content(
self,
request: gapic_prediction_service_types.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[gapic_content_types.Content]] = None,
) -> gapic_prediction_service_types.GenerateContentResponse:
last_message_part = request.contents[-1].parts[0]
should_fail = last_message_part.text and "Please fail" in last_message_part.text
if should_fail:
response = gapic_prediction_service_types.GenerateContentResponse(
candidates=[
gapic_content_types.Candidate(
finish_reason=gapic_content_types.Candidate.FinishReason.SAFETY,
finish_message="Failed due to: " + last_message_part.text,
safety_ratings=[
gapic_content_types.SafetyRating(rating)
for rating in _RESPONSE_SAFETY_RATINGS_STRUCT
],
),
],
)
return response
should_block = (
last_message_part.text
and "Please block with block_reason=OTHER" in last_message_part.text
)
if should_block:
response = gapic_prediction_service_types.GenerateContentResponse(
candidates=[],
prompt_feedback=gapic_prediction_service_types.GenerateContentResponse.PromptFeedback(
block_reason=gapic_prediction_service_types.GenerateContentResponse.PromptFeedback.BlockedReason.OTHER,
block_reason_message="Blocked for testing",
),
)
return response
is_continued_chat = len(request.contents) > 1
has_retrieval = any(
tool.retrieval or tool.google_search_retrieval for tool in request.tools
)
has_rag_retrieval = any(
isinstance(tool.retrieval, rag.Retrieval) for tool in request.tools
)
has_function_declarations = any(
tool.function_declarations for tool in request.tools
)
had_any_function_calls = any(
content.parts[0].function_call for content in request.contents
)
had_any_function_responses = any(
content.parts[0].function_response for content in request.contents
)
latest_user_message_function_responses = [
part.function_response
for part in request.contents[-1].parts
if part.function_response
]
if had_any_function_calls:
assert had_any_function_responses
if had_any_function_responses:
assert had_any_function_calls
assert has_function_declarations
if has_function_declarations and not had_any_function_calls:
# response_part_struct = _RESPONSE_FUNCTION_CALL_PART_STRUCT
# Workaround for the proto library bug
first_tool_with_function_declarations = next(
tool for tool in request.tools if tool.function_declarations
)
if (
first_tool_with_function_declarations.function_declarations[0].name
== update_weather_data.__name__
):
response_part_struct = dict(
function_call=gapic_tool_types.FunctionCall(
name=update_weather_data.__name__,
args={
"location": "Boston",
"temperature": 60,
"forecasts": [61, 62],
"extra_info": {"humidity": 50},
},
)
)
else:
response_part_struct = dict(
function_call=gapic_tool_types.FunctionCall(
name="get_current_weather",
args={"location": "Boston"},
)
)
elif has_function_declarations and latest_user_message_function_responses:
function_response = latest_user_message_function_responses[0]
function_response_dict = type(function_response).to_dict(function_response)
function_response_response_dict = function_response_dict["response"]
response_part_struct = {
"text": f"The weather in Boston is {function_response_response_dict}"
}
elif is_continued_chat:
response_part_struct = {"text": "Other planets may have different sky color."}
else:
response_part_struct = _RESPONSE_TEXT_PART_STRUCT
if has_retrieval and (not has_rag_retrieval) and request.contents[0].parts[0].text:
grounding_metadata = gapic_content_types.GroundingMetadata(
web_search_queries=[request.contents[0].parts[0].text],
)
elif has_rag_retrieval and request.contents[0].parts[0].text:
grounding_metadata = gapic_content_types.GroundingMetadata(
retrieval_queries=[request.contents[0].parts[0].text],
)
else:
grounding_metadata = None
response_part = gapic_content_types.Part(response_part_struct)
finish_reason = gapic_content_types.Candidate.FinishReason.STOP
# Handling the max_output_tokens limit
if response_part.text:
if request.generation_config.max_output_tokens:
tokens = response_part.text.split()
if len(tokens) >= request.generation_config.max_output_tokens:
tokens = tokens[: request.generation_config.max_output_tokens]
response_part.text = " ".join(tokens)
finish_reason = gapic_content_types.Candidate.FinishReason.MAX_TOKENS
response = gapic_prediction_service_types.GenerateContentResponse(
candidates=[
gapic_content_types.Candidate(
index=0,
content=gapic_content_types.Content(
role="model",
parts=[response_part],
),
finish_reason=finish_reason,
safety_ratings=[
gapic_content_types.SafetyRating(rating)
for rating in _RESPONSE_SAFETY_RATINGS_STRUCT
],
citation_metadata=gapic_content_types.CitationMetadata(
citations=[
gapic_content_types.Citation(_RESPONSE_CITATION_STRUCT),
]
),
grounding_metadata=grounding_metadata,
),
],
)
if "Please block response with finish_reason=OTHER" in (
last_message_part.text or ""
):
finish_reason = gapic_content_types.Candidate.FinishReason.OTHER
response.candidates[0].finish_reason = finish_reason
request_token_count = sum(
len(gapic_content_types.Content.to_json(content).split())
for content in request.contents
)
response_token_count = sum(
len(gapic_content_types.Content.to_json(candidate.content).split())
for candidate in response.candidates
)
response.usage_metadata.prompt_token_count = request_token_count
response.usage_metadata.candidates_token_count = response_token_count
response.usage_metadata.total_token_count = (
request_token_count + response_token_count
)
return response
@pytest.fixture
def mock_generate_content_fixture():
"""Mocks PredictionServiceClient.generate_content()."""
with mock.patch.object(
prediction_service.PredictionServiceClient,
"generate_content",
new=mock_generate_content,
) as generate_content:
yield generate_content
def mock_stream_generate_content(
self,
request: gapic_prediction_service_types.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[gapic_content_types.Content]] = None,
) -> Iterable[gapic_prediction_service_types.GenerateContentResponse]:
response = mock_generate_content(
self=self, request=request, model=model, contents=contents
)
# When a streaming response gets blocked, the last chunk has no content.
# Creating such last chunk.
blocked_chunk = None
candidate_0 = response.candidates[0] if response.candidates else None
if candidate_0 and candidate_0.finish_reason not in (
gapic_content_types.Candidate.FinishReason.STOP,
gapic_content_types.Candidate.FinishReason.MAX_TOKENS,
):
blocked_chunk = gapic_prediction_service_types.GenerateContentResponse(
candidates=[
gapic_content_types.Candidate(
index=0,
finish_reason=candidate_0.finish_reason,
finish_message=candidate_0.finish_message,
safety_ratings=candidate_0.safety_ratings,
)
]
)
candidate_0.finish_reason = None
candidate_0.finish_message = None
yield response
if blocked_chunk:
yield blocked_chunk
def mock_generate_content_v1(
self,
request: types_v1.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[types_v1.Content]] = None,
) -> types_v1.GenerateContentResponse:
request_v1beta1 = types_v1beta1.GenerateContentRequest.deserialize(
type(request).serialize(request)
)
response_v1beta1 = mock_generate_content(
self=self,
request=request_v1beta1,
)
response_v1 = types_v1.GenerateContentResponse.deserialize(
type(response_v1beta1).serialize(response_v1beta1)
)
return response_v1
def mock_stream_generate_content_v1(
self,
request: types_v1.GenerateContentRequest,
*,
model: Optional[str] = None,
contents: Optional[MutableSequence[types_v1.Content]] = None,
) -> Iterable[types_v1.GenerateContentResponse]:
request_v1beta1 = types_v1beta1.GenerateContentRequest.deserialize(
type(request).serialize(request)
)
for response_v1beta1 in mock_stream_generate_content(
self=self,
request=request_v1beta1,
):
response_v1 = types_v1.GenerateContentResponse.deserialize(
type(response_v1beta1).serialize(response_v1beta1)
)
yield response_v1
def patch_genai_services(func: callable):
"""Patches GenAI services (v1 and v1beta1, streaming and non-streaming)."""
func = mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content,
)(func)
func = mock.patch.object(
target=prediction_service_v1.PredictionServiceClient,
attribute="generate_content",
new=mock_generate_content_v1,
)(func)
func = mock.patch.object(
target=prediction_service.PredictionServiceClient,
attribute="stream_generate_content",
new=mock_stream_generate_content,
)(func)
func = mock.patch.object(
target=prediction_service_v1.PredictionServiceClient,
attribute="stream_generate_content",
new=mock_stream_generate_content_v1,
)(func)
return func
@pytest.fixture
def mock_get_cached_content_fixture():
"""Mocks GenAiCacheServiceClient.get_cached_content()."""
def get_cached_content(self, name, retry=None):
del self, retry
response = GapicCachedContent(
name=f"{name}",
model="gemini-pro-from-mock-get-cached-content",
)
return response
with mock.patch.object(
gen_ai_cache_service.client.GenAiCacheServiceClient,
"get_cached_content",
new=get_cached_content,
) as get_cached_content:
yield get_cached_content
def get_current_weather(location: str, unit: Optional[str] = "centigrade"):
"""Gets weather in the specified location.
Args:
location: The location for which to get the weather.
unit: Temperature unit. Can be Centigrade or Fahrenheit. Default: Centigrade.
Returns:
The weather information as a dict.
"""
return dict(
location=location,
unit=unit,
weather="Super nice, but maybe a bit hot.",
)
def update_weather_data(
location: str, temperature: int, forecasts: List[int], extra_info: Dict[str, int]
):
"""Updates the weather data in the specified location."""
return dict(
location=location,
temperature=temperature,
forecasts=forecasts,
extra_info=extra_info,
result="Success",
)
@pytest.mark.usefixtures("google_auth_mock")
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
class TestGenerativeModels:
"""Unit tests for the generative models."""
@pytest.fixture(scope="function", autouse=True)
def setup_method(self, api_transport: str):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generative_model_constructor_model_name(
self, generative_models: generative_models
):
project_location_prefix = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/"
)
model_name1 = "gemini-pro"
model1 = generative_models.GenerativeModel(model_name1)
assert (
model1._prediction_resource_name
== project_location_prefix + "publishers/google/models/" + model_name1
)
assert model1._model_name == "publishers/google/models/gemini-pro"
model_name2 = "models/gemini-pro"
model2 = generative_models.GenerativeModel(model_name2)
assert (
model2._prediction_resource_name
== project_location_prefix + "publishers/google/" + model_name2
)
assert model2._model_name == "publishers/google/models/gemini-pro"
model_name3 = "publishers/some_publisher/models/some_model"
model3 = generative_models.GenerativeModel(model_name3)
assert model3._prediction_resource_name == project_location_prefix + model_name3
assert model3._model_name == "publishers/some_publisher/models/some_model"
model_name4 = (
f"projects/{_TEST_PROJECT2}/locations/{_TEST_LOCATION2}/endpoints/endpoint1"
)
model4 = generative_models.GenerativeModel(model_name4)
assert model4._prediction_resource_name == model_name4
assert _TEST_LOCATION2 in model4._prediction_client._api_endpoint
assert model4._model_name == model_name4
with pytest.raises(ValueError):
generative_models.GenerativeModel("foo/bar/models/gemini-pro")
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generative_model_from_cached_content(
self, generative_models: generative_models, mock_get_cached_content_fixture
):
project_location_prefix = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/"
)
cached_content = CachedContent("cached-content-id-in-from-cached-content-test")
model = generative_models.GenerativeModel.from_cached_content(
cached_content=cached_content
)
assert (
model._prediction_resource_name
== project_location_prefix
+ "publishers/google/models/"
+ "gemini-pro-from-mock-get-cached-content"
)
assert (
model._cached_content.model_name
== "gemini-pro-from-mock-get-cached-content"
)
assert (
model._cached_content.resource_name
== f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/"
"cachedContents/cached-content-id-in-from-cached-content-test"
)
assert (
model._cached_content.name
== "cached-content-id-in-from-cached-content-test"
)
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generative_model_from_cached_content_with_resource_name(
self, mock_get_cached_content_fixture, generative_models: generative_models
):
project_location_prefix = (
f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/"
)
model = generative_models.GenerativeModel.from_cached_content(
cached_content="cached-content-id-in-from-cached-content-test"
)
assert (
model._prediction_resource_name
== project_location_prefix
+ "publishers/google/models/"
+ "gemini-pro-from-mock-get-cached-content"
)
assert (
model._cached_content.model_name
== "gemini-pro-from-mock-get-cached-content"
)
assert (
model._cached_content.resource_name
== f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}/"
"cachedContents/cached-content-id-in-from-cached-content-test"
)
assert (
model._cached_content.name
== "cached-content-id-in-from-cached-content-test"
)
@patch_genai_services
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content(
self, generative_models: generative_models, api_transport: str
):
model = generative_models.GenerativeModel("gemini-pro")
response = model.generate_content("Why is sky blue?")
assert response.text
# TODO(avolkov): Add usage metadata to the mock
assert response.usage_metadata.total_token_count
model2 = generative_models.GenerativeModel(
"gemini-pro",
system_instruction=[
"Talk like a pirate.",
"Don't use rude words.",
],
)
response2 = model2.generate_content(
"Why is sky blue?",
generation_config=generative_models.GenerationConfig(
temperature=0.2,
top_p=0.9,
top_k=20,
candidate_count=1,
max_output_tokens=200,
stop_sequences=["\n\n\n"],
presence_penalty=0.0,
frequency_penalty=0.0,
logprobs=5,
response_logprobs=True,
response_modalities=["TEXT"],
),
safety_settings=[
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
method=generative_models.SafetySetting.HarmBlockMethod.SEVERITY,
),
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH,
method=generative_models.SafetySetting.HarmBlockMethod.PROBABILITY,
),
],
)
assert response2.text
model3 = generative_models.GenerativeModel("gemini-1.5-pro-preview-0409")
response3 = model3.generate_content(
"Why is sky blue? Respond in JSON.",
generation_config=generative_models.GenerationConfig(
temperature=0.2,
top_p=0.9,
top_k=20,
candidate_count=1,
max_output_tokens=200,
stop_sequences=["\n\n\n"],
response_mime_type="application/json",
),
safety_settings=[
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
method=generative_models.SafetySetting.HarmBlockMethod.SEVERITY,
),
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH,
method=generative_models.SafetySetting.HarmBlockMethod.PROBABILITY,
),
],
)
assert response3.text
model4 = generative_models.GenerativeModel("gemini-1.5-pro-preview-0409")
response4 = model4.generate_content(
"Why is sky blue? Respond in JSON.",
generation_config=generative_models.GenerationConfig(
temperature=0.2,
top_p=0.9,
top_k=20,
candidate_count=1,
max_output_tokens=200,
stop_sequences=["\n\n\n"],
response_mime_type="application/json",
),
safety_settings=[
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
method=generative_models.SafetySetting.HarmBlockMethod.SEVERITY,
),
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH,
method=generative_models.SafetySetting.HarmBlockMethod.PROBABILITY,
),
],
labels={"label1": "value1", "label2": "value2"},
)
assert response4.text
model5 = generative_models.GenerativeModel("gemini-1.5-pro-002")
response5 = model5.generate_content(
contents=[
generative_models.Part.from_uri(
"gs://cloud-samples-data/generative-ai/audio/pixel.mp3",
mime_type="audio/mpeg",
),
"What is the audio about?",
],
generation_config=generative_models.GenerationConfig(
audio_timestamp=True,
),
safety_settings=[
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
method=generative_models.SafetySetting.HarmBlockMethod.SEVERITY,
),
generative_models.SafetySetting(
category=generative_models.SafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=generative_models.SafetySetting.HarmBlockThreshold.BLOCK_ONLY_HIGH,
method=generative_models.SafetySetting.HarmBlockMethod.PROBABILITY,
),
],
)
assert response5.text
@mock.patch.object(
target=prediction_service_v1.PredictionServiceClient,
attribute="generate_content",
new=lambda self, request: gapic_prediction_service_types.GenerateContentResponse(
candidates=[
gapic_content_types.Candidate(
index=0,
content=gapic_content_types.Content(
role="model",
parts=[
gapic_content_types.Part(
{"text": f"response to {request.cached_content}"}
)
],
),
),
],
),
)
def test_generate_content_with_cached_content(
self,
mock_get_cached_content_fixture,
):
cached_content = CachedContent("cached-content-id-in-from-cached-content-test")
model = generative_models.GenerativeModel.from_cached_content(
cached_content=cached_content
)
response = model.generate_content("Why is sky blue?")
assert response.text == "response to " + cached_content.resource_name
@patch_genai_services
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content_streaming(self, generative_models: generative_models):
model = generative_models.GenerativeModel("gemini-pro")
stream = model.generate_content("Why is sky blue?", stream=True)
for chunk in stream:
assert chunk.text
@patch_genai_services
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content_with_function_calling_integer_args(
self, generative_models: generative_models
):
model = generative_models.GenerativeModel("gemini-pro")
weather_tool = generative_models.Tool(
function_declarations=[
generative_models.FunctionDeclaration.from_func(update_weather_data)
],
)
response = model.generate_content(
"Please update the weather data in Boston, with temperature 60, "
"forecasts are 61 and 62, and humidity is 50",
tools=[weather_tool],
)
assert (
response.candidates[0].content.parts[0].function_call.name
== "update_weather_data"
)
assert [
function_call.name
for function_call in response.candidates[0].function_calls
] == ["update_weather_data"]
for args in (
response.candidates[0].function_calls[0].args,
response.candidates[0].function_calls[0].to_dict()["args"],
):
assert args["location"] == "Boston"
assert args["temperature"] == 60
assert isinstance(args["temperature"], int)
assert 61 in args["forecasts"] and 62 in args["forecasts"]
assert all(isinstance(forecast, int) for forecast in args["forecasts"])
assert args["extra_info"]["humidity"] == 50
assert isinstance(args["extra_info"]["humidity"], int)
assert args["location"] == "Boston"
@patch_genai_services
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content_response_accessor_errors(
self, generative_models: generative_models
):
"""Checks that the exception text contains response information."""
model = generative_models.GenerativeModel("gemini-pro")
# Case when response has no candidates
response1 = model.generate_content("Please block with block_reason=OTHER")
assert response1.prompt_feedback.block_reason.name == "OTHER"
with pytest.raises(ValueError) as e:
_ = response1.text
assert e.match("no candidates")
assert e.match("prompt_feedback")
# Case when response candidate content has no parts
response2 = model.generate_content("Please fail!")
with pytest.raises(ValueError) as e:
_ = response2.text
assert e.match("no parts")
assert e.match("finish_reason")
with pytest.raises(ValueError) as e:
_ = response2.candidates[0].text
assert e.match("no parts")
assert e.match("finish_reason")
# Case when response candidate content part has no text
weather_tool = generative_models.Tool(
function_declarations=[
generative_models.FunctionDeclaration.from_func(get_current_weather)
],
)
response3 = model.generate_content(
"What's the weather like in Boston?", tools=[weather_tool]
)
with pytest.raises(ValueError) as e:
print(response3.text)
assert e.match("no text")
assert e.match("function_call")
@patch_genai_services
@pytest.mark.parametrize(
"generative_models",
[generative_models, preview_generative_models],
)
def test_generate_content_model_optimizer(
self, generative_models: generative_models
):
model = generative_models.GenerativeModel("model-optimizer-exp-04-09")