-
Notifications
You must be signed in to change notification settings - Fork 348
/
_generative_models.py
2622 lines (2283 loc) · 94.4 KB
/
_generative_models.py
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 2024 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.
#
"""Classes for working with generative models."""
# pylint: disable=bad-continuation, line-too-long, protected-access
from collections.abc import Mapping
import copy
import io
import json
import pathlib
from typing import (
Any,
AsyncIterable,
Awaitable,
Callable,
Dict,
Iterable,
List,
Optional,
Sequence,
Union,
TYPE_CHECKING,
)
from google.cloud.aiplatform import initializer as aiplatform_initializer
from google.cloud.aiplatform import utils as aiplatform_utils
from google.cloud.aiplatform_v1beta1 import types as aiplatform_types
from google.cloud.aiplatform_v1beta1.services import prediction_service
from google.cloud.aiplatform_v1beta1.types import (
content as gapic_content_types,
)
from google.cloud.aiplatform_v1beta1.types import (
prediction_service as gapic_prediction_service_types,
)
from google.cloud.aiplatform_v1beta1.types import tool as gapic_tool_types
from google.protobuf import json_format
import warnings
if TYPE_CHECKING:
from vertexai.preview import caching
try:
from PIL import Image as PIL_Image # pylint: disable=g-import-not-at-top
except ImportError:
PIL_Image = None
# Re-exporting some GAPIC types
# GAPIC types used in request
HarmCategory = gapic_content_types.HarmCategory
HarmBlockThreshold = gapic_content_types.SafetySetting.HarmBlockThreshold
# GAPIC types used in response
# We expose FinishReason to make it easier to check the response finish reason.
FinishReason = gapic_content_types.Candidate.FinishReason
# We expose SafetyRating to make it easier to check the response safety rating.
SafetyRating = gapic_content_types.SafetyRating
# These type defnitions are expanded to help the user see all the types
PartsType = Union[
str,
"Image",
"Part",
List[Union[str, "Image", "Part"]],
]
ContentDict = Dict[str, Any]
ContentsType = Union[
List["Content"],
List[ContentDict],
str,
"Image",
"Part",
List[Union[str, "Image", "Part"]],
]
GenerationConfigDict = Dict[str, Any]
GenerationConfigType = Union[
"GenerationConfig",
GenerationConfigDict,
]
SafetySettingsType = Union[
List["SafetySetting"],
Dict[
gapic_content_types.HarmCategory,
gapic_content_types.SafetySetting.HarmBlockThreshold,
],
]
def _reconcile_model_name(model_name: str, project: str, location: str) -> str:
"""Returns a model name that's one of the following:
1. A full resource name starting with projects/
2. A partial resource name starting with publishers/
"""
if "/" not in model_name:
return f"publishers/google/models/{model_name}"
elif model_name.startswith("models/"):
return f"publishers/google/{model_name}"
elif model_name.startswith("publishers/") or model_name.startswith("projects/"):
return model_name
else:
raise ValueError(
"model_name must be either a Model Garden model ID or a full resource name."
f"recieved model_name {model_name}"
)
def _get_resource_name_from_model_name(
model_name: str, project: str, location: str
) -> str:
"""Returns the full resource name starting with projects/ given a model name."""
if model_name.startswith("publishers/"):
return f"projects/{project}/locations/{location}/{model_name}"
elif model_name.startswith("projects/"):
return model_name
else:
raise ValueError(
"model_name must be either a Model Garden model ID or a full resource name."
)
def _validate_generate_content_parameters(
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
system_instruction: Optional[PartsType] = None,
cached_content: Optional["caching.CachedContent"] = None,
) -> None:
"""Validates the parameters for a generate_content call."""
if not contents:
raise TypeError("contents must not be empty")
_validate_contents_type_as_valid_sequence(contents)
if cached_content and any([tools, tool_config, system_instruction]):
raise ValueError(
"When using cached_content, tools, tool_config, and system_instruction must be None."
)
if safety_settings:
_validate_safety_settings_type_as_valid_sequence(safety_settings)
if generation_config:
if not isinstance(
generation_config,
(gapic_content_types.GenerationConfig, GenerationConfig, Dict),
):
raise TypeError(
"generation_config must either be a GenerationConfig object or a dictionary representation of it."
)
if tools:
_validate_tools_type_as_valid_sequence(tools)
if tool_config:
_validate_tool_config_type(tool_config)
def _validate_contents_type_as_valid_sequence(contents: ContentsType) -> None:
"""Makes sure that individual elements of contents are of valid type."""
# contents can either be a list of Content objects (most generic case)
if isinstance(contents, Sequence) and any(
isinstance(c, gapic_content_types.Content) for c in contents
):
if not all(isinstance(c, gapic_content_types.Content) for c in contents):
raise TypeError(
"When passing a list with Content objects, every item in a "
+ "list must be a Content object."
)
elif isinstance(contents, Sequence) and any(
isinstance(c, Content) for c in contents
):
if not all(isinstance(c, Content) for c in contents):
raise TypeError(
"When passing a list with Content objects, every item in a "
+ "list must be a Content object."
)
elif isinstance(contents, Sequence) and any(isinstance(c, dict) for c in contents):
if not all(isinstance(c, dict) for c in contents):
raise TypeError(
"When passing a list with Content dict objects, every item in "
+ "a list must be a Content dict object."
)
def _validate_safety_settings_type_as_valid_sequence(
safety_settings: SafetySettingsType,
) -> None:
if not isinstance(safety_settings, (Sequence, Dict)):
raise TypeError(
"safety_settings must either be a SafetySetting object or a "
+ "dictionary mapping from HarmCategory to HarmBlockThreshold."
)
if isinstance(safety_settings, Sequence):
for safety_setting in safety_settings:
if not isinstance(
safety_setting,
(gapic_content_types.SafetySetting, SafetySetting),
):
raise TypeError(
"When passing a list with SafetySettings objects, every "
+ "item in a list must be a SafetySetting object."
)
def _validate_tools_type_as_valid_sequence(tools: List["Tool"]):
for tool in tools:
if not isinstance(tool, (gapic_tool_types.Tool, Tool)):
raise TypeError(f"Unexpected tool type: {tool}.")
def _validate_tool_config_type(tool_config: "ToolConfig"):
if not isinstance(tool_config, ToolConfig):
raise TypeError("tool_config must be a ToolConfig object.")
def _content_types_to_gapic_contents(
contents: ContentsType,
) -> List[gapic_content_types.Content]:
"""Converts a list of Content objects to a list of gapic_content_types.Content objects."""
if isinstance(contents, Sequence) and any(
isinstance(c, gapic_content_types.Content) for c in contents
):
return contents
elif isinstance(contents, Sequence) and any(
isinstance(c, Content) for c in contents
):
return [content._raw_content for content in contents]
elif isinstance(contents, Sequence) and any(isinstance(c, dict) for c in contents):
return [gapic_content_types.Content(content_dict) for content_dict in contents]
# or a value that can be converted to a *single* Content object
else:
return [_to_content(contents)]
def _tool_types_to_gapic_tools(
tools: Optional[List["Tool"]],
) -> List[gapic_tool_types.Tool]:
"""Converts a list of Tool objects to a list of gapic_tool_types.Tool objects."""
gapic_tools = []
if tools:
for tool in tools:
if isinstance(tool, gapic_tool_types.Tool):
gapic_tools.append(tool)
elif isinstance(tool, Tool):
gapic_tools.append(tool._raw_tool)
return gapic_tools
class _GenerativeModel:
r"""A model that can generate content.
Usage:
```
model = GenerativeModel("gemini-pro")
response = model.generate_content(
contents="Why is sky blue?",
# Optional:
generation_config=GenerationConfig(
temperature=0.1,
top_p=0.95,
top_k=20,
candidate_count=1,
max_output_tokens=100,
stop_sequences=["STOP!"],
),
safety_settings={
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
}
)
```
"""
_USER_ROLE = "user"
_MODEL_ROLE = "model"
def __init__(
self,
model_name: str,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
system_instruction: Optional[PartsType] = None,
):
r"""Initializes GenerativeModel.
Usage:
```
model = GenerativeModel("gemini-pro")
print(model.generate_content("Hello"))
```
Args:
model_name: Model Garden model resource name.
Alternatively, a tuned model endpoint resource name can be provided.
generation_config: Default generation config to use in generate_content.
safety_settings: Default safety settings to use in generate_content.
tools: Default tools to use in generate_content.
tool_config: Default tool config to use in generate_content.
system_instruction: Default system instruction to use in generate_content.
Note: Only text should be used in parts.
Content of each part will become a separate paragraph.
"""
project = aiplatform_initializer.global_config.project
location = aiplatform_initializer.global_config.location
model_name = _reconcile_model_name(model_name, project, location)
prediction_resource_name = _get_resource_name_from_model_name(
model_name, project, location
)
location = aiplatform_utils.extract_project_and_location_from_parent(
prediction_resource_name
)["location"]
self._model_name = model_name
self._prediction_resource_name = prediction_resource_name
self._location = location
self._generation_config = generation_config
self._safety_settings = safety_settings
self._tools = tools
self._tool_config = tool_config
self._system_instruction = system_instruction
self._cached_content: Optional["caching.CachedContent"] = None
# Validating the parameters
_validate_generate_content_parameters(
contents="test",
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
system_instruction=system_instruction,
)
@property
def _prediction_client(self) -> prediction_service.PredictionServiceClient:
# Switch to @functools.cached_property once its available.
if not getattr(self, "_prediction_client_value", None):
self._prediction_client_value = (
aiplatform_initializer.global_config.create_client(
client_class=prediction_service.PredictionServiceClient,
location_override=self._location,
prediction_client=True,
)
)
return self._prediction_client_value
@property
def _prediction_async_client(
self,
) -> prediction_service.PredictionServiceAsyncClient:
# Switch to @functools.cached_property once its available.
if not getattr(self, "_prediction_async_client_value", None):
self._prediction_async_client_value = (
aiplatform_initializer.global_config.create_client(
client_class=prediction_service.PredictionServiceAsyncClient,
location_override=self._location,
prediction_client=True,
)
)
return self._prediction_async_client_value
def _prepare_request(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
system_instruction: Optional[PartsType] = None,
) -> gapic_prediction_service_types.GenerateContentRequest:
"""Prepares a GAPIC GenerateContentRequest."""
if not contents:
raise TypeError("contents must not be empty")
generation_config = generation_config or self._generation_config
safety_settings = safety_settings or self._safety_settings
tools = tools or self._tools
tool_config = tool_config or self._tool_config
system_instruction = system_instruction or self._system_instruction
cached_content = self._cached_content
_validate_generate_content_parameters(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
system_instruction=system_instruction,
cached_content=cached_content,
)
contents = _content_types_to_gapic_contents(contents)
gapic_system_instruction: Optional[gapic_content_types.Content] = None
if system_instruction:
gapic_system_instruction = _to_content(system_instruction)
gapic_generation_config: Optional[gapic_content_types.GenerationConfig] = None
if generation_config:
if isinstance(generation_config, gapic_content_types.GenerationConfig):
gapic_generation_config = generation_config
elif isinstance(generation_config, GenerationConfig):
gapic_generation_config = generation_config._raw_generation_config
elif isinstance(generation_config, Dict):
gapic_generation_config = gapic_content_types.GenerationConfig(
**generation_config
)
gapic_safety_settings = None
if safety_settings:
if isinstance(safety_settings, Sequence):
gapic_safety_settings = []
for safety_setting in safety_settings:
if isinstance(safety_setting, gapic_content_types.SafetySetting):
gapic_safety_settings.append(safety_setting)
elif isinstance(safety_setting, SafetySetting):
gapic_safety_settings.append(safety_setting._raw_safety_setting)
elif isinstance(safety_settings, dict):
gapic_safety_settings = [
gapic_content_types.SafetySetting(
category=gapic_content_types.HarmCategory(category),
threshold=gapic_content_types.SafetySetting.HarmBlockThreshold(
threshold
),
)
for category, threshold in safety_settings.items()
]
gapic_tools = None
if tools:
gapic_tools = _tool_types_to_gapic_tools(tools)
gapic_tool_config = None
if tool_config:
gapic_tool_config = tool_config._gapic_tool_config
return gapic_prediction_service_types.GenerateContentRequest(
# The `model` parameter now needs to be set for the vision models.
# Always need to pass the resource via the `model` parameter.
# Even when resource is an endpoint.
model=self._prediction_resource_name,
contents=contents,
generation_config=gapic_generation_config,
safety_settings=gapic_safety_settings,
tools=gapic_tools,
tool_config=gapic_tool_config,
system_instruction=gapic_system_instruction,
cached_content=cached_content.resource_name if cached_content else None,
)
def _parse_response(
self,
response: gapic_prediction_service_types.GenerateContentResponse,
) -> "GenerationResponse":
return GenerationResponse._from_gapic(response)
def generate_content(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
stream: bool = False,
) -> Union["GenerationResponse", Iterable["GenerationResponse"],]:
"""Generates content.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
stream: Whether to stream the response.
Returns:
A single GenerationResponse object if stream == False
A stream of GenerationResponse objects if stream == True
"""
if stream:
# TODO(b/315810992): Surface prompt_feedback on the returned stream object
return self._generate_content_streaming(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
else:
return self._generate_content(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
async def generate_content_async(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
stream: bool = False,
) -> Union["GenerationResponse", AsyncIterable["GenerationResponse"],]:
"""Generates content asynchronously.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
stream: Whether to stream the response.
Returns:
An awaitable for a single GenerationResponse object if stream == False
An awaitable for a stream of GenerationResponse objects if stream == True
"""
if stream:
return await self._generate_content_streaming_async(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
else:
return await self._generate_content_async(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
def _generate_content(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
) -> "GenerationResponse":
"""Generates content.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
Returns:
A single GenerationResponse object
"""
request = self._prepare_request(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
gapic_response = self._prediction_client.generate_content(request=request)
return self._parse_response(gapic_response)
async def _generate_content_async(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
) -> "GenerationResponse":
"""Generates content asynchronously.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
Returns:
An awaitable for a single GenerationResponse object
"""
request = self._prepare_request(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
gapic_response = await self._prediction_async_client.generate_content(
request=request
)
return self._parse_response(gapic_response)
def _generate_content_streaming(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
) -> Iterable["GenerationResponse"]:
"""Generates content.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
Yields:
A stream of GenerationResponse objects
"""
request = self._prepare_request(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
response_stream = self._prediction_client.stream_generate_content(
request=request
)
for chunk in response_stream:
yield self._parse_response(chunk)
async def _generate_content_streaming_async(
self,
contents: ContentsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
tool_config: Optional["ToolConfig"] = None,
) -> AsyncIterable["GenerationResponse"]:
"""Generates content asynchronously.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
tool_config: Config shared for all tools provided in the request.
Returns:
An awaitable for a stream of GenerationResponse objects
"""
request = self._prepare_request(
contents=contents,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
tool_config=tool_config,
)
response_stream = await self._prediction_async_client.stream_generate_content(
request=request
)
async def async_generator():
async for chunk in response_stream:
yield self._parse_response(chunk)
return async_generator()
def count_tokens(
self, contents: ContentsType
) -> gapic_prediction_service_types.CountTokensResponse:
"""Counts tokens.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
Returns:
A CountTokensResponse object that has the following attributes:
total_tokens: The total number of tokens counted across all instances from the request.
total_billable_characters: The total number of billable characters counted across all instances from the request.
"""
return self._prediction_client.count_tokens(
request=gapic_prediction_service_types.CountTokensRequest(
endpoint=self._prediction_resource_name,
model=self._prediction_resource_name,
contents=self._prepare_request(contents=contents).contents,
)
)
async def count_tokens_async(
self, contents: ContentsType
) -> gapic_prediction_service_types.CountTokensResponse:
"""Counts tokens asynchronously.
Args:
contents: Contents to send to the model.
Supports either a list of Content objects (passing a multi-turn conversation)
or a value that can be converted to a single Content object (passing a single message).
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
* List[Content]
Returns:
And awaitable for a CountTokensResponse object that has the following attributes:
total_tokens: The total number of tokens counted across all instances from the request.
total_billable_characters: The total number of billable characters counted across all instances from the request.
"""
return await self._prediction_async_client.count_tokens(
request=gapic_prediction_service_types.CountTokensRequest(
endpoint=self._prediction_resource_name,
model=self._prediction_resource_name,
contents=self._prepare_request(contents=contents).contents,
)
)
def start_chat(
self,
*,
history: Optional[List["Content"]] = None,
response_validation: bool = True,
) -> "ChatSession":
"""Creates a stateful chat session.
Args:
history: Previous history to initialize the chat session.
response_validation: Whether to validate responses before adding
them to chat history. By default, `send_message` will raise
error if the request or response is blocked or if the response
is incomplete due to going over the max token limit.
If set to `False`, the chat session history will always
accumulate the request and response messages even if the
reponse if blocked or incomplete. This can result in an unusable
chat session state.
Returns:
A ChatSession object.
"""
return ChatSession(
model=self,
history=history,
response_validation=response_validation,
)
_SUCCESSFUL_FINISH_REASONS = [
gapic_content_types.Candidate.FinishReason.STOP,
# Many responses have this finish reason
gapic_content_types.Candidate.FinishReason.FINISH_REASON_UNSPECIFIED,
]
def _validate_response(
response: "GenerationResponse",
request_contents: Optional[List["Content"]] = None,
response_chunks: Optional[List["GenerationResponse"]] = None,
) -> None:
message = ""
if not response.candidates:
message += (
f"The model response was blocked due to {response._raw_response.prompt_feedback.block_reason}.\n"
f"Block reason message: {response._raw_response.prompt_feedback.block_reason_message}.\n"
)
else:
candidate = response.candidates[0]
if candidate.finish_reason not in _SUCCESSFUL_FINISH_REASONS:
message = (
"The model response did not completed successfully.\n"
f"Finish reason: {candidate.finish_reason}.\n"
f"Finish message: {candidate.finish_message}.\n"
f"Safety ratings: {candidate.safety_ratings}.\n"
)
if message:
message += (
"To protect the integrity of the chat session, the request and response were not added to chat history.\n"
"To skip the response validation, specify `model.start_chat(response_validation=False)`.\n"
"Note that letting blocked or otherwise incomplete responses into chat history might lead to future interactions being blocked by the service."
)
raise ResponseValidationError(
message=message,
request_contents=request_contents,
responses=response_chunks,
)
class ChatSession:
"""Chat session holds the chat history."""
_USER_ROLE = "user"
_MODEL_ROLE = "model"
def __init__(
self,
model: _GenerativeModel,
*,
history: Optional[List["Content"]] = None,
response_validation: bool = True,
):
if history:
if not all(isinstance(item, Content) for item in history):
raise ValueError("history must be a list of Content objects.")
self._model = model
self._history = history or []
self._response_validator = _validate_response if response_validation else None
# _responder is currently only set by PreviewChatSession
self._responder: Optional["AutomaticFunctionCallingResponder"] = None
@property
def history(self) -> List["Content"]:
return self._history
def send_message(
self,
content: PartsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
stream: bool = False,
) -> Union["GenerationResponse", Iterable["GenerationResponse"]]:
"""Generates content.
Args:
content: Content to send to the model.
Supports a value that can be converted to a Part or a list of such values.
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
stream: Whether to stream the response.
Returns:
A single GenerationResponse object if stream == False
A stream of GenerationResponse objects if stream == True
Raises:
ResponseValidationError: If the response was blocked or is incomplete.
"""
if stream:
return self._send_message_streaming(
content=content,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
)
else:
return self._send_message(
content=content,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
)
def send_message_async(
self,
content: PartsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
stream: bool = False,
) -> Union[
Awaitable["GenerationResponse"],
Awaitable[AsyncIterable["GenerationResponse"]],
]:
"""Generates content asynchronously.
Args:
content: Content to send to the model.
Supports a value that can be converted to a Part or a list of such values.
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
stream: Whether to stream the response.
Returns:
An awaitable for a single GenerationResponse object if stream == False
An awaitable for a stream of GenerationResponse objects if stream == True
Raises:
ResponseValidationError: If the response was blocked or is incomplete.
"""
if stream:
return self._send_message_streaming_async(
content=content,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
)
else:
return self._send_message_async(
content=content,
generation_config=generation_config,
safety_settings=safety_settings,
tools=tools,
)
def _send_message(
self,
content: PartsType,
*,
generation_config: Optional[GenerationConfigType] = None,
safety_settings: Optional[SafetySettingsType] = None,
tools: Optional[List["Tool"]] = None,
) -> "GenerationResponse":
"""Generates content.
Args:
content: Content to send to the model.
Supports a value that can be converted to a Part or a list of such values.
Supports
* str, Image, Part,
* List[Union[str, Image, Part]],
generation_config: Parameters for the generation.
safety_settings: Safety settings as a mapping from HarmCategory to HarmBlockThreshold.
tools: A list of tools (functions) that the model can try calling.
Returns: