google-genai 1.4.0__py3-none-any.whl → 1.6.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
@@ -23,7 +23,7 @@ import logging
23
23
  import sys
24
24
  import types as builtin_types
25
25
  import typing
26
- from typing import Any, Callable, Literal, Optional, Union, _UnionGenericAlias
26
+ from typing import Any, Callable, Literal, Optional, Union, _UnionGenericAlias # type: ignore
27
27
  import pydantic
28
28
  from pydantic import Field
29
29
  from typing_extensions import TypedDict
@@ -56,6 +56,8 @@ else:
56
56
 
57
57
  logger = logging.getLogger('google_genai.types')
58
58
 
59
+ T = typing.TypeVar('T', bound='GenerateContentResponse')
60
+
59
61
 
60
62
  class Outcome(_common.CaseInSensitiveEnum):
61
63
  """Required. Outcome of the code execution."""
@@ -717,10 +719,12 @@ class UserContent(Content):
717
719
  role: Literal['user'] = Field(default='user', init=False, frozen=True)
718
720
  parts: list[Part] = Field()
719
721
 
720
- def __init__(self, parts: Union['PartUnionDict', list['PartUnionDict']]):
722
+ def __init__(
723
+ self, parts: Union['PartUnionDict', list['PartUnionDict'], list['Part']]
724
+ ):
721
725
  from . import _transformers as t
722
726
 
723
- super().__init__(parts=t.t_parts(None, parts=parts))
727
+ super().__init__(parts=t.t_parts(parts=parts))
724
728
 
725
729
 
726
730
  class ModelContent(Content):
@@ -745,10 +749,12 @@ class ModelContent(Content):
745
749
  role: Literal['model'] = Field(default='model', init=False, frozen=True)
746
750
  parts: list[Part] = Field()
747
751
 
748
- def __init__(self, parts: Union['PartUnionDict', list['PartUnionDict']]):
752
+ def __init__(
753
+ self, parts: Union['PartUnionDict', list['PartUnionDict'], list['Part']]
754
+ ):
749
755
  from . import _transformers as t
750
756
 
751
- super().__init__(parts=t.t_parts(None, parts=parts))
757
+ super().__init__(parts=t.t_parts(parts=parts))
752
758
 
753
759
 
754
760
  class ContentDict(TypedDict, total=False):
@@ -819,17 +825,9 @@ class Schema(_common.BaseModel):
819
825
  default=None,
820
826
  description="""Optional. Pattern of the Type.STRING to restrict a string to a regular expression.""",
821
827
  )
822
- minimum: Optional[float] = Field(
823
- default=None,
824
- description="""Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER""",
825
- )
826
828
  default: Optional[Any] = Field(
827
829
  default=None, description="""Optional. Default value of the data."""
828
830
  )
829
- any_of: Optional[list['Schema']] = Field(
830
- default=None,
831
- description="""Optional. The value should be validated against any (one or more) of the subschemas in the list.""",
832
- )
833
831
  max_length: Optional[int] = Field(
834
832
  default=None,
835
833
  description="""Optional. Maximum length of the Type.STRING""",
@@ -845,14 +843,14 @@ class Schema(_common.BaseModel):
845
843
  default=None,
846
844
  description="""Optional. Minimum number of the properties for Type.OBJECT.""",
847
845
  )
848
- maximum: Optional[float] = Field(
849
- default=None,
850
- description="""Optional. Maximum value of the Type.INTEGER and Type.NUMBER""",
851
- )
852
846
  max_properties: Optional[int] = Field(
853
847
  default=None,
854
848
  description="""Optional. Maximum number of the properties for Type.OBJECT.""",
855
849
  )
850
+ any_of: Optional[list['Schema']] = Field(
851
+ default=None,
852
+ description="""Optional. The value should be validated against any (one or more) of the subschemas in the list.""",
853
+ )
856
854
  description: Optional[str] = Field(
857
855
  default=None, description="""Optional. The description of the data."""
858
856
  )
@@ -872,10 +870,18 @@ class Schema(_common.BaseModel):
872
870
  default=None,
873
871
  description="""Optional. Maximum number of the elements for Type.ARRAY.""",
874
872
  )
873
+ maximum: Optional[float] = Field(
874
+ default=None,
875
+ description="""Optional. Maximum value of the Type.INTEGER and Type.NUMBER""",
876
+ )
875
877
  min_items: Optional[int] = Field(
876
878
  default=None,
877
879
  description="""Optional. Minimum number of the elements for Type.ARRAY.""",
878
880
  )
881
+ minimum: Optional[float] = Field(
882
+ default=None,
883
+ description="""Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER""",
884
+ )
879
885
  nullable: Optional[bool] = Field(
880
886
  default=None,
881
887
  description="""Optional. Indicates if the value may be null.""",
@@ -909,15 +915,9 @@ class SchemaDict(TypedDict, total=False):
909
915
  pattern: Optional[str]
910
916
  """Optional. Pattern of the Type.STRING to restrict a string to a regular expression."""
911
917
 
912
- minimum: Optional[float]
913
- """Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER"""
914
-
915
918
  default: Optional[Any]
916
919
  """Optional. Default value of the data."""
917
920
 
918
- any_of: Optional[list['SchemaDict']]
919
- """Optional. The value should be validated against any (one or more) of the subschemas in the list."""
920
-
921
921
  max_length: Optional[int]
922
922
  """Optional. Maximum length of the Type.STRING"""
923
923
 
@@ -930,12 +930,12 @@ class SchemaDict(TypedDict, total=False):
930
930
  min_properties: Optional[int]
931
931
  """Optional. Minimum number of the properties for Type.OBJECT."""
932
932
 
933
- maximum: Optional[float]
934
- """Optional. Maximum value of the Type.INTEGER and Type.NUMBER"""
935
-
936
933
  max_properties: Optional[int]
937
934
  """Optional. Maximum number of the properties for Type.OBJECT."""
938
935
 
936
+ any_of: Optional[list['SchemaDict']]
937
+ """Optional. The value should be validated against any (one or more) of the subschemas in the list."""
938
+
939
939
  description: Optional[str]
940
940
  """Optional. The description of the data."""
941
941
 
@@ -951,9 +951,15 @@ class SchemaDict(TypedDict, total=False):
951
951
  max_items: Optional[int]
952
952
  """Optional. Maximum number of the elements for Type.ARRAY."""
953
953
 
954
+ maximum: Optional[float]
955
+ """Optional. Maximum value of the Type.INTEGER and Type.NUMBER"""
956
+
954
957
  min_items: Optional[int]
955
958
  """Optional. Minimum number of the elements for Type.ARRAY."""
956
959
 
960
+ minimum: Optional[float]
961
+ """Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER"""
962
+
957
963
  nullable: Optional[bool]
958
964
  """Optional. Indicates if the value may be null."""
959
965
 
@@ -1072,12 +1078,11 @@ class FunctionDeclaration(_common.BaseModel):
1072
1078
  type='OBJECT',
1073
1079
  properties=parameters_properties,
1074
1080
  )
1075
- if api_option == 'VERTEX_AI':
1076
- declaration.parameters.required = (
1077
- _automatic_function_calling_util._get_required_fields(
1078
- declaration.parameters
1079
- )
1080
- )
1081
+ declaration.parameters.required = (
1082
+ _automatic_function_calling_util._get_required_fields(
1083
+ declaration.parameters
1084
+ )
1085
+ )
1081
1086
  if api_option == 'GEMINI_API':
1082
1087
  return declaration
1083
1088
 
@@ -1661,7 +1666,7 @@ class File(_common.BaseModel):
1661
1666
  )
1662
1667
  sha256_hash: Optional[str] = Field(
1663
1668
  default=None,
1664
- description="""Output only. SHA-256 hash of the uploaded bytes.""",
1669
+ description="""Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format.""",
1665
1670
  )
1666
1671
  uri: Optional[str] = Field(
1667
1672
  default=None, description="""Output only. The URI of the `File`."""
@@ -1710,7 +1715,7 @@ class FileDict(TypedDict, total=False):
1710
1715
  """Output only. The timestamp of when the `File` was last updated."""
1711
1716
 
1712
1717
  sha256_hash: Optional[str]
1713
- """Output only. SHA-256 hash of the uploaded bytes."""
1718
+ """Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format."""
1714
1719
 
1715
1720
  uri: Optional[str]
1716
1721
  """Output only. The URI of the `File`."""
@@ -1736,7 +1741,7 @@ FileOrDict = Union[File, FileDict]
1736
1741
  if _is_pillow_image_imported:
1737
1742
  PartUnion = Union[File, Part, PIL_Image, str]
1738
1743
  else:
1739
- PartUnion = Union[File, Part, str]
1744
+ PartUnion = Union[File, Part, str] # type: ignore[misc]
1740
1745
 
1741
1746
 
1742
1747
  PartUnionDict = Union[PartUnion, PartDict]
@@ -3012,8 +3017,11 @@ class GenerateContentResponse(_common.BaseModel):
3012
3017
 
3013
3018
  @classmethod
3014
3019
  def _from_response(
3015
- cls, *, response: dict[str, object], kwargs: dict[str, object]
3016
- ) -> _common.BaseModel:
3020
+ cls: typing.Type[T],
3021
+ *,
3022
+ response: dict[str, object],
3023
+ kwargs: dict[str, object],
3024
+ ) -> T:
3017
3025
  result = super()._from_response(response=response, kwargs=kwargs)
3018
3026
 
3019
3027
  # Handles response schema.
@@ -3029,13 +3037,14 @@ class GenerateContentResponse(_common.BaseModel):
3029
3037
  ):
3030
3038
  # Pydantic schema.
3031
3039
  try:
3032
- result.parsed = response_schema.model_validate_json(result.text)
3040
+ if result.text is not None:
3041
+ result.parsed = response_schema.model_validate_json(result.text)
3033
3042
  # may not be a valid json per stream response
3034
3043
  except pydantic.ValidationError:
3035
3044
  pass
3036
3045
  except json.decoder.JSONDecodeError:
3037
3046
  pass
3038
- elif isinstance(response_schema, EnumMeta):
3047
+ elif isinstance(response_schema, EnumMeta) and result.text is not None:
3039
3048
  # Enum with "application/json" returns response in double quotes.
3040
3049
  enum_value = result.text.replace('"', '')
3041
3050
  try:
@@ -3044,7 +3053,7 @@ class GenerateContentResponse(_common.BaseModel):
3044
3053
  hasattr(response_schema, '__name__')
3045
3054
  and response_schema.__name__ == 'PlaceholderLiteralEnum'
3046
3055
  ):
3047
- result.parsed = str(response_schema(enum_value).name)
3056
+ result.parsed = str(response_schema(enum_value).name) # type: ignore
3048
3057
  except ValueError:
3049
3058
  pass
3050
3059
  elif isinstance(response_schema, builtin_types.GenericAlias) or isinstance(
@@ -3052,12 +3061,13 @@ class GenerateContentResponse(_common.BaseModel):
3052
3061
  ):
3053
3062
 
3054
3063
  class Placeholder(pydantic.BaseModel):
3055
- placeholder: response_schema
3064
+ placeholder: response_schema # type: ignore[valid-type]
3056
3065
 
3057
3066
  try:
3058
- parsed = {'placeholder': json.loads(result.text)}
3059
- placeholder = Placeholder.model_validate(parsed)
3060
- result.parsed = placeholder.placeholder
3067
+ if result.text is not None:
3068
+ parsed = {'placeholder': json.loads(result.text)}
3069
+ placeholder = Placeholder.model_validate(parsed)
3070
+ result.parsed = placeholder.placeholder
3061
3071
  except json.decoder.JSONDecodeError:
3062
3072
  pass
3063
3073
  except pydantic.ValidationError:
@@ -3070,7 +3080,8 @@ class GenerateContentResponse(_common.BaseModel):
3070
3080
  # want the result converted to. So just return json.
3071
3081
  # JSON schema.
3072
3082
  try:
3073
- result.parsed = json.loads(result.text)
3083
+ if result.text is not None:
3084
+ result.parsed = json.loads(result.text)
3074
3085
  # may not be a valid json per stream response
3075
3086
  except json.decoder.JSONDecodeError:
3076
3087
  pass
@@ -3080,20 +3091,22 @@ class GenerateContentResponse(_common.BaseModel):
3080
3091
  for union_type in union_types:
3081
3092
  if issubclass(union_type, pydantic.BaseModel):
3082
3093
  try:
3094
+ if result.text is not None:
3083
3095
 
3084
- class Placeholder(pydantic.BaseModel): # type: ignore[no-redef]
3085
- placeholder: response_schema
3096
+ class Placeholder(pydantic.BaseModel): # type: ignore[no-redef]
3097
+ placeholder: response_schema # type: ignore[valid-type]
3086
3098
 
3087
- parsed = {'placeholder': json.loads(result.text)}
3088
- placeholder = Placeholder.model_validate(parsed)
3089
- result.parsed = placeholder.placeholder
3099
+ parsed = {'placeholder': json.loads(result.text)}
3100
+ placeholder = Placeholder.model_validate(parsed)
3101
+ result.parsed = placeholder.placeholder
3090
3102
  except json.decoder.JSONDecodeError:
3091
3103
  pass
3092
3104
  except pydantic.ValidationError:
3093
3105
  pass
3094
3106
  else:
3095
3107
  try:
3096
- result.parsed = json.loads(result.text)
3108
+ if result.text is not None:
3109
+ result.parsed = json.loads(result.text)
3097
3110
  # may not be a valid json per stream response
3098
3111
  except json.decoder.JSONDecodeError:
3099
3112
  pass
@@ -3602,18 +3615,23 @@ class Image(_common.BaseModel):
3602
3615
  """Image."""
3603
3616
 
3604
3617
  @classmethod
3605
- def from_file(cls, *, location: str) -> 'Image':
3618
+ def from_file(
3619
+ cls, *, location: str, mime_type: Optional[str] = None
3620
+ ) -> 'Image':
3606
3621
  """Lazy-loads an image from a local file or Google Cloud Storage.
3607
3622
 
3608
3623
  Args:
3609
3624
  location: The local path or Google Cloud Storage URI from which to load
3610
3625
  the image.
3626
+ mime_type: The MIME type of the image. If not provided, the MIME type
3627
+ will be automatically determined.
3611
3628
 
3612
3629
  Returns:
3613
3630
  A loaded image as an `Image` object.
3614
3631
  """
3615
3632
  import urllib
3616
3633
  import pathlib
3634
+ import mimetypes
3617
3635
 
3618
3636
  parsed_url = urllib.parse.urlparse(location)
3619
3637
  if (
@@ -3632,7 +3650,10 @@ class Image(_common.BaseModel):
3632
3650
 
3633
3651
  # Load image from local path
3634
3652
  image_bytes = pathlib.Path(location).read_bytes()
3635
- image = cls(image_bytes=image_bytes)
3653
+
3654
+ if not mime_type:
3655
+ mime_type, _ = mimetypes.guess_type(location)
3656
+ image = cls(image_bytes=image_bytes, mime_type=mime_type)
3636
3657
  return image
3637
3658
 
3638
3659
  def show(self):
@@ -3663,6 +3684,8 @@ class Image(_common.BaseModel):
3663
3684
  'The PIL module is not available. Please install the Pillow'
3664
3685
  ' package. `pip install pillow`'
3665
3686
  )
3687
+ if self.image_bytes is None:
3688
+ raise ValueError('The image bytes are not set.')
3666
3689
  self._loaded_image = PIL_Image.open(io.BytesIO(self.image_bytes))
3667
3690
  return self._loaded_image
3668
3691
 
@@ -3674,6 +3697,8 @@ class Image(_common.BaseModel):
3674
3697
  """
3675
3698
  import pathlib
3676
3699
 
3700
+ if self.image_bytes is None:
3701
+ raise ValueError('The image bytes are not set.')
3677
3702
  pathlib.Path(location).write_bytes(self.image_bytes)
3678
3703
 
3679
3704
 
@@ -3723,6 +3748,36 @@ class ImageDict(TypedDict, total=False):
3723
3748
  ImageOrDict = Union[Image, ImageDict]
3724
3749
 
3725
3750
 
3751
+ class SafetyAttributes(_common.BaseModel):
3752
+ """Safety attributes of a GeneratedImage or the user-provided prompt."""
3753
+
3754
+ categories: Optional[list[str]] = Field(
3755
+ default=None,
3756
+ description="""List of RAI categories.
3757
+ """,
3758
+ )
3759
+ scores: Optional[list[float]] = Field(
3760
+ default=None,
3761
+ description="""List of scores of each categories.
3762
+ """,
3763
+ )
3764
+
3765
+
3766
+ class SafetyAttributesDict(TypedDict, total=False):
3767
+ """Safety attributes of a GeneratedImage or the user-provided prompt."""
3768
+
3769
+ categories: Optional[list[str]]
3770
+ """List of RAI categories.
3771
+ """
3772
+
3773
+ scores: Optional[list[float]]
3774
+ """List of scores of each categories.
3775
+ """
3776
+
3777
+
3778
+ SafetyAttributesOrDict = Union[SafetyAttributes, SafetyAttributesDict]
3779
+
3780
+
3726
3781
  class GeneratedImage(_common.BaseModel):
3727
3782
  """An output image."""
3728
3783
 
@@ -3737,6 +3792,12 @@ class GeneratedImage(_common.BaseModel):
3737
3792
  response.
3738
3793
  """,
3739
3794
  )
3795
+ safety_attributes: Optional[SafetyAttributes] = Field(
3796
+ default=None,
3797
+ description="""Safety attributes of the image. Lists of RAI categories and their
3798
+ scores of each content.
3799
+ """,
3800
+ )
3740
3801
  enhanced_prompt: Optional[str] = Field(
3741
3802
  default=None,
3742
3803
  description="""The rewritten prompt used for the image generation if the prompt
@@ -3757,6 +3818,11 @@ class GeneratedImageDict(TypedDict, total=False):
3757
3818
  response.
3758
3819
  """
3759
3820
 
3821
+ safety_attributes: Optional[SafetyAttributesDict]
3822
+ """Safety attributes of the image. Lists of RAI categories and their
3823
+ scores of each content.
3824
+ """
3825
+
3760
3826
  enhanced_prompt: Optional[str]
3761
3827
  """The rewritten prompt used for the image generation if the prompt
3762
3828
  enhancer is enabled.
@@ -4048,6 +4114,11 @@ class EditImageConfig(_common.BaseModel):
4048
4114
  default=None,
4049
4115
  description="""Describes the editing mode for the request.""",
4050
4116
  )
4117
+ base_steps: Optional[int] = Field(
4118
+ default=None,
4119
+ description="""The number of sampling steps. A higher value has better image
4120
+ quality, while a lower value has better latency.""",
4121
+ )
4051
4122
 
4052
4123
 
4053
4124
  class EditImageConfigDict(TypedDict, total=False):
@@ -4116,6 +4187,10 @@ class EditImageConfigDict(TypedDict, total=False):
4116
4187
  edit_mode: Optional[EditMode]
4117
4188
  """Describes the editing mode for the request."""
4118
4189
 
4190
+ base_steps: Optional[int]
4191
+ """The number of sampling steps. A higher value has better image
4192
+ quality, while a lower value has better latency."""
4193
+
4119
4194
 
4120
4195
  EditImageConfigOrDict = Union[EditImageConfig, EditImageConfigDict]
4121
4196
 
@@ -5074,6 +5149,11 @@ class _GenerateVideosParameters(_common.BaseModel):
5074
5149
  default=None,
5075
5150
  description="""The text prompt for generating the videos. Optional for image to video use cases.""",
5076
5151
  )
5152
+ image: Optional[Image] = Field(
5153
+ default=None,
5154
+ description="""The input image for generating the videos.
5155
+ Optional if prompt is provided.""",
5156
+ )
5077
5157
  config: Optional[GenerateVideosConfig] = Field(
5078
5158
  default=None, description="""Configuration for generating videos."""
5079
5159
  )
@@ -5089,6 +5169,10 @@ class _GenerateVideosParametersDict(TypedDict, total=False):
5089
5169
  prompt: Optional[str]
5090
5170
  """The text prompt for generating the videos. Optional for image to video use cases."""
5091
5171
 
5172
+ image: Optional[ImageDict]
5173
+ """The input image for generating the videos.
5174
+ Optional if prompt is provided."""
5175
+
5092
5176
  config: Optional[GenerateVideosConfigDict]
5093
5177
  """Configuration for generating videos."""
5094
5178
 
@@ -5130,14 +5214,16 @@ class Video(_common.BaseModel):
5130
5214
  def show(self):
5131
5215
  """Shows the video.
5132
5216
 
5217
+ If the video has no mime_type, it is assumed to be video/mp4.
5218
+
5133
5219
  This method only works in a notebook environment.
5134
5220
  """
5135
- if self.uri:
5221
+ if self.uri and not self.video_bytes:
5136
5222
  return ValueError('Showing remote videos is not supported.')
5137
5223
  if not self.video_bytes:
5138
5224
  return ValueError('Video has no bytes.')
5139
- if not self.mime_type:
5140
- return ValueError('Mime type must be provided to display video.')
5225
+
5226
+ mime_type = self.mime_type or 'video/mp4'
5141
5227
 
5142
5228
  try:
5143
5229
  from IPython import display as IPython_display
@@ -5145,8 +5231,10 @@ class Video(_common.BaseModel):
5145
5231
  IPython_display = None
5146
5232
 
5147
5233
  if IPython_display:
5148
- return IPython_display.Video(
5149
- data=self.video_bytes, mimetype=self.mime_type, embed=True
5234
+ IPython_display.display(
5235
+ IPython_display.Video(
5236
+ data=self.video_bytes, mimetype=mime_type, embed=True
5237
+ )
5150
5238
  )
5151
5239
 
5152
5240
  def __repr__(self):
google/genai/version.py CHANGED
@@ -13,4 +13,4 @@
13
13
  # limitations under the License.
14
14
  #
15
15
 
16
- __version__ = '1.4.0' # x-release-please-version
16
+ __version__ = '1.6.0' # x-release-please-version