google-genai 1.1.0__py3-none-any.whl → 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
google/genai/types.py CHANGED
@@ -22,9 +22,10 @@ import json
22
22
  import logging
23
23
  import sys
24
24
  import typing
25
- from typing import Any, Callable, GenericAlias, Literal, Optional, Type, TypedDict, Union
25
+ from typing import Any, Callable, GenericAlias, Literal, Optional, Union
26
26
  import pydantic
27
27
  from pydantic import Field
28
+ from typing_extensions import TypedDict
28
29
  from . import _common
29
30
 
30
31
  if sys.version_info >= (3, 10):
@@ -43,7 +44,7 @@ if typing.TYPE_CHECKING:
43
44
  PIL_Image = PIL.Image.Image
44
45
  _is_pillow_image_imported = True
45
46
  else:
46
- PIL_Image: Type = Any
47
+ PIL_Image: typing.Type = Any
47
48
  try:
48
49
  import PIL.Image
49
50
 
@@ -52,6 +53,8 @@ else:
52
53
  except ImportError:
53
54
  PIL_Image = None
54
55
 
56
+ logger = logging.getLogger('google_genai.types')
57
+
55
58
 
56
59
  class Outcome(_common.CaseInSensitiveEnum):
57
60
  """Required. Outcome of the code execution."""
@@ -690,6 +693,65 @@ class Content(_common.BaseModel):
690
693
  )
691
694
 
692
695
 
696
+ class UserContent(Content):
697
+ """UserContent facilitates the creation of a Content object with a user role.
698
+
699
+ Example usages:
700
+
701
+
702
+ - Create a user Content object with a string:
703
+ user_content = UserContent("Why is the sky blue?")
704
+ - Create a user Content object with a file data Part object:
705
+ user_content = UserContent(Part.from_uri(file_uril="gs://bucket/file.txt",
706
+ mime_type="text/plain"))
707
+ - Create a user Content object with byte data Part object:
708
+ user_content = UserContent(Part.from_bytes(data=b"Hello, World!",
709
+ mime_type="text/plain"))
710
+
711
+ You can create a user Content object using other classmethods in the Part
712
+ class as well.
713
+ You can also create a user Content using a list of Part objects or strings.
714
+ """
715
+
716
+ role: Literal['user'] = Field(default='user', init=False, frozen=True)
717
+ parts: list[Part] = Field(init=False)
718
+
719
+ @pydantic.field_validator('parts', mode='before')
720
+ def validate_parts(cls, value):
721
+ from . import _transformers as t
722
+
723
+ return t.t_parts(None, parts=value)
724
+
725
+
726
+ class ModelContent(Content):
727
+ """ModelContent facilitates the creation of a Content object with a model role.
728
+
729
+ Example usages:
730
+
731
+ - Create a model Content object with a string:
732
+ model_content = ModelContent("Why is the sky blue?")
733
+ - Create a model Content object with a file data Part object:
734
+ model_content = ModelContent(Part.from_uri(file_uril="gs://bucket/file.txt",
735
+ mime_type="text/plain"))
736
+ - Create a model Content object with byte data Part object:
737
+ model_content = ModelContent(Part.from_bytes(data=b"Hello, World!",
738
+ mime_type="text/plain"))
739
+
740
+ You can create a model Content object using other classmethods in the Part
741
+ class as well.
742
+ You can also create a model Content using a list of Part objects or strings.
743
+ """
744
+
745
+ role: Literal['model'] = Field(default='model', init=False, frozen=True)
746
+ parts: list[Part] = Field(init=False)
747
+
748
+ @pydantic.field_validator('parts', mode='before')
749
+ def validate_parts(cls, value):
750
+ from . import _transformers as t
751
+
752
+ return t.t_parts(None, parts=value)
753
+
754
+
693
755
  class ContentDict(TypedDict, total=False):
694
756
  """Contains the multi-part content of a message."""
695
757
 
@@ -1592,7 +1654,7 @@ class File(_common.BaseModel):
1592
1654
  )
1593
1655
  expiration_time: Optional[datetime.datetime] = Field(
1594
1656
  default=None,
1595
- description="""Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image'""",
1657
+ description="""Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire.""",
1596
1658
  )
1597
1659
  update_time: Optional[datetime.datetime] = Field(
1598
1660
  default=None,
@@ -1643,7 +1705,7 @@ class FileDict(TypedDict, total=False):
1643
1705
  """Output only. The timestamp of when the `File` was created."""
1644
1706
 
1645
1707
  expiration_time: Optional[datetime.datetime]
1646
- """Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image'"""
1708
+ """Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire."""
1647
1709
 
1648
1710
  update_time: Optional[datetime.datetime]
1649
1711
  """Output only. The timestamp of when the `File` was last updated."""
@@ -2849,7 +2911,7 @@ class GenerateContentResponse(_common.BaseModel):
2849
2911
  ):
2850
2912
  return None
2851
2913
  if len(self.candidates) > 1:
2852
- logging.warning(
2914
+ logger.warning(
2853
2915
  f'there are {len(self.candidates)} candidates, returning text from'
2854
2916
  ' the first candidate.Access response.candidates directly to get'
2855
2917
  ' text from other candidates.'
@@ -2863,7 +2925,7 @@ class GenerateContentResponse(_common.BaseModel):
2863
2925
  if field_value is not None:
2864
2926
  raise ValueError(
2865
2927
  'GenerateContentResponse.text only supports text parts, but got'
2866
- f' {field_name} part{part}'
2928
+ f' {field_name} part'
2867
2929
  )
2868
2930
  if isinstance(part.text, str):
2869
2931
  if isinstance(part.thought, bool) and part.thought:
@@ -2883,7 +2945,7 @@ class GenerateContentResponse(_common.BaseModel):
2883
2945
  ):
2884
2946
  return None
2885
2947
  if len(self.candidates) > 1:
2886
- logging.warning(
2948
+ logger.warning(
2887
2949
  'Warning: there are multiple candidates in the response, returning'
2888
2950
  ' function calls from the first one.'
2889
2951
  )
@@ -2895,6 +2957,44 @@ class GenerateContentResponse(_common.BaseModel):
2895
2957
 
2896
2958
  return function_calls if function_calls else None
2897
2959
 
2960
+ @property
2961
+ def executable_code(self) -> Optional[str]:
2962
+ """Returns the executable code in the response."""
2963
+ if (
2964
+ not self.candidates
2965
+ or not self.candidates[0].content
2966
+ or not self.candidates[0].content.parts
2967
+ ):
2968
+ return None
2969
+ if len(self.candidates) > 1:
2970
+ logging.warning(
2971
+ 'Warning: there are multiple candidates in the response, returning'
2972
+ ' executable code from the first one.'
2973
+ )
2974
+ for part in self.candidates[0].content.parts:
2975
+ if part.executable_code is not None:
2976
+ return part.executable_code.code
2977
+ return None
2978
+
2979
+ @property
2980
+ def code_execution_result(self) -> Optional[str]:
2981
+ """Returns the code execution result in the response."""
2982
+ if (
2983
+ not self.candidates
2984
+ or not self.candidates[0].content
2985
+ or not self.candidates[0].content.parts
2986
+ ):
2987
+ return None
2988
+ if len(self.candidates) > 1:
2989
+ logging.warning(
2990
+ 'Warning: there are multiple candidates in the response, returning'
2991
+ ' code execution result from the first one.'
2992
+ )
2993
+ for part in self.candidates[0].content.parts:
2994
+ if part.code_execution_result is not None:
2995
+ return part.code_execution_result.output
2996
+ return None
2997
+
2898
2998
  @classmethod
2899
2999
  def _from_response(
2900
3000
  cls, *, response: dict[str, object], kwargs: dict[str, object]
@@ -4834,6 +4934,338 @@ ComputeTokensResponseOrDict = Union[
4834
4934
  ]
4835
4935
 
4836
4936
 
4937
+ class GenerateVideosConfig(_common.BaseModel):
4938
+ """Configuration for generating videos."""
4939
+
4940
+ http_options: Optional[HttpOptions] = Field(
4941
+ default=None, description="""Used to override HTTP request options."""
4942
+ )
4943
+ number_of_videos: Optional[int] = Field(
4944
+ default=None, description="""Number of output videos."""
4945
+ )
4946
+ output_gcs_uri: Optional[str] = Field(
4947
+ default=None,
4948
+ description="""The gcs bucket where to save the generated videos.""",
4949
+ )
4950
+ fps: Optional[int] = Field(
4951
+ default=None, description="""Frames per second for video generation."""
4952
+ )
4953
+ duration_seconds: Optional[int] = Field(
4954
+ default=None,
4955
+ description="""Duration of the clip for video generation in seconds.""",
4956
+ )
4957
+ seed: Optional[int] = Field(
4958
+ default=None,
4959
+ description="""The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result.""",
4960
+ )
4961
+ aspect_ratio: Optional[str] = Field(
4962
+ default=None,
4963
+ description="""The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported.""",
4964
+ )
4965
+ resolution: Optional[str] = Field(
4966
+ default=None,
4967
+ description="""The resolution for the generated video. 1280x720, 1920x1080 are supported.""",
4968
+ )
4969
+ person_generation: Optional[str] = Field(
4970
+ default=None,
4971
+ description="""Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult.""",
4972
+ )
4973
+ pubsub_topic: Optional[str] = Field(
4974
+ default=None,
4975
+ description="""The pubsub topic where to publish the video generation progress.""",
4976
+ )
4977
+ negative_prompt: Optional[str] = Field(
4978
+ default=None,
4979
+ description="""Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video.""",
4980
+ )
4981
+ enhance_prompt: Optional[bool] = Field(
4982
+ default=None, description="""Whether to use the prompt rewriting logic."""
4983
+ )
4984
+
4985
+
4986
+ class GenerateVideosConfigDict(TypedDict, total=False):
4987
+ """Configuration for generating videos."""
4988
+
4989
+ http_options: Optional[HttpOptionsDict]
4990
+ """Used to override HTTP request options."""
4991
+
4992
+ number_of_videos: Optional[int]
4993
+ """Number of output videos."""
4994
+
4995
+ output_gcs_uri: Optional[str]
4996
+ """The gcs bucket where to save the generated videos."""
4997
+
4998
+ fps: Optional[int]
4999
+ """Frames per second for video generation."""
5000
+
5001
+ duration_seconds: Optional[int]
5002
+ """Duration of the clip for video generation in seconds."""
5003
+
5004
+ seed: Optional[int]
5005
+ """The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result."""
5006
+
5007
+ aspect_ratio: Optional[str]
5008
+ """The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported."""
5009
+
5010
+ resolution: Optional[str]
5011
+ """The resolution for the generated video. 1280x720, 1920x1080 are supported."""
5012
+
5013
+ person_generation: Optional[str]
5014
+ """Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult."""
5015
+
5016
+ pubsub_topic: Optional[str]
5017
+ """The pubsub topic where to publish the video generation progress."""
5018
+
5019
+ negative_prompt: Optional[str]
5020
+ """Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video."""
5021
+
5022
+ enhance_prompt: Optional[bool]
5023
+ """Whether to use the prompt rewriting logic."""
5024
+
5025
+
5026
+ GenerateVideosConfigOrDict = Union[
5027
+ GenerateVideosConfig, GenerateVideosConfigDict
5028
+ ]
5029
+
5030
+
5031
+ class _GenerateVideosParameters(_common.BaseModel):
5032
+ """Class that represents the parameters for generating an image."""
5033
+
5034
+ model: Optional[str] = Field(
5035
+ default=None,
5036
+ description="""ID of the model to use. For a list of models, see `Google models
5037
+ <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_.""",
5038
+ )
5039
+ prompt: Optional[str] = Field(
5040
+ default=None,
5041
+ description="""The text prompt for generating the videos. Optional for image to video use cases.""",
5042
+ )
5043
+ config: Optional[GenerateVideosConfig] = Field(
5044
+ default=None, description="""Configuration for generating videos."""
5045
+ )
5046
+
5047
+
5048
+ class _GenerateVideosParametersDict(TypedDict, total=False):
5049
+ """Class that represents the parameters for generating an image."""
5050
+
5051
+ model: Optional[str]
5052
+ """ID of the model to use. For a list of models, see `Google models
5053
+ <https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models>`_."""
5054
+
5055
+ prompt: Optional[str]
5056
+ """The text prompt for generating the videos. Optional for image to video use cases."""
5057
+
5058
+ config: Optional[GenerateVideosConfigDict]
5059
+ """Configuration for generating videos."""
5060
+
5061
+
5062
+ _GenerateVideosParametersOrDict = Union[
5063
+ _GenerateVideosParameters, _GenerateVideosParametersDict
5064
+ ]
5065
+
5066
+
5067
+ class Video(_common.BaseModel):
5068
+ """A generated video."""
5069
+
5070
+ uri: Optional[str] = Field(
5071
+ default=None, description="""Path to another storage."""
5072
+ )
5073
+ video_bytes: Optional[bytes] = Field(
5074
+ default=None, description="""Video bytes."""
5075
+ )
5076
+ mime_type: Optional[str] = Field(
5077
+ default=None, description="""Video encoding, for example "video/mp4"."""
5078
+ )
5079
+
5080
+ def save(
5081
+ self,
5082
+ path: str,
5083
+ # *,
5084
+ # client: Optional[ApiClient] = None,
5085
+ ) -> None:
5086
+ """Saves the video to a file.
5087
+
5088
+ Args:
5089
+ path: Local path where to save the video.
5090
+ """
5091
+ import pathlib # pylint: disable=g-import-not-at-top
5092
+
5093
+ if not self.data:
5094
+ raise NotImplementedError('Saving remote videos is not supported.')
5095
+ if not self.uri:
5096
+ raise ValueError('No data or uri provided.')
5097
+ if not client:
5098
+ raise ValueError('Client is required to save remote videos.')
5099
+ self.data = client.files.download(self.uri)
5100
+
5101
+ pathlib.Path(path).write_bytes(self.data)
5102
+
5103
+ def show(self):
5104
+ """Shows the video.
5105
+
5106
+ This method only works in a notebook environment.
5107
+ """
5108
+ if self.uri:
5109
+ return ValueError('Showing remote videos is not supported.')
5110
+ if not self.video_bytes:
5111
+ return ValueError('Video has no bytes.')
5112
+ if not self.mime_type:
5113
+ return ValueError('Mime type must be provided to display video.')
5114
+
5115
+ try:
5116
+ from IPython import display as IPython_display
5117
+ except ImportError:
5118
+ IPython_display = None
5119
+
5120
+ if IPython_display:
5121
+ return IPython_display.Video(
5122
+ data=self.video_bytes, mimetype=self.mime_type, embed=True
5123
+ )
5124
+
5125
+ def __repr__(self):
5126
+ video_bytes = '<video_bytes>' if self.video_bytes else 'None'
5127
+ return (
5128
+ f'Video(uri={self.uri}, video_bytes={video_bytes},'
5129
+ f' mime_type={self.mime_type})'
5130
+ )
5131
+
5132
+
5133
+ class VideoDict(TypedDict, total=False):
5134
+ """A generated video."""
5135
+
5136
+ uri: Optional[str]
5137
+ """Path to another storage."""
5138
+
5139
+ video_bytes: Optional[bytes]
5140
+ """Video bytes."""
5141
+
5142
+ mime_type: Optional[str]
5143
+ """Video encoding, for example "video/mp4"."""
5144
+
5145
+
5146
+ VideoOrDict = Union[Video, VideoDict]
5147
+
5148
+
5149
+ class GeneratedVideo(_common.BaseModel):
5150
+ """A generated video."""
5151
+
5152
+ video: Optional[Video] = Field(
5153
+ default=None, description="""The output video"""
5154
+ )
5155
+
5156
+
5157
+ class GeneratedVideoDict(TypedDict, total=False):
5158
+ """A generated video."""
5159
+
5160
+ video: Optional[VideoDict]
5161
+ """The output video"""
5162
+
5163
+
5164
+ GeneratedVideoOrDict = Union[GeneratedVideo, GeneratedVideoDict]
5165
+
5166
+
5167
+ class GenerateVideosResponse(_common.BaseModel):
5168
+ """Response with generated videos."""
5169
+
5170
+ generated_videos: Optional[list[GeneratedVideo]] = Field(
5171
+ default=None, description="""List of the generated videos"""
5172
+ )
5173
+ rai_media_filtered_count: Optional[int] = Field(
5174
+ default=None,
5175
+ description="""Returns if any videos were filtered due to RAI policies.""",
5176
+ )
5177
+ rai_media_filtered_reasons: Optional[list[str]] = Field(
5178
+ default=None, description="""Returns rai failure reasons if any."""
5179
+ )
5180
+
5181
+
5182
+ class GenerateVideosResponseDict(TypedDict, total=False):
5183
+ """Response with generated videos."""
5184
+
5185
+ generated_videos: Optional[list[GeneratedVideoDict]]
5186
+ """List of the generated videos"""
5187
+
5188
+ rai_media_filtered_count: Optional[int]
5189
+ """Returns if any videos were filtered due to RAI policies."""
5190
+
5191
+ rai_media_filtered_reasons: Optional[list[str]]
5192
+ """Returns rai failure reasons if any."""
5193
+
5194
+
5195
+ GenerateVideosResponseOrDict = Union[
5196
+ GenerateVideosResponse, GenerateVideosResponseDict
5197
+ ]
5198
+
5199
+
5200
+ class GenerateVideosOperation(_common.BaseModel):
5201
+ """A video generation operation.
5202
+
5203
+ Use the following code to refresh the operation:
5204
+
5205
+ ```
5206
+ operation = client.operations.get(operation)
5207
+ ```
5208
+ """
5209
+
5210
+ name: Optional[str] = Field(
5211
+ default=None,
5212
+ description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""",
5213
+ )
5214
+ metadata: Optional[dict[str, Any]] = Field(
5215
+ default=None,
5216
+ description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""",
5217
+ )
5218
+ done: Optional[bool] = Field(
5219
+ default=None,
5220
+ description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""",
5221
+ )
5222
+ error: Optional[dict[str, Any]] = Field(
5223
+ default=None,
5224
+ description="""The error result of the operation in case of failure or cancellation.""",
5225
+ )
5226
+ response: Optional[dict[str, Any]] = Field(
5227
+ default=None,
5228
+ description="""The normal response of the operation in case of success.""",
5229
+ )
5230
+ result: Optional[GenerateVideosResponse] = Field(
5231
+ default=None, description="""The generated videos."""
5232
+ )
5233
+
5234
+
5235
+ class GenerateVideosOperationDict(TypedDict, total=False):
5236
+ """A video generation operation.
5237
+
5238
+ Use the following code to refresh the operation:
5239
+
5240
+ ```
5241
+ operation = client.operations.get(operation)
5242
+ ```
5243
+ """
5244
+
5245
+ name: Optional[str]
5246
+ """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`."""
5247
+
5248
+ metadata: Optional[dict[str, Any]]
5249
+ """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any."""
5250
+
5251
+ done: Optional[bool]
5252
+ """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available."""
5253
+
5254
+ error: Optional[dict[str, Any]]
5255
+ """The error result of the operation in case of failure or cancellation."""
5256
+
5257
+ response: Optional[dict[str, Any]]
5258
+ """The normal response of the operation in case of success."""
5259
+
5260
+ result: Optional[GenerateVideosResponseDict]
5261
+ """The generated videos."""
5262
+
5263
+
5264
+ GenerateVideosOperationOrDict = Union[
5265
+ GenerateVideosOperation, GenerateVideosOperationDict
5266
+ ]
5267
+
5268
+
4837
5269
  class GetTuningJobConfig(_common.BaseModel):
4838
5270
  """Optional parameters for tunings.get method."""
4839
5271
 
google/genai/version.py CHANGED
@@ -13,4 +13,4 @@
13
13
  # limitations under the License.
14
14
  #
15
15
 
16
- __version__ = '1.1.0' # x-release-please-version
16
+ __version__ = '1.3.0' # x-release-please-version