first vommit

This commit is contained in:
Till-Immer committed 2026-07-04 14:31:50 +02:00
commit a04e68bc95
4926 files changed
+764440

No files matched your search

@@ -0,0 +1,197 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import Any, TYPE_CHECKING, Callable, TypeVar
import asyncio
from .dynamic_imports import lazy_getattr, lazy_dir
_T = TypeVar("_T")
async def run_sync_in_thread(func: Callable[..., _T], *args) -> _T:
"""Run a synchronous function in a thread pool to avoid blocking the event loop."""
return await asyncio.to_thread(func, *args)
if TYPE_CHECKING:
from .annotations import get_discriminator
from .datetimes import parse_datetime
from .enums import OpenEnumMeta
from .unions import parse_open_union
from .headers import get_headers, get_response_headers
from .metadata import (
FieldMetadata,
find_metadata,
FormMetadata,
HeaderMetadata,
MultipartFormMetadata,
PathParamMetadata,
QueryParamMetadata,
RequestMetadata,
SecurityMetadata,
)
from .queryparams import get_query_params
from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig
from .requestbodies import serialize_request_body, SerializedRequestBody
from .security import get_security, get_security_from_env
from .serializers import (
get_pydantic_model,
marshal_json,
unmarshal,
unmarshal_json,
serialize_decimal,
serialize_float,
serialize_int,
stream_to_text,
stream_to_text_async,
stream_to_bytes,
stream_to_bytes_async,
validate_const,
validate_decimal,
validate_float,
validate_int,
)
from .url import generate_url, template_url, remove_suffix
from .values import (
get_global_from_env,
match_content_type,
match_status_codes,
match_response,
cast_partial,
)
from .logger import Logger, get_body_content, get_default_logger
__all__ = [
"BackoffStrategy",
"FieldMetadata",
"find_metadata",
"FormMetadata",
"generate_url",
"get_body_content",
"get_default_logger",
"get_discriminator",
"parse_datetime",
"get_global_from_env",
"get_headers",
"get_pydantic_model",
"get_query_params",
"get_response_headers",
"get_security",
"get_security_from_env",
"HeaderMetadata",
"Logger",
"marshal_json",
"match_content_type",
"match_status_codes",
"match_response",
"MultipartFormMetadata",
"OpenEnumMeta",
"parse_open_union",
"PathParamMetadata",
"QueryParamMetadata",
"remove_suffix",
"Retries",
"retry",
"retry_async",
"RetryConfig",
"RequestMetadata",
"SecurityMetadata",
"serialize_decimal",
"serialize_float",
"serialize_int",
"serialize_request_body",
"SerializedRequestBody",
"stream_to_text",
"stream_to_text_async",
"stream_to_bytes",
"stream_to_bytes_async",
"template_url",
"unmarshal",
"unmarshal_json",
"validate_decimal",
"validate_const",
"validate_float",
"validate_int",
"cast_partial",
]
_dynamic_imports: dict[str, str] = {
"BackoffStrategy": ".retries",
"FieldMetadata": ".metadata",
"find_metadata": ".metadata",
"FormMetadata": ".metadata",
"generate_url": ".url",
"get_body_content": ".logger",
"get_default_logger": ".logger",
"get_discriminator": ".annotations",
"parse_datetime": ".datetimes",
"get_global_from_env": ".values",
"get_headers": ".headers",
"get_pydantic_model": ".serializers",
"get_query_params": ".queryparams",
"get_response_headers": ".headers",
"get_security": ".security",
"get_security_from_env": ".security",
"HeaderMetadata": ".metadata",
"Logger": ".logger",
"marshal_json": ".serializers",
"match_content_type": ".values",
"match_status_codes": ".values",
"match_response": ".values",
"MultipartFormMetadata": ".metadata",
"OpenEnumMeta": ".enums",
"parse_open_union": ".unions",
"PathParamMetadata": ".metadata",
"QueryParamMetadata": ".metadata",
"remove_suffix": ".url",
"Retries": ".retries",
"retry": ".retries",
"retry_async": ".retries",
"RetryConfig": ".retries",
"RequestMetadata": ".metadata",
"SecurityMetadata": ".metadata",
"serialize_decimal": ".serializers",
"serialize_float": ".serializers",
"serialize_int": ".serializers",
"serialize_request_body": ".requestbodies",
"SerializedRequestBody": ".requestbodies",
"stream_to_text": ".serializers",
"stream_to_text_async": ".serializers",
"stream_to_bytes": ".serializers",
"stream_to_bytes_async": ".serializers",
"template_url": ".url",
"unmarshal": ".serializers",
"unmarshal_json": ".serializers",
"validate_decimal": ".serializers",
"validate_const": ".serializers",
"validate_float": ".serializers",
"validate_int": ".serializers",
"cast_partial": ".values",
}
def __getattr__(attr_name: str) -> Any:
return lazy_getattr(
attr_name, package=__package__, dynamic_imports=_dynamic_imports
)
def __dir__():
return lazy_dir(dynamic_imports=_dynamic_imports)
@@ -0,0 +1,95 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from enum import Enum
from typing import Any, Optional
def get_discriminator(model: Any, fieldname: str, key: str) -> str:
"""
Recursively search for the discriminator attribute in a model.
Args:
model (Any): The model to search within.
fieldname (str): The name of the field to search for.
key (str): The key to search for in dictionaries.
Returns:
str: The name of the discriminator attribute.
Raises:
ValueError: If the discriminator attribute is not found.
"""
upper_fieldname = fieldname.upper()
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]}"
if hasattr(field, fieldname):
attr = getattr(field, fieldname)
if isinstance(attr, Enum):
return f"{attr.value}"
return f"{attr}"
if hasattr(field, upper_fieldname):
attr = getattr(field, upper_fieldname)
if isinstance(attr, Enum):
return f"{attr.value}"
return f"{attr}"
return None
def search_nested_discriminator(obj: Any) -> Optional[str]:
"""Recursively search for discriminator in nested structures."""
# First try direct field lookup
discriminator = get_field_discriminator(obj)
if discriminator is not None:
return discriminator
# If it's a dict, search in nested values
if isinstance(obj, dict):
for value in obj.values():
if isinstance(value, list):
# Search in list items
for item in value:
nested_discriminator = search_nested_discriminator(item)
if nested_discriminator is not None:
return nested_discriminator
elif isinstance(value, dict):
# Search in nested dict
nested_discriminator = search_nested_discriminator(value)
if nested_discriminator is not None:
return nested_discriminator
return None
if isinstance(model, list):
for field in model:
discriminator = search_nested_discriminator(field)
if discriminator is not None:
return discriminator
discriminator = search_nested_discriminator(model)
if discriminator is not None:
return discriminator
raise ValueError(f"Could not find discriminator field {fieldname} in {model}")
@@ -0,0 +1,39 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from datetime import datetime
import sys
def parse_datetime(datetime_string: str) -> datetime:
"""
Convert a RFC 3339 / ISO 8601 formatted string into a datetime object.
Python versions 3.11 and later support parsing RFC 3339 directly with
datetime.fromisoformat(), but for earlier versions, this function
encapsulates the necessary extra logic.
"""
# Python 3.11 and later can parse RFC 3339 directly
if sys.version_info >= (3, 11):
return datetime.fromisoformat(datetime_string)
# For Python 3.10 and earlier, a common ValueError is trailing 'Z' suffix,
# so fix that upfront.
if datetime_string.endswith("Z"):
datetime_string = datetime_string[:-1] + "+00:00"
return datetime.fromisoformat(datetime_string)
@@ -0,0 +1,71 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from importlib import import_module, util
import builtins
import sys
def dynamic_import(package, modname, retries=3):
"""Import a module relative to package, retrying on KeyError from half-initialized modules."""
for attempt in range(retries):
try:
return import_module(modname, package)
except KeyError:
resolved = util.resolve_name(modname, package)
sys.modules.pop(resolved, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def lazy_getattr(attr_name, *, package, dynamic_imports, sub_packages=None):
"""Module-level __getattr__ that lazily loads from a dynamic_imports mapping.
Args:
attr_name: The attribute being looked up.
package: The caller's __package__ (for relative imports).
dynamic_imports: Dict mapping attribute names to relative module paths.
sub_packages: Optional list of subpackage names to lazy-load.
"""
module_name = dynamic_imports.get(attr_name)
if module_name is not None:
try:
module = dynamic_import(package, module_name)
return getattr(module, attr_name)
except ImportError as e:
raise ImportError(
f"Failed to import {attr_name} from {module_name}: {e}"
) from e
except AttributeError as e:
raise AttributeError(
f"Failed to get {attr_name} from {module_name}: {e}"
) from e
if sub_packages and attr_name in sub_packages:
return import_module(f".{attr_name}", package)
raise AttributeError(f"module '{package}' has no attribute '{attr_name}'")
def lazy_dir(*, dynamic_imports, sub_packages=None):
"""Module-level __dir__ that lists lazily-loadable attributes."""
lazy_attrs = builtins.list(dynamic_imports.keys())
if sub_packages:
lazy_attrs.extend(sub_packages)
return builtins.sorted(lazy_attrs)
@@ -0,0 +1,150 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import enum
import sys
from typing import Any
from pydantic_core import core_schema
class OpenEnumMeta(enum.EnumMeta):
# The __call__ method `boundary` kwarg was added in 3.11 and must be present
# for pyright. Refer also: https://github.com/pylint-dev/pylint/issues/9622
# pylint: disable=unexpected-keyword-arg
# The __call__ method `values` varg must be named for pyright.
# pylint: disable=keyword-arg-before-vararg
if sys.version_info >= (3, 11):
def __call__(
cls, value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None
):
# The `type` kwarg also happens to be a built-in that pylint flags as
# redeclared. Safe to ignore this lint rule with this scope.
# pylint: disable=redefined-builtin
if names is not None:
return super().__call__(
value,
names=names,
*values,
module=module,
qualname=qualname,
type=type,
start=start,
boundary=boundary,
)
try:
return super().__call__(
value,
names=names, # pyright: ignore[reportArgumentType]
*values,
module=module,
qualname=qualname,
type=type,
start=start,
boundary=boundary,
)
except ValueError:
return value
else:
def __call__(
cls, value, names=None, *, module=None, qualname=None, type=None, start=1
):
# The `type` kwarg also happens to be a built-in that pylint flags as
# redeclared. Safe to ignore this lint rule with this scope.
# pylint: disable=redefined-builtin
if names is not None:
return super().__call__(
value,
names=names,
module=module,
qualname=qualname,
type=type,
start=start,
)
try:
return super().__call__(
value,
names=names, # pyright: ignore[reportArgumentType]
module=module,
qualname=qualname,
type=type,
start=start,
)
except ValueError:
return value
def __new__(mcs, name, bases, namespace, **kwargs):
cls = super().__new__(mcs, name, bases, namespace, **kwargs)
# Add __get_pydantic_core_schema__ to make open enums work correctly
# in union discrimination. In strict mode (used by Pydantic for unions),
# only known enum values match. In lax mode, unknown values are accepted.
def __get_pydantic_core_schema__(
cls_inner: Any, _source_type: Any, _handler: Any
) -> core_schema.CoreSchema:
# Create a validator that only accepts known enum values (for strict mode)
def validate_strict(v: Any) -> Any:
if isinstance(v, cls_inner):
return v
# Use the parent EnumMeta's __call__ which raises ValueError for unknown values
return enum.EnumMeta.__call__(cls_inner, v)
# Create a lax validator that accepts unknown values
def validate_lax(v: Any) -> Any:
if isinstance(v, cls_inner):
return v
try:
return enum.EnumMeta.__call__(cls_inner, v)
except ValueError:
# Return the raw value for unknown enum values
return v
# Determine the base type schema (str or int)
is_int_enum = False
for base in cls_inner.__mro__:
if base is int:
is_int_enum = True
break
if base is str:
break
base_schema = (
core_schema.int_schema()
if is_int_enum
else core_schema.str_schema()
)
# Use lax_or_strict_schema:
# - strict mode: only known enum values match (raises ValueError for unknown)
# - lax mode: accept any value, return enum member or raw value
return core_schema.lax_or_strict_schema(
lax_schema=core_schema.chain_schema(
[base_schema, core_schema.no_info_plain_validator_function(validate_lax)]
),
strict_schema=core_schema.chain_schema(
[base_schema, core_schema.no_info_plain_validator_function(validate_strict)]
),
)
setattr(cls, "__get_pydantic_core_schema__", classmethod(__get_pydantic_core_schema__))
return cls
@@ -0,0 +1,342 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import re
import json
from dataclasses import dataclass, asdict
from typing import (
Any,
Callable,
Generic,
List,
TypeVar,
Optional,
Generator,
AsyncGenerator,
Tuple,
)
import httpx
T = TypeVar("T")
class Stream(Generic[T]):
# Holds a reference to the SDK client to avoid it being garbage collected
# and cause termination of the underlying httpx client.
client_ref: Optional[object]
response: httpx.Response
generator: Generator[T, None, None]
_closed: bool
def __init__(
self,
response: httpx.Response,
decoder: Callable[[str], T],
sentinel: Optional[str] = None,
client_ref: Optional[object] = None,
data_required: bool = True,
):
self.response = response
self.generator = stream_events(
response, decoder, sentinel, data_required=data_required
)
self.client_ref = client_ref
self._closed = False
def __iter__(self):
return self
def __next__(self):
if self._closed:
raise StopIteration
return next(self.generator)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
self._closed = True
self.response.close()
class AsyncStream(Generic[T]):
# Holds a reference to the SDK client to avoid it being garbage collected
# and cause termination of the underlying httpx client.
client_ref: Optional[object]
response: httpx.Response
generator: AsyncGenerator[T, None]
_closed: bool
def __init__(
self,
response: httpx.Response,
decoder: Callable[[str], T],
sentinel: Optional[str] = None,
client_ref: Optional[object] = None,
data_required: bool = True,
):
self.response = response
self.generator = stream_events_async(
response, decoder, sentinel, data_required=data_required
)
self.client_ref = client_ref
self._closed = False
def __aiter__(self):
return self
async def __anext__(self):
if self._closed:
raise StopAsyncIteration
return await self.generator.__anext__()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
async def close(self):
self._closed = True
await self.response.aclose()
@dataclass
class ServerEvent:
id: Optional[str] = None
event: Optional[str] = None
data: Any = None
retry: Optional[int] = None
MESSAGE_BOUNDARIES = [
b"\r\n\r\n",
b"\r\n\r",
b"\r\n\n",
b"\r\r\n",
b"\n\r\n",
b"\r\r",
b"\n\r",
b"\n\n",
]
MAX_BOUNDARY_LEN = max(len(b) for b in MESSAGE_BOUNDARIES)
UTF8_BOM = b"\xef\xbb\xbf"
async def stream_events_async(
response: httpx.Response,
decoder: Callable[[str], T],
sentinel: Optional[str] = None,
data_required: bool = True,
) -> AsyncGenerator[T, None]:
try:
buffer = bytearray()
position = 0
event_id: Optional[str] = None
async for chunk in response.aiter_bytes():
if len(buffer) == 0 and chunk.startswith(UTF8_BOM):
chunk = chunk[len(UTF8_BOM) :]
old_len = len(buffer)
buffer += chunk
search_start = max(position, old_len - MAX_BOUNDARY_LEN + 1)
for i in range(search_start, len(buffer)):
char = buffer[i : i + 1]
seq: Optional[bytes] = None
if char in [b"\r", b"\n"]:
for boundary in MESSAGE_BOUNDARIES:
seq = _peek_sequence(i, buffer, boundary)
if seq is not None:
break
if seq is None:
continue
block = buffer[position:i]
position = i + len(seq)
event, discard, event_id = _parse_event(
raw=block,
decoder=decoder,
sentinel=sentinel,
event_id=event_id,
data_required=data_required,
)
if event is not None:
yield event
if discard:
return
if position > 0:
buffer = buffer[position:]
position = 0
event, discard, _ = _parse_event(
raw=buffer,
decoder=decoder,
sentinel=sentinel,
event_id=event_id,
data_required=data_required,
)
if event is not None:
yield event
finally:
await response.aclose()
def stream_events(
response: httpx.Response,
decoder: Callable[[str], T],
sentinel: Optional[str] = None,
data_required: bool = True,
) -> Generator[T, None, None]:
try:
buffer = bytearray()
position = 0
event_id: Optional[str] = None
for chunk in response.iter_bytes():
if len(buffer) == 0 and chunk.startswith(UTF8_BOM):
chunk = chunk[len(UTF8_BOM) :]
old_len = len(buffer)
buffer += chunk
search_start = max(position, old_len - MAX_BOUNDARY_LEN + 1)
for i in range(search_start, len(buffer)):
char = buffer[i : i + 1]
seq: Optional[bytes] = None
if char in [b"\r", b"\n"]:
for boundary in MESSAGE_BOUNDARIES:
seq = _peek_sequence(i, buffer, boundary)
if seq is not None:
break
if seq is None:
continue
block = buffer[position:i]
position = i + len(seq)
event, discard, event_id = _parse_event(
raw=block,
decoder=decoder,
sentinel=sentinel,
event_id=event_id,
data_required=data_required,
)
if event is not None:
yield event
if discard:
return
if position > 0:
buffer = buffer[position:]
position = 0
event, discard, _ = _parse_event(
raw=buffer,
decoder=decoder,
sentinel=sentinel,
event_id=event_id,
data_required=data_required,
)
if event is not None:
yield event
finally:
response.close()
def _parse_event(
*,
raw: bytearray,
decoder: Callable[[str], T],
sentinel: Optional[str] = None,
event_id: Optional[str] = None,
data_required: bool = True,
) -> Tuple[Optional[T], bool, Optional[str]]:
block = raw.decode()
lines = re.split(r"\r?\n|\r", block)
publish = False
event = ServerEvent()
data_parts: List[str] = []
for line in lines:
if not line:
continue
delim = line.find(":")
if delim == 0:
continue
field = line
value = ""
if delim > 0:
field = line[0:delim]
value = line[delim + 1 :] if delim < len(line) - 1 else ""
if len(value) and value[0] == " ":
value = value[1:]
if field == "event":
event.event = value
publish = True
elif field == "data":
data_parts.append(value)
publish = True
elif field == "id":
publish = True
if "\x00" not in value:
event_id = value
elif field == "retry":
if value.isdigit():
event.retry = int(value)
publish = True
event.id = event_id
has_data = bool(data_parts)
data = "\n".join(data_parts)
if sentinel and has_data and data == sentinel:
return None, True, event_id
# Skip data-less events when data is required
if not has_data and publish and data_required:
return None, False, event_id
if has_data:
try:
event.data = json.loads(data)
except json.JSONDecodeError:
event.data = data
out = None
if publish:
out_dict = {
k: v
for k, v in asdict(event).items()
if v is not None or (k == "data" and has_data)
}
out = decoder(json.dumps(out_dict))
return out, False, event_id
def _peek_sequence(position: int, buffer: bytearray, sequence: bytes):
if len(sequence) > (len(buffer) - position):
return None
for i, seq in enumerate(sequence):
if buffer[position + i] != seq:
return None
return sequence
@@ -0,0 +1,255 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import io
from typing import (
Any,
Dict,
get_type_hints,
List,
Tuple,
)
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from .serializers import marshal_json
from .metadata import (
FormMetadata,
MultipartFormMetadata,
find_field_metadata,
)
from .values import _is_set, _val_to_string
def _populate_form(
field_name: str,
explode: bool,
obj: Any,
delimiter: str,
form: Dict[str, List[str]],
):
if not _is_set(obj):
return form
if isinstance(obj, BaseModel):
items = []
obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields
for name in obj_fields:
obj_field = obj_fields[name]
obj_field_name = obj_field.alias if obj_field.alias is not None else name
if obj_field_name == "":
continue
val = getattr(obj, name)
if not _is_set(val):
continue
if explode:
form[obj_field_name] = [_val_to_string(val)]
else:
items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}")
if len(items) > 0:
form[field_name] = [delimiter.join(items)]
elif isinstance(obj, Dict):
items = []
for key, value in obj.items():
if not _is_set(value):
continue
if explode:
form[key] = [_val_to_string(value)]
else:
items.append(f"{key}{delimiter}{_val_to_string(value)}")
if len(items) > 0:
form[field_name] = [delimiter.join(items)]
elif isinstance(obj, List):
items = []
for value in obj:
if not _is_set(value):
continue
if explode:
if not field_name in form:
form[field_name] = []
form[field_name].append(_val_to_string(value))
else:
items.append(_val_to_string(value))
if len(items) > 0:
form[field_name] = [delimiter.join([str(item) for item in items])]
else:
form[field_name] = [_val_to_string(obj)]
return form
def _extract_file_properties(file_obj: Any) -> Tuple[str, Any, Any]:
"""Extract file name, content, and content type from a file object."""
file_fields: Dict[str, FieldInfo] = file_obj.__class__.model_fields
file_name = ""
content = None
content_type = None
for file_field_name in file_fields:
file_field = file_fields[file_field_name]
file_metadata = find_field_metadata(file_field, MultipartFormMetadata)
if file_metadata is None:
continue
if file_metadata.content:
content = getattr(file_obj, file_field_name, None)
if isinstance(content, io.TextIOBase):
content = content.read().encode(
getattr(content, "encoding", None) or "utf-8"
)
elif file_field_name == "content_type":
content_type = getattr(file_obj, file_field_name, None)
else:
file_name = getattr(file_obj, file_field_name)
if file_name == "" or content is None:
raise ValueError("invalid multipart/form-data file")
return file_name, content, content_type
def serialize_multipart_form(
media_type: str, request: Any
) -> Tuple[str, Dict[str, Any], List[Tuple[str, Any]]]:
form: Dict[str, Any] = {}
files: List[Tuple[str, Any]] = []
if not isinstance(request, BaseModel):
raise TypeError("invalid request body type")
request_fields: Dict[str, FieldInfo] = request.__class__.model_fields
request_field_types = get_type_hints(request.__class__)
for name in request_fields:
field = request_fields[name]
val = getattr(request, name)
if not _is_set(val):
continue
field_metadata = find_field_metadata(field, MultipartFormMetadata)
if not field_metadata:
continue
f_name = field.alias if field.alias else name
if field_metadata.file:
if isinstance(val, List):
# Handle array of files
array_field_name = f_name
for file_obj in val:
if not _is_set(file_obj):
continue
file_name, content, content_type = _extract_file_properties(
file_obj
)
if content_type is not None:
files.append(
(array_field_name, (file_name, content, content_type))
)
else:
files.append((array_field_name, (file_name, content)))
else:
# Handle single file
file_name, content, content_type = _extract_file_properties(val)
if content_type is not None:
files.append((f_name, (file_name, content, content_type)))
else:
files.append((f_name, (file_name, content)))
elif field_metadata.json:
files.append(
(
f_name,
(
None,
marshal_json(val, request_field_types[name]),
"application/json",
),
)
)
else:
if isinstance(val, List):
values = []
for value in val:
if not _is_set(value):
continue
values.append(_val_to_string(value))
array_field_name = f_name
form[array_field_name] = values
else:
form[f_name] = _val_to_string(val)
return media_type, form, files
def serialize_form_data(data: Any) -> Dict[str, Any]:
form: Dict[str, List[str]] = {}
if isinstance(data, BaseModel):
data_fields: Dict[str, FieldInfo] = data.__class__.model_fields
data_field_types = get_type_hints(data.__class__)
for name in data_fields:
field = data_fields[name]
val = getattr(data, name)
if not _is_set(val):
continue
metadata = find_field_metadata(field, FormMetadata)
if metadata is None:
continue
f_name = field.alias if field.alias is not None else name
if metadata.json:
form[f_name] = [marshal_json(val, data_field_types[name])]
else:
if metadata.style == "form":
_populate_form(
f_name,
metadata.explode,
val,
",",
form,
)
else:
raise ValueError(f"Invalid form style for field {name}")
elif isinstance(data, Dict):
for key, value in data.items():
if _is_set(value):
form[key] = [_val_to_string(value)]
else:
raise TypeError(f"Invalid request body type {type(data)} for form data")
return form
@@ -0,0 +1,152 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import (
Any,
Dict,
List,
Optional,
)
from httpx import Headers
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from .metadata import (
HeaderMetadata,
find_field_metadata,
)
from .values import _is_set, _populate_from_globals, _val_to_string
def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]:
headers: Dict[str, str] = {}
globals_already_populated = []
if _is_set(headers_params):
globals_already_populated = _populate_headers(headers_params, gbls, headers, [])
if _is_set(gbls):
_populate_headers(gbls, None, headers, globals_already_populated)
return headers
def _populate_headers(
headers_params: Any,
gbls: Any,
header_values: Dict[str, str],
skip_fields: List[str],
) -> List[str]:
globals_already_populated: List[str] = []
if not isinstance(headers_params, BaseModel):
return globals_already_populated
param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields
for name in param_fields:
if name in skip_fields:
continue
field = param_fields[name]
f_name = field.alias if field.alias is not None else name
metadata = find_field_metadata(field, HeaderMetadata)
if metadata is None:
continue
value, global_found = _populate_from_globals(
name, getattr(headers_params, name), HeaderMetadata, gbls
)
if global_found:
globals_already_populated.append(name)
value = _serialize_header(metadata.explode, value)
if value != "":
header_values[f_name] = value
return globals_already_populated
def _serialize_header(explode: bool, obj: Any) -> str:
if not _is_set(obj):
return ""
if isinstance(obj, BaseModel):
items = []
obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields
for name in obj_fields:
obj_field = obj_fields[name]
obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata)
if not obj_param_metadata:
continue
f_name = obj_field.alias if obj_field.alias is not None else name
val = getattr(obj, name)
if not _is_set(val):
continue
if explode:
items.append(f"{f_name}={_val_to_string(val)}")
else:
items.append(f_name)
items.append(_val_to_string(val))
if len(items) > 0:
return ",".join(items)
elif isinstance(obj, Dict):
items = []
for key, value in obj.items():
if not _is_set(value):
continue
if explode:
items.append(f"{key}={_val_to_string(value)}")
else:
items.append(key)
items.append(_val_to_string(value))
if len(items) > 0:
return ",".join([str(item) for item in items])
elif isinstance(obj, List):
items = []
for value in obj:
if not _is_set(value):
continue
items.append(_val_to_string(value))
if len(items) > 0:
return ",".join(items)
elif _is_set(obj):
return f"{_val_to_string(obj)}"
return ""
def get_response_headers(headers: Headers) -> Dict[str, List[str]]:
res: Dict[str, List[str]] = {}
for k, v in headers.items():
if not k in res:
res[k] = []
res[k].append(v)
return res
@@ -0,0 +1,43 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import httpx
import logging
import os
from typing import Any, Protocol
class Logger(Protocol):
def debug(self, msg: str, *args: Any, **kwargs: Any) -> None:
pass
class NoOpLogger:
def debug(self, msg: str, *args: Any, **kwargs: Any) -> None:
pass
def get_body_content(req: httpx.Request) -> str:
return "<streaming body>" if not hasattr(req, "_content") else str(req.content)
def get_default_logger() -> Logger:
if os.getenv("GOOGLE_GENAI_DEBUG"):
logging.basicConfig(level=logging.DEBUG)
return logging.getLogger("google.genai")
return NoOpLogger()
@@ -0,0 +1,135 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import Optional, Type, TypeVar, Union
from dataclasses import dataclass
from pydantic.fields import FieldInfo
T = TypeVar("T")
@dataclass
class SecurityMetadata:
option: bool = False
scheme: bool = False
scheme_type: Optional[str] = None
sub_type: Optional[str] = None
field_name: Optional[str] = None
composite: bool = False
def get_field_name(self, default: str) -> str:
return self.field_name or default
@dataclass
class ParamMetadata:
serialization: Optional[str] = None
style: str = "simple"
explode: bool = False
@dataclass
class PathParamMetadata(ParamMetadata):
pass
@dataclass
class QueryParamMetadata(ParamMetadata):
style: str = "form"
explode: bool = True
@dataclass
class HeaderMetadata(ParamMetadata):
pass
@dataclass
class RequestMetadata:
media_type: str = "application/octet-stream"
@dataclass
class MultipartFormMetadata:
file: bool = False
content: bool = False
json: bool = False
@dataclass
class FormMetadata:
json: bool = False
style: str = "form"
explode: bool = True
class FieldMetadata:
security: Optional[SecurityMetadata] = None
path: Optional[PathParamMetadata] = None
query: Optional[QueryParamMetadata] = None
header: Optional[HeaderMetadata] = None
request: Optional[RequestMetadata] = None
form: Optional[FormMetadata] = None
multipart: Optional[MultipartFormMetadata] = None
def __init__(
self,
security: Optional[SecurityMetadata] = None,
path: Optional[Union[PathParamMetadata, bool]] = None,
query: Optional[Union[QueryParamMetadata, bool]] = None,
header: Optional[Union[HeaderMetadata, bool]] = None,
request: Optional[Union[RequestMetadata, bool]] = None,
form: Optional[Union[FormMetadata, bool]] = None,
multipart: Optional[Union[MultipartFormMetadata, bool]] = None,
):
self.security = security
self.path = PathParamMetadata() if isinstance(path, bool) else path
self.query = QueryParamMetadata() if isinstance(query, bool) else query
self.header = HeaderMetadata() if isinstance(header, bool) else header
self.request = RequestMetadata() if isinstance(request, bool) else request
self.form = FormMetadata() if isinstance(form, bool) else form
self.multipart = (
MultipartFormMetadata() if isinstance(multipart, bool) else multipart
)
def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]:
metadata = find_metadata(field_info, FieldMetadata)
if not metadata:
return None
fields = metadata.__dict__
for field in fields:
if isinstance(fields[field], metadata_type):
return fields[field]
return None
def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]:
metadata = field_info.metadata
if not metadata:
return None
for md in metadata:
if isinstance(md, metadata_type):
return md
return None
@@ -0,0 +1,233 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import (
Any,
Dict,
get_type_hints,
List,
Optional,
)
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from .metadata import (
QueryParamMetadata,
find_field_metadata,
)
from .values import (
_get_serialized_params,
_is_set,
_populate_from_globals,
_val_to_string,
)
from .forms import _populate_form
def get_query_params(
query_params: Any,
gbls: Optional[Any] = None,
allow_empty_value: Optional[List[str]] = None,
) -> Dict[str, List[str]]:
params: Dict[str, List[str]] = {}
globals_already_populated = _populate_query_params(query_params, gbls, params, [], allow_empty_value)
if _is_set(gbls):
_populate_query_params(gbls, None, params, globals_already_populated, allow_empty_value)
return params
def _populate_query_params(
query_params: Any,
gbls: Any,
query_param_values: Dict[str, List[str]],
skip_fields: List[str],
allow_empty_value: Optional[List[str]] = None,
) -> List[str]:
globals_already_populated: List[str] = []
if not isinstance(query_params, BaseModel):
return globals_already_populated
param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields
param_field_types = get_type_hints(query_params.__class__)
for name in param_fields:
if name in skip_fields:
continue
field = param_fields[name]
metadata = find_field_metadata(field, QueryParamMetadata)
if not metadata:
continue
value = getattr(query_params, name) if _is_set(query_params) else None
value, global_found = _populate_from_globals(
name, value, QueryParamMetadata, gbls
)
if global_found:
globals_already_populated.append(name)
f_name = field.alias if field.alias is not None else name
allow_empty_set = set(allow_empty_value or [])
should_include_empty = f_name in allow_empty_set and (
value is None or value == [] or value == ""
)
if should_include_empty:
query_param_values[f_name] = [""]
continue
serialization = metadata.serialization
if serialization is not None:
serialized_parms = _get_serialized_params(
metadata, f_name, value, param_field_types[name]
)
for key, value in serialized_parms.items():
if key in query_param_values:
query_param_values[key].extend(value)
else:
query_param_values[key] = [value]
else:
style = metadata.style
if style == "deepObject":
_populate_deep_object_query_params(f_name, value, query_param_values)
elif style == "form":
_populate_delimited_query_params(
metadata, f_name, value, ",", query_param_values
)
elif style == "pipeDelimited":
_populate_delimited_query_params(
metadata, f_name, value, "|", query_param_values
)
else:
raise NotImplementedError(
f"query param style {style} not yet supported"
)
return globals_already_populated
def _populate_deep_object_query_params(
field_name: str,
obj: Any,
params: Dict[str, List[str]],
):
if not _is_set(obj):
return
if isinstance(obj, BaseModel):
_populate_deep_object_query_params_basemodel(field_name, obj, params)
elif isinstance(obj, Dict):
_populate_deep_object_query_params_dict(field_name, obj, params)
def _populate_deep_object_query_params_basemodel(
prior_params_key: str,
obj: Any,
params: Dict[str, List[str]],
):
if not _is_set(obj) or not isinstance(obj, BaseModel):
return
obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields
for name in obj_fields:
obj_field = obj_fields[name]
f_name = obj_field.alias if obj_field.alias is not None else name
params_key = f"{prior_params_key}[{f_name}]"
obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata)
if not _is_set(obj_param_metadata):
continue
obj_val = getattr(obj, name)
if not _is_set(obj_val):
continue
if isinstance(obj_val, BaseModel):
_populate_deep_object_query_params_basemodel(params_key, obj_val, params)
elif isinstance(obj_val, Dict):
_populate_deep_object_query_params_dict(params_key, obj_val, params)
elif isinstance(obj_val, List):
_populate_deep_object_query_params_list(params_key, obj_val, params)
else:
params[params_key] = [_val_to_string(obj_val)]
def _populate_deep_object_query_params_dict(
prior_params_key: str,
value: Dict,
params: Dict[str, List[str]],
):
if not _is_set(value):
return
for key, val in value.items():
if not _is_set(val):
continue
params_key = f"{prior_params_key}[{key}]"
if isinstance(val, BaseModel):
_populate_deep_object_query_params_basemodel(params_key, val, params)
elif isinstance(val, Dict):
_populate_deep_object_query_params_dict(params_key, val, params)
elif isinstance(val, List):
_populate_deep_object_query_params_list(params_key, val, params)
else:
params[params_key] = [_val_to_string(val)]
def _populate_deep_object_query_params_list(
params_key: str,
value: List,
params: Dict[str, List[str]],
):
if not _is_set(value):
return
for val in value:
if not _is_set(val):
continue
if params.get(params_key) is None:
params[params_key] = []
params[params_key].append(_val_to_string(val))
def _populate_delimited_query_params(
metadata: QueryParamMetadata,
field_name: str,
obj: Any,
delimiter: str,
query_param_values: Dict[str, List[str]],
):
_populate_form(
field_name,
metadata.explode,
obj,
delimiter,
query_param_values,
)
@@ -0,0 +1,92 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import io
import json
from dataclasses import dataclass
import re
from typing import (
Any,
Mapping,
Optional,
)
from .forms import serialize_form_data, serialize_multipart_form
from .serializers import marshal_json
SERIALIZATION_METHOD_TO_CONTENT_TYPE = {
"json": "application/json",
"form": "application/x-www-form-urlencoded",
"multipart": "multipart/form-data",
"raw": "application/octet-stream",
"string": "text/plain",
}
@dataclass
class SerializedRequestBody:
media_type: Optional[str] = None
content: Optional[Any] = None
data: Optional[Any] = None
files: Optional[Any] = None
def serialize_request_body(
request_body: Any,
nullable: bool,
optional: bool,
serialization_method: str,
request_body_type,
extra_body: Optional[Mapping[str, Any]] = None,
) -> Optional[SerializedRequestBody]:
if request_body is None:
if not nullable and optional:
return None
media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method]
serialized_request_body = SerializedRequestBody(media_type)
if re.match(r"^(application|text)\/([^+]+\+)*json.*", media_type) is not None:
serialized_request_body.content = marshal_json(request_body, request_body_type)
if extra_body is not None:
body = json.loads(serialized_request_body.content or "{}")
if not isinstance(body, dict):
raise TypeError("extra_body can only be merged into JSON object bodies")
body.update(extra_body)
serialized_request_body.content = json.dumps(body, separators=(",", ":"))
elif re.match(r"^multipart\/.*", media_type) is not None:
(
serialized_request_body.media_type,
serialized_request_body.data,
serialized_request_body.files,
) = serialize_multipart_form(media_type, request_body)
elif re.match(r"^application\/x-www-form-urlencoded.*", media_type) is not None:
serialized_request_body.data = serialize_form_data(request_body)
elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)):
serialized_request_body.content = request_body
elif isinstance(request_body, str):
serialized_request_body.content = request_body
else:
raise TypeError(
f"invalid request body type {type(request_body)} for mediaType {media_type}"
)
return serialized_request_body
@@ -0,0 +1,764 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
import functools
import json
from datetime import timedelta
from types import TracebackType
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Generic,
Iterator,
Literal,
Mapping,
NoReturn,
Optional,
ParamSpec,
Tuple,
Type,
TypeVar,
Union,
cast,
get_args,
get_origin,
overload,
)
import httpx
from pydantic import BaseModel
from typing_extensions import TypeAliasType
from .._version import __response_mode_header__
from .._hooks.types import AfterParseErrorContext
from .eventstreaming import Stream, AsyncStream
from .unmarshal_json_response import unmarshal_json_response
P = ParamSpec("P")
T = TypeVar("T")
U = TypeVar("U")
ResponseT = TypeVar("ResponseT", bound="_APIResponseBase[Any]")
AsyncResponseT = TypeVar("AsyncResponseT", bound="_AsyncAPIResponseBase[Any]")
ResponseMode = Literal["buffered", "raw_stream", "event_stream"]
ResponseModeHeader = Literal["parsed", "raw", "streaming"]
_DEFAULT_PARSE_KEY = object()
_PARSED_RESPONSE_MODE: ResponseModeHeader = "parsed"
_RAW_RESPONSE_MODE: ResponseModeHeader = "raw"
_STREAMING_RESPONSE_MODE: ResponseModeHeader = "streaming"
# Internal marker header set by the raw/streaming response helpers and removed
# before the request is sent, so it never reaches the wire.
_RESPONSE_MODE_HEADER = __response_mode_header__.lower()
def raise_parse_error(
hooks: Optional[Any],
hook_ctx: Optional[AfterParseErrorContext],
response: httpx.Response,
exc: Exception,
) -> NoReturn:
"""Raise the hook-substituted parse error.
When hooks return the same exception instance, preserve its existing cause
chain instead of overwriting it with `raise exc from exc`.
"""
parse_error = exc
if hooks is not None and hook_ctx is not None:
parse_error = hooks.after_parse_error(hook_ctx, response, exc)
if parse_error is exc:
raise exc.with_traceback(exc.__traceback__)
raise parse_error from exc
async def raise_parse_error_async(
async_hooks: Optional[Any],
hooks: Optional[Any],
hook_ctx: Optional[AfterParseErrorContext],
response: httpx.Response,
exc: Exception,
) -> NoReturn:
"""Raise the async hook-substituted parse error."""
parse_error = exc
if async_hooks is not None and hook_ctx is not None:
parse_error = await async_hooks.after_parse_error(hook_ctx, response, exc)
elif hooks is not None and hook_ctx is not None:
parse_error = hooks.after_parse_error(hook_ctx, response, exc)
if parse_error is exc:
raise exc.with_traceback(exc.__traceback__)
raise parse_error from exc
def _unwrap_type(t: Any) -> Any:
"""Strip ``TypeAliasType('Name', T)`` and ``Annotated[T, ...]`` wrappers."""
if isinstance(t, TypeAliasType):
t = t.__value__
if get_origin(t) is not None and hasattr(t, "__metadata__"):
t = t.__origin__
return t
def _event_stream_origin(
to: Any,
) -> Optional[
Union[
Type[Stream[Any]],
Type[AsyncStream[Any]],
]
]:
"""Resolve ``to`` to its underlying ``Stream`` / ``AsyncStream``
subclass, or ``None`` if it isn't one. Accepts subclasses, generic
parametrizations (``Stream[T]``), ``Annotated[...]``, and
``TypeAliasType``."""
unwrapped = _unwrap_type(to)
origin = get_origin(unwrapped) or unwrapped
if isinstance(origin, type) and issubclass(origin, (Stream, AsyncStream)):
return origin
return None
def _extract_stream_chunk_type(to: Any) -> Optional[type]:
"""Recover the chunk type ``T`` from ``Stream[T]`` or from a
pre-bound subclass ``class MyStream(Stream[T]): ...``."""
unwrapped = _unwrap_type(to)
args = get_args(unwrapped)
if args:
return args[0]
for base in getattr(unwrapped, "__orig_bases__", ()):
base_args = get_args(base)
if base_args:
return base_args[0]
return None
def _can_honor_event_stream(to: Any, response: httpx.Response) -> bool:
"""True when spec-declared ``event_stream`` is confirmed by caller intent
or wire Content-Type. ``to=None`` defers to the spec-driven default parser
and must not be demoted — preserves streaming semantics when the wire
Content-Type is unreliable (proxy strip, server misconfig)."""
if to is None:
return True
if _event_stream_origin(to) is not None:
return True
content_type = response.headers.get("content-type", "")
media_type = content_type.partition(";")[0].strip().lower()
return media_type == "text/event-stream"
def _build_event_stream(
*,
to: Any,
decoder: Optional[Callable[[str], Any]],
sentinel: Optional[str],
response: httpx.Response,
client_ref: Optional[object],
async_: bool,
) -> Any:
"""Dispatch ``parse(to=Stream)`` to a typed SSE iterator."""
base_class = AsyncStream if async_ else Stream
origin = _event_stream_origin(to)
if origin is None or not issubclass(origin, base_class):
iter_methods = (
"aiter_lines() / aiter_bytes()" if async_ else "iter_lines() / iter_bytes()"
)
raise TypeError(
f"parse(to=...) on SSE responses must use {base_class.__name__}[T]; got {to!r}. Iterate via {iter_methods} for raw access."
)
if decoder is not None:
resolved_decoder: Callable[[str], Any] = decoder
else:
chunk_t = _extract_stream_chunk_type(to)
if chunk_t is None:
raise TypeError(
f"parse(to={base_class.__name__}[T]) requires a type parameter."
)
if not (isinstance(chunk_t, type) and issubclass(chunk_t, BaseModel)):
raise TypeError(
f"parse(to={base_class.__name__}[T]) requires T to be a BaseModel when decoder= is not supplied; got {chunk_t!r}."
)
def _synthesized_decoder(raw: str, _t: Any = chunk_t) -> Any:
envelope = json.loads(raw)
if not isinstance(envelope, dict) or "data" not in envelope:
raise ValueError(
f"Synthesized SSE decoder expected an envelope of shape {{'data': ...}}, got {envelope!r}. Pass decoder=<fn> to parse(...) to handle non-standard envelopes."
)
return _t.model_validate(envelope["data"])
resolved_decoder = _synthesized_decoder
return origin(
response,
resolved_decoder,
sentinel=sentinel,
client_ref=client_ref,
)
class _APIResponseBase(Generic[T]):
def __init__(
self,
*,
raw: httpx.Response,
parser: Callable[[httpx.Response], T],
mode: ResponseMode = "buffered",
client_ref: Optional[object] = None,
hook_ctx: Optional[Any] = None,
hooks: Optional[Any] = None,
) -> None:
self.http_response = raw
self._parser = parser
self._mode = mode
self._client_ref = client_ref
self._hook_ctx = hook_ctx
self._hooks = hooks
self._parsed_by_type: dict[Any, Any] = {}
def _raise_parse_error(self, exc: Exception) -> NoReturn:
if self._hook_ctx is None:
raise_parse_error(None, None, self.http_response, exc)
raise_parse_error(self._hooks, self._hook_ctx, self.http_response, exc)
@property
def headers(self) -> httpx.Headers:
return self.http_response.headers
@property
def http_request(self) -> httpx.Request:
return self.http_response.request
@property
def status_code(self) -> int:
return self.http_response.status_code
@property
def request_id(self) -> Optional[str]:
return self.http_response.headers.get("x-request-id")
@property
def url(self) -> httpx.URL:
return self.http_response.url
@property
def method(self) -> str:
return self.http_request.method
@property
def http_version(self) -> str:
return self.http_response.http_version
@property
def elapsed(self) -> timedelta:
return self.http_response.elapsed
@property
def is_closed(self) -> bool:
return self.http_response.is_closed
def _parse(
self,
*,
to: Optional[Type[U]] = None,
decoder: Optional[Callable[[str], Any]] = None,
sentinel: Optional[str] = None,
) -> T | U:
mode = self._mode
if mode == "event_stream" and not _can_honor_event_stream(
to, self.http_response
):
mode = "buffered"
if to is not None and mode == "event_stream":
return _build_event_stream(
to=to,
decoder=decoder,
sentinel=sentinel,
response=self.http_response,
client_ref=self._client_ref,
async_=False,
)
parse_key = to or _DEFAULT_PARSE_KEY
if parse_key not in self._parsed_by_type:
# raw_stream / event_stream wrappers leave the body unread so the
# caller can iter_bytes/iter_lines; buffered mode eagerly reads.
body = None
try:
if to is None:
if mode == "buffered":
self.read()
self._parsed_by_type[parse_key] = self._parser(self.http_response)
else:
body = self.text()
self._parsed_by_type[parse_key] = unmarshal_json_response(
to, self.http_response, body, validate=False
)
except Exception as exc:
self._raise_parse_error(exc)
return self._parsed_by_type[parse_key]
def read(self) -> bytes:
return self.http_response.read()
def text(self) -> str:
self.read()
return self.http_response.text
def json(self) -> Any:
self.read()
return self.http_response.json()
def close(self) -> None:
self.http_response.close()
def __enter__(self: ResponseT) -> ResponseT:
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
self.close()
def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]:
yield from self.http_response.iter_bytes(chunk_size)
def iter_text(self, chunk_size: Optional[int] = None) -> Iterator[str]:
yield from self.http_response.iter_text(chunk_size)
def iter_lines(self) -> Iterator[str]:
yield from self.http_response.iter_lines()
class APIResponse(_APIResponseBase[T]):
@overload
def parse(self) -> T: ...
@overload
def parse(self, *, to: Type[U]) -> U: ...
@overload
def parse(self, *, to: Type[U], decoder: Callable[[str], Any]) -> U: ...
@overload
def parse(self, *, to: Type[U], sentinel: str) -> U: ...
@overload
def parse(
self,
*,
to: Type[U],
decoder: Callable[[str], Any],
sentinel: str,
) -> U: ...
def parse(
self,
*,
to: Optional[Type[U]] = None,
decoder: Optional[Callable[[str], Any]] = None,
sentinel: Optional[str] = None,
) -> T | U:
"""Decode the response body into a typed value.
Three modes, depending on the value provided for ``to``:
1. ``to=None`` (default) — runs the operation's generator-emitted
parser and returns ``T``.
2. ``to=<BaseModel>`` on a non-SSE response — reads the body as
JSON and validates against the given Pydantic model. Returns an
instance of that model.
3. ``to=Stream[T]`` on an SSE response — constructs a typed
iterator over Server-Sent Events frames. Dispatch is driven by
the spec-derived ``mode="event_stream"`` set at wrapper construction,
not by the wire ``Content-Type`` header.
SSE frame decoding
------------------
Each SSE frame is wrapped into a JSON envelope of shape
``{"id"?, "event"?, "data"?, "retry"?}`` (None-valued fields
omitted) before reaching the decoder. The decoder receives the
serialized envelope as a single string per frame.
* ``decoder=None`` — synthesizes a decoder that JSON-parses the
envelope, takes ``["data"]``, and validates as ``T`` via
``T.model_validate(...)``. ``T`` must subclass
``pydantic.BaseModel``. Correct when the wire ``data:`` payload
is itself an instance of ``T``.
* ``decoder=<Callable[[str], T]>`` — bypasses synthesis. The
callable receives the JSON-encoded envelope and returns ``T``.
Use when the wire payload has an outer wrapper that must be
peeled, when ``T`` is a discriminated union, or whenever the
synthesized mapping does not match the spec.
* ``sentinel=<str>`` — when an SSE ``data:`` line equals this
string verbatim, iteration terminates cleanly. Use for
protocols that mark end-of-stream with a literal token.
Errors
------
* ``TypeError`` if ``to`` is supplied on an SSE response
(``mode="event_stream"``) and is neither ``Stream[T]``
nor ``AsyncStream[T]``.
* ``TypeError`` if ``to`` is the right stream class but ``T`` is
not a ``BaseModel`` and ``decoder`` was not supplied.
* ``pydantic.ValidationError`` from the (synthesized or
user-supplied) decoder when the wire shape does not match
``T``.
"""
return self._parse(to=to, decoder=decoder, sentinel=sentinel)
class StreamedAPIResponse(_APIResponseBase[T]):
def parse(self) -> T:
return self._parse()
class _AsyncAPIResponseBase(Generic[T]):
def __init__(
self,
*,
raw: httpx.Response,
parser: Callable[[httpx.Response], Awaitable[T]],
mode: ResponseMode = "buffered",
client_ref: Optional[object] = None,
hook_ctx: Optional[Any] = None,
hooks: Optional[Any] = None,
async_hooks: Optional[Any] = None,
) -> None:
self.http_response = raw
self._parser = parser
self._mode = mode
self._client_ref = client_ref
self._hook_ctx = hook_ctx
self._hooks = hooks
self._async_hooks = async_hooks
self._parsed_by_type: dict[Any, Any] = {}
async def _raise_parse_error(self, exc: Exception) -> NoReturn:
if self._hook_ctx is None:
raise_parse_error(None, None, self.http_response, exc)
await raise_parse_error_async(
self._async_hooks, self._hooks, self._hook_ctx, self.http_response, exc
)
@property
def headers(self) -> httpx.Headers:
return self.http_response.headers
@property
def http_request(self) -> httpx.Request:
return self.http_response.request
@property
def status_code(self) -> int:
return self.http_response.status_code
@property
def request_id(self) -> Optional[str]:
return self.http_response.headers.get("x-request-id")
@property
def url(self) -> httpx.URL:
return self.http_response.url
@property
def method(self) -> str:
return self.http_request.method
@property
def http_version(self) -> str:
return self.http_response.http_version
@property
def elapsed(self) -> timedelta:
return self.http_response.elapsed
@property
def is_closed(self) -> bool:
return self.http_response.is_closed
async def _parse(
self,
*,
to: Optional[Type[U]] = None,
decoder: Optional[Callable[[str], Any]] = None,
sentinel: Optional[str] = None,
) -> T | U:
mode = self._mode
if mode == "event_stream" and not _can_honor_event_stream(
to, self.http_response
):
mode = "buffered"
if to is not None and mode == "event_stream":
return _build_event_stream(
to=to,
decoder=decoder,
sentinel=sentinel,
response=self.http_response,
client_ref=self._client_ref,
async_=True,
)
parse_key = to or _DEFAULT_PARSE_KEY
if parse_key not in self._parsed_by_type:
# raw_stream / event_stream wrappers leave the body unread so the
# caller can iter_bytes/iter_lines; buffered mode eagerly reads.
body = None
try:
if to is None:
if mode == "buffered":
await self.read()
self._parsed_by_type[parse_key] = await self._parser(
self.http_response
)
else:
body = await self.text()
self._parsed_by_type[parse_key] = unmarshal_json_response(
to, self.http_response, body, validate=False
)
except Exception as exc:
await self._raise_parse_error(exc)
return self._parsed_by_type[parse_key]
async def read(self) -> bytes:
return await self.http_response.aread()
async def text(self) -> str:
await self.read()
return self.http_response.text
async def json(self) -> Any:
await self.read()
return self.http_response.json()
async def close(self) -> None:
await self.http_response.aclose()
async def __aenter__(self: AsyncResponseT) -> AsyncResponseT:
return self
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.close()
async def iter_bytes(
self, chunk_size: Optional[int] = None
) -> AsyncIterator[bytes]:
async for chunk in self.http_response.aiter_bytes(chunk_size):
yield chunk
async def iter_text(self, chunk_size: Optional[int] = None) -> AsyncIterator[str]:
async for chunk in self.http_response.aiter_text(chunk_size):
yield chunk
async def iter_lines(self) -> AsyncIterator[str]:
async for chunk in self.http_response.aiter_lines():
yield chunk
class AsyncAPIResponse(_AsyncAPIResponseBase[T]):
@overload
async def parse(self) -> T: ...
@overload
async def parse(self, *, to: Type[U]) -> U: ...
@overload
async def parse(self, *, to: Type[U], decoder: Callable[[str], Any]) -> U: ...
@overload
async def parse(self, *, to: Type[U], sentinel: str) -> U: ...
@overload
async def parse(
self,
*,
to: Type[U],
decoder: Callable[[str], Any],
sentinel: str,
) -> U: ...
async def parse(
self,
*,
to: Optional[Type[U]] = None,
decoder: Optional[Callable[[str], Any]] = None,
sentinel: Optional[str] = None,
) -> T | U:
"""Decode the response body into a typed value.
Async sibling of ``APIResponse.parse``. Modes, decoder synthesis,
and ``sentinel`` semantics follow the same contract. For SSE
responses pass ``to=AsyncStream[T]`` (not ``Stream[T]``)
and iterate with ``async for``.
Errors
------
* ``TypeError`` if ``to`` is supplied on an SSE response
(``mode="event_stream"``) and is neither ``Stream[T]``
nor ``AsyncStream[T]``.
* ``TypeError`` if ``to`` is the right stream class but ``T`` is
not a ``BaseModel`` and ``decoder`` was not supplied.
* ``pydantic.ValidationError`` from the (synthesized or
user-supplied) decoder when the wire shape does not match
``T``.
"""
return await self._parse(to=to, decoder=decoder, sentinel=sentinel)
class AsyncStreamedAPIResponse(_AsyncAPIResponseBase[T]):
async def parse(self) -> T:
return await self._parse()
class ResponseContextManager(Generic[ResponseT]):
def __init__(self, request_func: Callable[[], ResponseT]) -> None:
self._request_func = request_func
self._response: Optional[ResponseT] = None
def __enter__(self) -> ResponseT:
self._response = self._request_func()
return self._response
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
if self._response is not None:
self._response.close()
class AsyncResponseContextManager(Generic[AsyncResponseT]):
def __init__(self, request_func: Callable[[], Awaitable[AsyncResponseT]]) -> None:
self._request_func = request_func
self._response: Optional[AsyncResponseT] = None
async def __aenter__(self) -> AsyncResponseT:
self._response = await self._request_func()
return self._response
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
if self._response is not None:
await self._response.close()
def _set_response_mode(kwargs: Dict[str, Any], mode: str, header_kwarg: str) -> None:
headers = dict(kwargs.get(header_kwarg) or {})
headers[_RESPONSE_MODE_HEADER] = mode
kwargs[header_kwarg] = headers
def consume_response_mode(
http_headers: Optional[Mapping[str, str]],
) -> Tuple[ResponseModeHeader, Optional[Mapping[str, str]]]:
"""Read and remove the marker header, returning the response mode and the
remaining headers."""
if http_headers is None:
return _PARSED_RESPONSE_MODE, None
mode: ResponseModeHeader = _PARSED_RESPONSE_MODE
remaining: Dict[str, str] = {}
for name, value in http_headers.items():
if name.lower() == _RESPONSE_MODE_HEADER:
if value in (_RAW_RESPONSE_MODE, _STREAMING_RESPONSE_MODE):
mode = cast(ResponseModeHeader, value)
else:
remaining[name] = value
return mode, (remaining or None)
def to_raw_response_wrapper(
func: Callable[P, T], header_kwarg: str
) -> Callable[P, APIResponse[T]]:
@functools.wraps(func)
def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[T]:
_set_response_mode(
cast(Dict[str, Any], kwargs), _RAW_RESPONSE_MODE, header_kwarg
)
return cast(APIResponse[T], func(*args, **kwargs))
return wrapped
def async_to_raw_response_wrapper(
func: Callable[P, Awaitable[T]], header_kwarg: str
) -> Callable[P, Awaitable[AsyncAPIResponse[T]]]:
@functools.wraps(func)
async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[T]:
_set_response_mode(
cast(Dict[str, Any], kwargs), _RAW_RESPONSE_MODE, header_kwarg
)
return cast(AsyncAPIResponse[T], await func(*args, **kwargs))
return wrapped
def to_streamed_response_wrapper(
func: Callable[P, T], header_kwarg: str
) -> Callable[P, ResponseContextManager[StreamedAPIResponse[T]]]:
@functools.wraps(func)
def wrapped(
*args: P.args, **kwargs: P.kwargs
) -> ResponseContextManager[StreamedAPIResponse[T]]:
_set_response_mode(
cast(Dict[str, Any], kwargs), _STREAMING_RESPONSE_MODE, header_kwarg
)
request_func = functools.partial(func, *args, **kwargs)
return ResponseContextManager(
cast(Callable[[], StreamedAPIResponse[T]], request_func)
)
return wrapped
def async_to_streamed_response_wrapper(
func: Callable[P, Awaitable[T]], header_kwarg: str
) -> Callable[P, AsyncResponseContextManager[AsyncStreamedAPIResponse[T]]]:
@functools.wraps(func)
def wrapped(
*args: P.args, **kwargs: P.kwargs
) -> AsyncResponseContextManager[AsyncStreamedAPIResponse[T]]:
_set_response_mode(
cast(Dict[str, Any], kwargs), _STREAMING_RESPONSE_MODE, header_kwarg
)
request_func = functools.partial(func, *args, **kwargs)
return AsyncResponseContextManager(
cast(Callable[[], Awaitable[AsyncStreamedAPIResponse[T]]], request_func)
)
return wrapped
@@ -0,0 +1,489 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import asyncio
import random
import time
from datetime import datetime
from email.utils import parsedate_to_datetime
from typing import List, Optional
import httpx
class BackoffStrategy:
"""Exponential backoff strategy configuration."""
initial_interval: int
max_interval: int
exponent: float
max_elapsed_time: int
jitter_ms: Optional[int]
def __init__(
self,
initial_interval: int,
max_interval: int,
exponent: float,
max_elapsed_time: int,
jitter_ms: Optional[int] = None,
):
"""Initialize a backoff strategy.
Args:
initial_interval: Initial retry interval in milliseconds.
max_interval: Maximum retry interval in milliseconds.
exponent: Base of the exponential backoff; the interval grows as
``initial_interval * exponent ** retries``.
max_elapsed_time: Maximum total elapsed time in milliseconds. Only used
by the ``"backoff"`` strategy; ignored by ``"attempt-count-backoff"``.
jitter_ms: Additive jitter bound in milliseconds. When set, adds a random
value in ``[0, jitter_ms]`` to each computed backoff interval (default -25%
for attempt-count, +[0, 1s] for backoff).
Note:
When a response carries a ``Retry-After`` or ``retry-after-ms`` header,
that delay is used as-is and the sleep-shaping parameters
(``initial_interval``, ``max_interval``, ``exponent``, ``jitter_ms``) are
ignored for that attempt.
"""
if jitter_ms is not None and jitter_ms < 0:
raise ValueError("jitter_ms must be >= 0")
self.initial_interval = initial_interval
self.max_interval = max_interval
self.exponent = exponent
self.max_elapsed_time = max_elapsed_time
self.jitter_ms = jitter_ms
class RetryConfig:
"""Runtime retry configuration."""
strategy: str
backoff: Optional[BackoffStrategy]
retry_connection_errors: bool
max_retries: Optional[int]
status_codes_override: Optional[List[str]]
def __init__(
self,
strategy: str,
backoff: Optional[BackoffStrategy],
retry_connection_errors: bool,
max_retries: Optional[int] = None,
status_codes_override: Optional[List[str]] = None,
):
"""Initialize a retry configuration.
Args:
strategy: Retry strategy: ``"none"``, ``"backoff"`` or ``"attempt-count-backoff"``.
backoff: Backoff parameters; falls back to a built-in default when ``None``.
retry_connection_errors: Whether to also retry transport-level connection errors.
max_retries: Maximum number of retries for the ``"attempt-count-backoff"`` strategy.
status_codes_override: Retryable HTTP status codes that take precedence over the
per-operation defaults when non-empty.
"""
self.strategy = strategy
self.backoff = backoff
self.retry_connection_errors = retry_connection_errors
self.max_retries = max_retries
self.status_codes_override = status_codes_override
class Retries:
config: RetryConfig
status_codes: List[str]
def __init__(self, config: RetryConfig, status_codes: List[str]):
self.config = config
self.status_codes = config.status_codes_override or status_codes
class TemporaryError(Exception):
response: httpx.Response
retry_after: Optional[int]
def __init__(self, response: httpx.Response):
self.response = response
self.retry_after = _parse_retry_after_header(response)
class PermanentError(Exception):
inner: Exception
def __init__(self, inner: Exception):
self.inner = inner
def _parse_retry_after_header(response: httpx.Response) -> Optional[int]:
"""Parse Retry-After header from response.
Returns:
Retry interval in milliseconds, or None if header is missing or invalid.
"""
retry_after_header = response.headers.get("retry-after")
if not retry_after_header:
return None
try:
seconds = float(retry_after_header)
return round(seconds * 1000)
except ValueError:
pass
try:
retry_date = parsedate_to_datetime(retry_after_header)
delta = (retry_date - datetime.now(retry_date.tzinfo)).total_seconds()
return round(max(0, delta) * 1000)
except (ValueError, TypeError):
pass
return None
def _parse_retry_after_ms_header(response: httpx.Response) -> Optional[int]:
retry_after_ms_header = response.headers.get("retry-after-ms")
if not retry_after_ms_header:
return None
try:
milliseconds = float(retry_after_ms_header)
if milliseconds >= 0:
return round(milliseconds)
except (OverflowError, ValueError):
pass
return None
def _get_sleep_interval(
exception: Exception,
initial_interval: int,
max_interval: int,
exponent: float,
retries: int,
attempt_count_backoff: bool = False,
jitter_ms: Optional[int] = None,
) -> float:
"""Get sleep interval for retry with exponential backoff.
Args:
exception: The exception that triggered the retry.
initial_interval: Initial retry interval in milliseconds.
max_interval: Maximum retry interval in milliseconds.
exponent: Base for exponential backoff calculation.
retries: Current retry attempt count.
attempt_count_backoff: Use multiplicative jitter when ``jitter_ms`` is unset.
jitter_ms: Additive jitter bound in ms; see ``BackoffStrategy.jitter_ms``.
Returns:
Sleep interval in seconds.
"""
if (
isinstance(exception, TemporaryError)
and exception.retry_after is not None
and exception.retry_after > 0
):
return exception.retry_after / 1000
sleep = (initial_interval / 1000) * exponent**retries
if jitter_ms is not None:
sleep += random.uniform(0, jitter_ms / 1000)
elif attempt_count_backoff:
sleep = sleep * (1 - random.random() * 0.25)
else:
sleep += random.uniform(0, 1)
return min(sleep, max_interval / 1000)
def retry(func, retries: Retries):
if retries.config.strategy in ("backoff", "attempt-count-backoff"):
def do_request(attempt: int) -> httpx.Response:
res: httpx.Response
try:
res = func(attempt)
should_retry = False
for code in retries.status_codes:
if "X" in code.upper():
code_range = int(code[0])
status_major = res.status_code / 100
if code_range <= status_major < code_range + 1:
should_retry = True
else:
parsed_code = int(code)
if res.status_code == parsed_code:
should_retry = True
if should_retry:
raise TemporaryError(res)
except (httpx.NetworkError, httpx.TimeoutException) as exception:
if retries.config.retry_connection_errors:
raise
raise PermanentError(exception) from exception
except TemporaryError:
raise
except Exception as exception:
raise PermanentError(exception) from exception
return res
backoff = retries.config.backoff or BackoffStrategy(500, 60000, 1.5, 3600000)
if retries.config.strategy == "attempt-count-backoff":
return retry_with_attempt_count_backoff(
do_request,
backoff.initial_interval,
backoff.max_interval,
backoff.exponent,
retries.config.max_retries or 0,
backoff.jitter_ms,
)
return retry_with_backoff(
do_request,
backoff.initial_interval,
backoff.max_interval,
backoff.exponent,
backoff.max_elapsed_time,
backoff.jitter_ms,
)
return func(0)
async def retry_async(func, retries: Retries):
if retries.config.strategy in ("backoff", "attempt-count-backoff"):
async def do_request(attempt: int) -> httpx.Response:
res: httpx.Response
try:
res = await func(attempt)
should_retry = False
for code in retries.status_codes:
if "X" in code.upper():
code_range = int(code[0])
status_major = res.status_code / 100
if code_range <= status_major < code_range + 1:
should_retry = True
else:
parsed_code = int(code)
if res.status_code == parsed_code:
should_retry = True
if should_retry:
raise TemporaryError(res)
except (httpx.NetworkError, httpx.TimeoutException) as exception:
if retries.config.retry_connection_errors:
raise
raise PermanentError(exception) from exception
except TemporaryError:
raise
except Exception as exception:
raise PermanentError(exception) from exception
return res
backoff = retries.config.backoff or BackoffStrategy(500, 60000, 1.5, 3600000)
if retries.config.strategy == "attempt-count-backoff":
return await retry_with_attempt_count_backoff_async(
do_request,
backoff.initial_interval,
backoff.max_interval,
backoff.exponent,
retries.config.max_retries or 0,
backoff.jitter_ms,
)
return await retry_with_backoff_async(
do_request,
backoff.initial_interval,
backoff.max_interval,
backoff.exponent,
backoff.max_elapsed_time,
backoff.jitter_ms,
)
return await func(0)
def retry_with_backoff(
func,
initial_interval=500,
max_interval=60000,
exponent=1.5,
max_elapsed_time=3600000,
jitter_ms=None,
):
start = round(time.time() * 1000)
retries = 0
while True:
try:
return func(retries)
except PermanentError as exception:
raise exception.inner
except Exception as exception: # pylint: disable=broad-exception-caught
now = round(time.time() * 1000)
if now - start > max_elapsed_time:
if isinstance(exception, TemporaryError):
return exception.response
raise
if isinstance(exception, TemporaryError):
retry_after_ms = _parse_retry_after_ms_header(exception.response)
if retry_after_ms is not None:
exception.retry_after = retry_after_ms
sleep = _get_sleep_interval(
exception,
initial_interval,
max_interval,
exponent,
retries,
jitter_ms=jitter_ms,
)
time.sleep(sleep)
retries += 1
def retry_with_attempt_count_backoff(
func,
initial_interval=500,
max_interval=60000,
exponent=1.5,
max_retries=0,
jitter_ms=None,
):
retries = 0
while True:
try:
return func(retries)
except PermanentError as exception:
raise exception.inner
except Exception as exception: # pylint: disable=broad-exception-caught
if retries >= max_retries:
if isinstance(exception, TemporaryError):
return exception.response
raise
if isinstance(exception, TemporaryError):
retry_after_ms = _parse_retry_after_ms_header(exception.response)
if retry_after_ms is not None:
exception.retry_after = retry_after_ms
sleep = _get_sleep_interval(
exception,
initial_interval,
max_interval,
exponent,
retries,
attempt_count_backoff=True,
jitter_ms=jitter_ms,
)
time.sleep(sleep)
retries += 1
async def retry_with_backoff_async(
func,
initial_interval=500,
max_interval=60000,
exponent=1.5,
max_elapsed_time=3600000,
jitter_ms=None,
):
start = round(time.time() * 1000)
retries = 0
while True:
try:
return await func(retries)
except PermanentError as exception:
raise exception.inner
except Exception as exception: # pylint: disable=broad-exception-caught
now = round(time.time() * 1000)
if now - start > max_elapsed_time:
if isinstance(exception, TemporaryError):
return exception.response
raise
if isinstance(exception, TemporaryError):
retry_after_ms = _parse_retry_after_ms_header(exception.response)
if retry_after_ms is not None:
exception.retry_after = retry_after_ms
sleep = _get_sleep_interval(
exception,
initial_interval,
max_interval,
exponent,
retries,
jitter_ms=jitter_ms,
)
await asyncio.sleep(sleep)
retries += 1
async def retry_with_attempt_count_backoff_async(
func,
initial_interval=500,
max_interval=60000,
exponent=1.5,
max_retries=0,
jitter_ms=None,
):
retries = 0
while True:
try:
return await func(retries)
except PermanentError as exception:
raise exception.inner
except Exception as exception: # pylint: disable=broad-exception-caught
if retries >= max_retries:
if isinstance(exception, TemporaryError):
return exception.response
raise
if isinstance(exception, TemporaryError):
retry_after_ms = _parse_retry_after_ms_header(exception.response)
if retry_after_ms is not None:
exception.retry_after = retry_after_ms
sleep = _get_sleep_interval(
exception,
initial_interval,
max_interval,
exponent,
retries,
attempt_count_backoff=True,
jitter_ms=jitter_ms,
)
await asyncio.sleep(sleep)
retries += 1
@@ -0,0 +1,237 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import base64
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
)
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from .metadata import (
SecurityMetadata,
find_field_metadata,
)
import os
def get_security(
security: Any, allowed_fields: Optional[List[str]] = None
) -> Tuple[Dict[str, str], Dict[str, List[str]]]:
headers: Dict[str, str] = {}
query_params: Dict[str, List[str]] = {}
if security is None:
return headers, query_params
if not isinstance(security, BaseModel):
raise TypeError("security must be a pydantic model")
sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields
sec_field_names = (
list(sec_fields.keys()) if allowed_fields is None else allowed_fields
)
for name in sec_field_names:
if name not in sec_fields:
continue
sec_field = sec_fields[name]
value = getattr(security, name)
if value is None:
continue
metadata = find_field_metadata(sec_field, SecurityMetadata)
if metadata is None:
continue
if metadata.option:
_parse_security_option(headers, query_params, value)
return headers, query_params
if metadata.scheme:
# Special case for basic auth or custom auth which could be a flattened model
if metadata.sub_type in ["basic", "custom"] and not isinstance(
value, BaseModel
):
_parse_security_scheme(headers, query_params, metadata, name, security)
else:
_parse_security_scheme(headers, query_params, metadata, name, value)
if not metadata.composite:
return headers, query_params
return headers, query_params
def get_security_from_env(security: Any, security_class: Any) -> Optional[BaseModel]:
if security is not None:
return security
if not issubclass(security_class, BaseModel):
raise TypeError("security_class must be a pydantic model class")
security_dict: Any = {}
if os.getenv("GOOGLE_GENAI_API_KEY"):
security_dict["api_key"] = os.getenv("GOOGLE_GENAI_API_KEY")
if os.getenv("GOOGLE_GENAI_ACCESS_TOKEN"):
security_dict["access_token"] = os.getenv("GOOGLE_GENAI_ACCESS_TOKEN")
if os.getenv("GOOGLE_GENAI_DEFAULT_HEADERS"):
security_dict["default_headers"] = os.getenv("GOOGLE_GENAI_DEFAULT_HEADERS")
return security_class(**security_dict) if security_dict else None
def _parse_security_option(
headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any
):
if not isinstance(option, BaseModel):
raise TypeError("security option must be a pydantic model")
opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields
for name in opt_fields:
opt_field = opt_fields[name]
metadata = find_field_metadata(opt_field, SecurityMetadata)
if metadata is None or not metadata.scheme:
continue
value = getattr(option, name)
if (
metadata.scheme_type == "http"
and metadata.sub_type == "basic"
and not isinstance(value, BaseModel)
):
_parse_basic_auth_scheme(headers, option)
return
_parse_security_scheme(headers, query_params, metadata, name, value)
def _parse_security_scheme(
headers: Dict[str, str],
query_params: Dict[str, List[str]],
scheme_metadata: SecurityMetadata,
field_name: str,
scheme: Any,
):
scheme_type = scheme_metadata.scheme_type
sub_type = scheme_metadata.sub_type
if isinstance(scheme, BaseModel):
if scheme_type == "http":
if sub_type == "basic":
_parse_basic_auth_scheme(headers, scheme)
return
if sub_type == "custom":
return
scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
for name in scheme_fields:
scheme_field = scheme_fields[name]
metadata = find_field_metadata(scheme_field, SecurityMetadata)
if metadata is None or metadata.field_name is None:
continue
value = getattr(scheme, name)
_parse_security_scheme_value(
headers, query_params, scheme_metadata, metadata, name, value
)
else:
_parse_security_scheme_value(
headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme
)
def _parse_security_scheme_value(
headers: Dict[str, str],
query_params: Dict[str, List[str]],
scheme_metadata: SecurityMetadata,
security_metadata: SecurityMetadata,
field_name: str,
value: Any,
):
scheme_type = scheme_metadata.scheme_type
sub_type = scheme_metadata.sub_type
header_name = security_metadata.get_field_name(field_name)
if scheme_type == "apiKey":
if sub_type == "header":
headers[header_name] = value
elif sub_type == "query":
query_params[header_name] = [value]
else:
raise ValueError("sub type {sub_type} not supported")
elif scheme_type == "openIdConnect":
headers[header_name] = _apply_bearer(value)
elif scheme_type == "oauth2":
if sub_type != "client_credentials":
headers[header_name] = _apply_bearer(value)
elif scheme_type == "http":
if sub_type == "bearer":
headers[header_name] = _apply_bearer(value)
elif sub_type == "basic":
headers[header_name] = value
elif sub_type == "custom":
return
else:
raise ValueError("sub type {sub_type} not supported")
else:
raise ValueError("scheme type {scheme_type} not supported")
def _apply_bearer(token: str) -> str:
return token.lower().startswith("bearer ") and token or f"Bearer {token}"
def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any):
username = ""
password = ""
if not isinstance(scheme, BaseModel):
raise TypeError("basic auth scheme must be a pydantic model")
scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
for name in scheme_fields:
scheme_field = scheme_fields[name]
metadata = find_field_metadata(scheme_field, SecurityMetadata)
if metadata is None or metadata.field_name is None:
continue
field_name = metadata.field_name
value = getattr(scheme, name)
if field_name == "username":
username = value
if field_name == "password":
password = value
data = f"{username}:{password}".encode()
headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}"
@@ -0,0 +1,437 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from decimal import Decimal
import functools
import json
import typing
from typing import Any, Dict, Iterable, List, Mapping, Tuple, Union, get_args
import typing_extensions
from typing_extensions import get_origin
import httpx
from pydantic import ConfigDict, create_model
from pydantic_core import from_json
from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset
def serialize_decimal(as_str: bool):
def serialize(d):
if d is None:
return None
if isinstance(d, Unset):
return d
if not isinstance(d, Decimal):
raise ValueError("Expected Decimal object")
return str(d) if as_str else float(d)
return serialize
def validate_decimal(d):
if d is None:
return None
if isinstance(d, (Decimal, Unset)):
return d
if not isinstance(d, (str, int, float)):
raise ValueError("Expected string, int or float")
return Decimal(str(d))
def serialize_float(as_str: bool):
def serialize(f):
if f is None:
return None
if isinstance(f, Unset):
return f
if not isinstance(f, float):
raise ValueError("Expected float")
return str(f) if as_str else f
return serialize
def validate_float(f):
if f is None:
return None
if isinstance(f, (float, Unset)):
return f
if not isinstance(f, str):
raise ValueError("Expected string")
return float(f)
def serialize_int(as_str: bool):
def serialize(i):
if i is None:
return None
if isinstance(i, Unset):
return i
if not isinstance(i, int):
raise ValueError("Expected int")
return str(i) if as_str else i
return serialize
def validate_int(b):
if b is None:
return None
if isinstance(b, (int, Unset)):
return b
if not isinstance(b, str):
raise ValueError("Expected string")
return int(b)
def validate_const(v):
def validate(c):
if c is None:
return None
if v != c:
raise ValueError(f"Expected {v}")
return c
return validate
def unmarshal_json(raw, typ: Any) -> Any:
return unmarshal(from_json(raw), typ, coerce_iterables=False)
def unmarshal(val, typ: Any, coerce_iterables: bool = True) -> Any:
if coerce_iterables:
val = _coerce_iterables_for_type(val, typ)
unmarshaller = create_model(
"Unmarshaller",
body=(typ, ...),
__config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
)
m = unmarshaller(body=val)
# pyright: ignore[reportAttributeAccessIssue]
return m.body # type: ignore
_CONSTRUCT_UNVALIDATED_MAX_DEPTH = 64
def construct_unvalidated(value: Any, typ: Any, _depth: int = 0) -> Any:
try:
return unmarshal(value, typ, coerce_iterables=True)
except Exception:
pass
return _construct_lenient(value, typ, _depth)
def _construct_lenient(value: Any, typ: Any, depth: int) -> Any:
if depth > _CONSTRUCT_UNVALIDATED_MAX_DEPTH:
return value
typ = _resolve_type_alias(typ)
origin = get_origin(typ)
if _is_annotated_type(origin):
args = get_args(typ)
return _construct_lenient(value, args[0], depth) if args else value
if is_union(origin):
variants = [arg for arg in get_args(typ) if arg is not type(None)]
for variant in variants:
try:
return unmarshal(value, variant, coerce_iterables=True)
except Exception:
continue
last_err = None
for variant in variants:
try:
return _construct_lenient(value, variant, depth)
except Exception as e: # noqa: BLE001
last_err = e
continue
if value is None and type(None) in get_args(typ):
return None
if last_err is not None:
raise last_err
return value
if _is_list_type(typ):
if not isinstance(value, list):
raise TypeError(f"expected list for {typ!r}, got {type(value)!r}")
item_type = get_args(typ)[0] if get_args(typ) else Any
return [construct_unvalidated(item, item_type, depth + 1) for item in value]
if _is_mapping_type(typ):
if not isinstance(value, Mapping):
raise TypeError(f"expected mapping for {typ!r}, got {type(value)!r}")
value_type = get_args(typ)[1] if len(get_args(typ)) > 1 else Any
return {
key: construct_unvalidated(item, value_type, depth + 1)
for key, item in value.items()
}
if _is_pydantic_model_type(typ):
if not isinstance(value, Mapping):
raise TypeError(f"expected mapping for {typ!r}, got {type(value)!r}")
return _construct_model_lenient(value, typ, depth)
return value
def _construct_model_lenient(value: Mapping, typ: Any, depth: int) -> Any:
fields: Dict[str, Any] = {}
consumed = set()
for name, field in typ.model_fields.items():
wire_key = None
if field.alias is not None and field.alias in value:
wire_key = field.alias
elif name in value:
wire_key = name
annotation = field.rebuild_annotation()
if wire_key is not None:
consumed.add(wire_key)
fields[name] = construct_unvalidated(value[wire_key], annotation, depth + 1)
elif field.is_required():
fields[name] = _default_for_required(annotation, depth)
else:
fields[name] = field.get_default(call_default_factory=True)
for key, item in value.items():
if key not in consumed and key not in fields:
fields[key] = item
return typ.model_construct(**fields)
def _default_for_required(typ: Any, depth: int) -> Any:
typ = _resolve_type_alias(typ)
origin = get_origin(typ)
if _is_annotated_type(origin):
args = get_args(typ)
return _default_for_required(args[0], depth) if args else None
if is_union(origin):
if type(None) in get_args(typ):
return None
for variant in get_args(typ):
try:
return _default_for_required(variant, depth)
except Exception: # noqa: BLE001
continue
return None
if depth <= _CONSTRUCT_UNVALIDATED_MAX_DEPTH and _is_pydantic_model_type(typ):
return _construct_model_lenient({}, typ, depth + 1)
return None
def marshal_json(val, typ):
if is_nullable(typ) and val is None:
return "null"
marshaller = create_model(
"Marshaller",
body=(typ, ...),
__config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
)
m = marshaller(body=val)
d = m.model_dump(by_alias=True, mode="json", exclude_none=True)
if len(d) == 0:
return ""
return json.dumps(d[next(iter(d))], separators=(",", ":"))
def is_nullable(field):
origin = get_origin(field)
if origin is Nullable or origin is OptionalNullable:
return True
if not origin is Union or type(None) not in get_args(field):
return False
for arg in get_args(field):
if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable:
return True
return False
def is_union(obj: object) -> bool:
"""
Returns True if the given object is a typing.Union or typing_extensions.Union.
"""
return any(
obj is typing_obj for typing_obj in _get_typing_objects_by_name_of("Union")
)
def stream_to_text(stream: httpx.Response) -> str:
return "".join(stream.iter_text())
async def stream_to_text_async(stream: httpx.Response) -> str:
return "".join([chunk async for chunk in stream.aiter_text()])
def stream_to_bytes(stream: httpx.Response) -> bytes:
return stream.content
async def stream_to_bytes_async(stream: httpx.Response) -> bytes:
return await stream.aread()
def get_pydantic_model(data: Any, typ: Any) -> Any:
if not _contains_pydantic_model(data):
return unmarshal(data, typ)
return _coerce_iterables_for_type(data, typ)
def _coerce_iterables_for_type(data: Any, typ: Any) -> Any:
if data is None or isinstance(data, (BaseModel, Unset)):
return data
typ = _resolve_type_alias(typ)
origin = get_origin(typ)
if _is_annotated_type(origin):
args = get_args(typ)
return _coerce_iterables_for_type(data, args[0]) if args else data
if is_union(origin):
for arg in (arg for arg in get_args(typ) if arg is not type(None)):
coerced = _coerce_iterables_for_type(data, arg)
if coerced is not data:
return coerced
return data
if _is_list_type(typ):
item_type = get_args(typ)[0] if get_args(typ) else Any
if isinstance(data, (str, bytes, bytearray, Mapping)):
return data
if isinstance(data, Iterable):
return [_coerce_iterables_for_type(item, item_type) for item in data]
return data
if _is_mapping_type(typ):
value_type = get_args(typ)[1] if len(get_args(typ)) > 1 else Any
if isinstance(data, Mapping):
return {
key: _coerce_iterables_for_type(value, value_type)
for key, value in data.items()
}
return data
if _is_pydantic_model_type(typ) and isinstance(data, Mapping):
coerced = None
for field_name, field in typ.model_fields.items():
field_type = field.annotation
for key in (field_name, field.alias):
if key is not None and key in data:
value = data[key] if coerced is None else coerced[key]
coerced_value = _coerce_iterables_for_type(value, field_type)
if coerced_value is not value:
if coerced is None:
coerced = dict(data)
coerced[key] = coerced_value
return coerced if coerced is not None else data
return data
def _resolve_type_alias(typ: Any) -> Any:
return getattr(typ, "__value__", typ)
def _is_annotated_type(origin: Any) -> bool:
return any(
origin is typing_obj
for typing_obj in _get_typing_objects_by_name_of("Annotated")
)
def _is_list_type(typ: Any) -> bool:
typ = _resolve_type_alias(typ)
return typ is list or get_origin(typ) is list
def _is_mapping_type(typ: Any) -> bool:
typ = _resolve_type_alias(typ)
origin = get_origin(typ)
mapping_origin = get_origin(Mapping[Any, Any])
return typ in (dict, Dict, Mapping) or origin in (dict, Mapping, mapping_origin)
def _is_pydantic_model_type(typ: Any) -> bool:
return isinstance(typ, type) and issubclass(typ, BaseModel)
def _contains_pydantic_model(data: Any) -> bool:
if isinstance(data, BaseModel):
return True
if isinstance(data, List):
return any(_contains_pydantic_model(item) for item in data)
if isinstance(data, Dict):
return any(_contains_pydantic_model(value) for value in data.values())
return False
@functools.cache
def _get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]:
"""
Get typing objects by name from typing and typing_extensions.
Reference: https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types
"""
result = tuple(
getattr(module, name)
for module in (typing, typing_extensions)
if hasattr(module, name)
)
if not result:
raise ValueError(
f"Neither typing nor typing_extensions has an object called {name!r}"
)
return result
@@ -0,0 +1,64 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import Any
from pydantic import BaseModel, TypeAdapter, ValidationError
from .serializers import construct_unvalidated
def parse_open_union(
v: Any,
*,
disc_key: str,
variants: dict[str, Any],
unknown_cls: type,
union_name: str,
lenient: bool = False,
) -> Any:
"""Parse an open discriminated union value with forward-compatibility.
Known discriminator values are dispatched to their variant types.
Unknown discriminator values — or known discriminator values whose
payload fails variant validation (e.g. a partial variant emitted by a
newer server) — produce an instance of the fallback class, preserving
the raw payload for inspection.
Non-dict values and dicts missing the discriminator deliberately raise
instead of falling back, so pydantic can try sibling branches of an
enclosing union (e.g. None in Optional[...]).
"""
if isinstance(v, BaseModel):
return v
if not isinstance(v, dict) or disc_key not in v:
raise ValueError(f"{union_name}: expected object with '{disc_key}' field")
disc = v[disc_key]
variant_cls = variants.get(disc)
if variant_cls is not None:
try:
if isinstance(variant_cls, type) and issubclass(variant_cls, BaseModel):
return variant_cls.model_validate(v)
return TypeAdapter(variant_cls).validate_python(v)
except ValidationError:
if lenient:
try:
return construct_unvalidated(v, variant_cls)
except Exception:
pass
return unknown_cls(raw=v)
return unknown_cls(raw=v)
@@ -0,0 +1,66 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import Any, Optional, Type, TypeVar, overload
import httpx
from .serializers import unmarshal_json, construct_unvalidated
from .. import errors
import json
T = TypeVar("T")
@overload
def unmarshal_json_response(
typ: Type[T],
http_res: httpx.Response,
body: Optional[str] = None,
validate: bool = True,
) -> T: ...
@overload
def unmarshal_json_response(
typ: Any,
http_res: httpx.Response,
body: Optional[str] = None,
validate: bool = True,
) -> Any: ...
def unmarshal_json_response(
typ: Any,
http_res: httpx.Response,
body: Optional[str] = None,
validate: bool = True,
) -> Any:
if body is None:
body = http_res.text
try:
return unmarshal_json(body, typ)
except Exception as e:
if not validate:
return construct_unvalidated(json.loads(body), typ)
raise errors.ResponseValidationError(
"Response validation failed",
http_res,
e,
body,
) from e
@@ -0,0 +1,171 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from decimal import Decimal
from typing import (
Any,
Dict,
get_type_hints,
List,
Optional,
Union,
get_args,
get_origin,
)
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from .metadata import (
PathParamMetadata,
find_field_metadata,
)
from .values import (
_get_serialized_params,
_is_set,
_populate_from_globals,
_val_to_string,
)
def generate_url(
server_url: str,
path: str,
path_params: Any,
gbls: Optional[Any] = None,
) -> str:
path_param_values: Dict[str, str] = {}
globals_already_populated = _populate_path_params(
path_params, gbls, path_param_values, []
)
if _is_set(gbls):
_populate_path_params(gbls, None, path_param_values, globals_already_populated)
for key, value in path_param_values.items():
path = path.replace("{" + key + "}", value, 1)
return remove_suffix(server_url, "/") + path
def _populate_path_params(
path_params: Any,
gbls: Any,
path_param_values: Dict[str, str],
skip_fields: List[str],
) -> List[str]:
globals_already_populated: List[str] = []
if not isinstance(path_params, BaseModel):
return globals_already_populated
path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields
path_param_field_types = get_type_hints(path_params.__class__)
for name in path_param_fields:
if name in skip_fields:
continue
field = path_param_fields[name]
param_metadata = find_field_metadata(field, PathParamMetadata)
if param_metadata is None:
continue
param = getattr(path_params, name) if _is_set(path_params) else None
param, global_found = _populate_from_globals(
name, param, PathParamMetadata, gbls
)
if global_found:
globals_already_populated.append(name)
if not _is_set(param):
continue
f_name = field.alias if field.alias is not None else name
serialization = param_metadata.serialization
if serialization is not None:
serialized_params = _get_serialized_params(
param_metadata, f_name, param, path_param_field_types[name]
)
for key, value in serialized_params.items():
path_param_values[key] = value
else:
pp_vals: List[str] = []
if param_metadata.style == "simple":
if isinstance(param, List):
for pp_val in param:
if not _is_set(pp_val):
continue
pp_vals.append(_val_to_string(pp_val))
path_param_values[f_name] = ",".join(pp_vals)
elif isinstance(param, Dict):
for pp_key in param:
if not _is_set(param[pp_key]):
continue
if param_metadata.explode:
pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}")
else:
pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}")
path_param_values[f_name] = ",".join(pp_vals)
elif not isinstance(param, (str, int, float, complex, bool, Decimal)):
param_fields: Dict[str, FieldInfo] = param.__class__.model_fields
for name in param_fields:
param_field = param_fields[name]
param_value_metadata = find_field_metadata(
param_field, PathParamMetadata
)
if param_value_metadata is None:
continue
param_name = (
param_field.alias if param_field.alias is not None else name
)
param_field_val = getattr(param, name)
if not _is_set(param_field_val):
continue
if param_metadata.explode:
pp_vals.append(
f"{param_name}={_val_to_string(param_field_val)}"
)
else:
pp_vals.append(
f"{param_name},{_val_to_string(param_field_val)}"
)
path_param_values[f_name] = ",".join(pp_vals)
elif _is_set(param):
path_param_values[f_name] = _val_to_string(param)
return globals_already_populated
def is_optional(field):
return get_origin(field) is Union and type(None) in get_args(field)
def template_url(url_with_params: str, params: Dict[str, str]) -> str:
for key, value in params.items():
url_with_params = url_with_params.replace("{" + key + "}", value)
return url_with_params
def remove_suffix(input_string, suffix):
if suffix and input_string.endswith(suffix):
return input_string[: -len(suffix)]
return input_string
@@ -0,0 +1,153 @@
# Copyright 2026 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.
#
# pyformat: disable
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from datetime import datetime
from enum import Enum
from email.message import Message
from functools import partial
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, cast
from httpx import Response
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from ..types.basemodel import Unset
from .serializers import marshal_json
from .metadata import ParamMetadata, find_field_metadata
def match_content_type(content_type: str, pattern: str) -> bool:
if pattern in (content_type, "*", "*/*"):
return True
msg = Message()
msg["content-type"] = content_type
media_type = msg.get_content_type()
if media_type == pattern:
return True
parts = media_type.split("/")
if len(parts) == 2:
if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"):
return True
return False
def match_status_codes(status_codes: List[str], status_code: int) -> bool:
if "default" in status_codes:
return True
for code in status_codes:
if code == str(status_code):
return True
if code.endswith("XX") and code.startswith(str(status_code)[:1]):
return True
return False
T = TypeVar("T")
def cast_partial(typ):
return partial(cast, typ)
def get_global_from_env(
value: Optional[T], env_key: str, type_cast: Callable[[str], T]
) -> Optional[T]:
if value is not None:
return value
env_value = os.getenv(env_key)
if env_value is not None:
try:
return type_cast(env_value)
except ValueError:
pass
return None
def match_response(
response: Response, code: Union[str, List[str]], content_type: str
) -> bool:
codes = code if isinstance(code, list) else [code]
return match_status_codes(codes, response.status_code) and match_content_type(
response.headers.get("content-type", "application/octet-stream"), content_type
)
def _populate_from_globals(
param_name: str, value: Any, param_metadata_type: type, gbls: Any
) -> Tuple[Any, bool]:
if gbls is None:
return value, False
if not isinstance(gbls, BaseModel):
raise TypeError("globals must be a pydantic model")
global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields
found = False
for name in global_fields:
field = global_fields[name]
if name is not param_name:
continue
found = True
if value is not None:
return value, True
global_value = getattr(gbls, name)
param_metadata = find_field_metadata(field, param_metadata_type)
if param_metadata is None:
return value, True
return global_value, True
return value, found
def _val_to_string(val) -> str:
if isinstance(val, bool):
return str(val).lower()
if isinstance(val, datetime):
return str(val.isoformat().replace("+00:00", "Z"))
if isinstance(val, Enum):
return str(val.value)
return str(val)
def _get_serialized_params(
metadata: ParamMetadata, field_name: str, obj: Any, typ: type
) -> Dict[str, str]:
params: Dict[str, str] = {}
serialization = metadata.serialization
if serialization == "json":
params[field_name] = marshal_json(obj, typ)
return params
def _is_set(value: Any) -> bool:
return value is not None and not isinstance(value, Unset)