Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/mypy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ on:
- main

env:
SPEAKEASY_VERSION: v2.959.1
SPEAKEASY_VERSION: v2.965.1

jobs:
mypy:
Expand Down
56 changes: 39 additions & 17 deletions google/genai/_gaos/types/base64fileinput.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,30 +28,52 @@
from typing_extensions import Annotated


Base64FileInput = Union[IO[bytes], PathLike[str]]
Base64FileInput = Union[bytes, bytearray, memoryview, IO[bytes], PathLike[str]]

_BYTE_FORMATS = ("B", "b", "c")


# Must stay a str subclass, returned only for bytes-like input: pydantic scores it as a strict
# but non-exact str match, so an exact `bytes` member of the same union wins for `bytes` input.
class _EncodedBase64(str):
pass


def _encode_binary(binary: Union[bytes, bytearray, memoryview]) -> str:
if isinstance(binary, memoryview):
if binary.format.lstrip("@=<>!") not in _BYTE_FORMATS:
raise ValueError(
f"Base64FileInput expected a memoryview of bytes; got item format {binary.format!r}"
)
if not binary.c_contiguous:
binary = bytes(binary)
return base64.b64encode(binary).decode("ascii")


def encode_base64_file_input(value: Any) -> Any:
"""Convert PathLike or IO[bytes] inputs to a base64 string. All standard binary streams
that inherit from io.IOBase are handled. Other values pass through.
"""Convert raw bytes-like, PathLike or IO[bytes] inputs to a base64 string. All standard
binary streams that inherit from io.IOBase are handled. Bytes-like values are always
treated as raw content and encoded; str values pass through as already-encoded base64.
Other values pass through.
"""
if isinstance(value, (PathLike, io.IOBase)):
if isinstance(value, PathLike):
with open(value, "rb") as fh:
binary = fh.read()
else:
# Restore position after reading: pydantic may validate the same stream more than once.
position = value.tell() if value.seekable() else None
binary = value.read()
if position is not None:
value.seek(position)
if isinstance(binary, str):
binary = binary.encode()
if not isinstance(binary, (bytes, bytearray)):
if isinstance(value, PathLike):
with open(value, "rb") as fh:
return _encode_binary(fh.read())
if isinstance(value, io.IOBase):
# Restore position after reading: pydantic may validate the same stream more than once.
position = value.tell() if value.seekable() else None
binary = value.read()
if position is not None:
value.seek(position)
if isinstance(binary, str):
binary = binary.encode()
if not isinstance(binary, (bytes, bytearray, memoryview)):
raise TypeError(
f"Base64FileInput expected binary IO returning bytes; got {type(binary).__name__}"
)
return base64.b64encode(binary).decode("ascii")
return _encode_binary(binary)
if isinstance(value, (bytes, bytearray, memoryview)):
return _EncodedBase64(_encode_binary(value))
return value


Expand Down
18 changes: 9 additions & 9 deletions google/genai/_gaos/utils/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,24 @@ def get_discriminator(model: Any, fieldname: str, key: str) -> str:
"""
upper_fieldname = fieldname.upper()

def to_discriminator(value: Any) -> str:
"""Convert a discriminator value to a string, using the value of enum members."""
if isinstance(value, Enum):
return f"{value.value}"
return f"{value}"

def get_field_discriminator(field: Any) -> Optional[str]:
"""Search for the discriminator attribute in a given field."""

if isinstance(field, dict):
if key in field:
return f"{field[key]}"
return to_discriminator(field[key])

if hasattr(field, fieldname):
attr = getattr(field, fieldname)
if isinstance(attr, Enum):
return f"{attr.value}"
return f"{attr}"
return to_discriminator(getattr(field, fieldname))

if hasattr(field, upper_fieldname):
attr = getattr(field, upper_fieldname)
if isinstance(attr, Enum):
return f"{attr.value}"
return f"{attr}"
return to_discriminator(getattr(field, upper_fieldname))

return None

Expand Down
7 changes: 6 additions & 1 deletion google/genai/_gaos/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ def get_body_content(req: httpx.Request) -> str:


def get_default_logger() -> Logger:
if os.getenv("GOOGLE_GENAI_DEBUG"):
if os.getenv("GOOGLE_GENAI_DEBUG", "").strip().lower() in (
"true",
"1",
"yes",
"on",
):
logging.basicConfig(level=logging.DEBUG)
return logging.getLogger("google.genai")
return NoOpLogger()
Loading
Loading