# 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 . import models, types, utils from ._hooks import AsyncSDKHooks, SDKHooks, init_async_hooks from .basesdk import AsyncBaseSDK, BaseSDK from .httpclient import ( AsyncHttpClient, ClientOwner, HttpClient, close_clients, close_clients_async, ) from .sdkconfiguration import SDKConfiguration from .types import OptionalNullable, UNSET from .utils.logger import Logger, get_default_logger from .utils.retries import RetryConfig import httpx import importlib import importlib.util import sys from typing import Callable, Dict, Optional, TYPE_CHECKING, Union, cast import weakref if TYPE_CHECKING: from .agents import Agents, AsyncAgents from .interactions import AsyncInteractions, Interactions from .webhooks import AsyncWebhooks, Webhooks class GenAI(BaseSDK): r"""Gemini API: The Gemini Interactions API allows developers to build generative AI applications using Gemini models. Gemini is our most capable model, built from the ground up to be multimodal. It can generalize and seamlessly understand, operate across, and combine different types of information including language, images, audio, video, and code. You can use the Gemini API for use cases like reasoning across text and images, content generation, dialogue agents, summarization and classification systems, and more.""" @property def with_raw_response(self): return GenAIWithRawResponse(self) @property def with_streaming_response(self): return GenAIWithStreamingResponse(self) interactions: "Interactions" webhooks: "Webhooks" agents: "Agents" _sub_sdk_map = { "interactions": (".interactions", "Interactions"), "webhooks": (".webhooks", "Webhooks"), "agents": (".agents", "Agents"), } def __init__( self, security: Optional[Union[types.Security, Callable[[], types.Security]]] = None, api_version: Optional[str] = None, api_revision: Optional[str] = None, user_project: Optional[str] = None, server_idx: Optional[int] = None, url_params: Optional[Dict[str, str]] = None, server_url: Optional[str] = None, client: Optional[HttpClient] = None, retry_config: OptionalNullable[RetryConfig] = UNSET, timeout_ms: Optional[int] = None, debug_logger: Optional[Logger] = None, ) -> None: r"""Instantiates the SDK configuring it with the provided parameters. :param security: The security details required for authentication :param api_version: Configures the api_version parameter for all supported operations :param api_revision: Configures the api_revision parameter for all supported operations :param user_project: Configures the user_project parameter for all supported operations :param server_idx: The index of the server to use for all methods :param server_url: The server URL to use for all methods :param url_params: Parameters to optionally template the server URL with :param client: The HTTP client to use for all synchronous methods :param retry_config: The retry configuration to use for all supported methods :param timeout_ms: Optional request timeout applied to each operation in milliseconds """ client_supplied = True if client is None: client = httpx.Client(follow_redirects=True) client_supplied = False assert issubclass( type(client), HttpClient ), "The provided client must implement the HttpClient protocol." if debug_logger is None: debug_logger = get_default_logger() if server_url is not None: if url_params is not None: server_url = utils.template_url(server_url, url_params) _globals = models.internal.Globals( api_version=utils.get_global_from_env( api_version, "GOOGLE_GENAI_API_VERSION", str ), api_revision=utils.get_global_from_env( api_revision, "GOOGLE_GENAI_API_REVISION", str ), user_project=utils.get_global_from_env( user_project, "GOOGLE_GENAI_USER_PROJECT", str ), ) BaseSDK.__init__( self, SDKConfiguration( client=client, client_supplied=client_supplied, async_client=None, async_client_supplied=False, globals=_globals, security=security, server_url=server_url, server_idx=server_idx, retry_config=retry_config, timeout_ms=timeout_ms, debug_logger=debug_logger, ), parent_ref=self, ) hooks = SDKHooks() async_hooks = AsyncSDKHooks() # pylint: disable=protected-access self.sdk_configuration.__dict__["_hooks"] = hooks self.sdk_configuration.__dict__["_async_hooks"] = async_hooks init_async_hooks(async_hooks) self.sdk_configuration = hooks.sdk_init(self.sdk_configuration) weakref.finalize( self, close_clients, cast(ClientOwner, self.sdk_configuration), self.sdk_configuration.client, self.sdk_configuration.client_supplied, ) def dynamic_import(self, modname, retries=3): for attempt in range(retries): try: return importlib.import_module(modname, package=__package__) except KeyError: # Clear any half-initialized module and retry resolved = importlib.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 __getattr__(self, name: str): if name in self._sub_sdk_map: module_path, class_name = self._sub_sdk_map[name] try: module = self.dynamic_import(module_path) klass = getattr(module, class_name) instance = klass(self.sdk_configuration, parent_ref=self) setattr(self, name, instance) return instance except ImportError as e: raise AttributeError( f"Failed to import module {module_path} for attribute {name}: {e}" ) from e except AttributeError as e: raise AttributeError( f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}" ) from e raise AttributeError( f"'{type(self).__name__}' object has no attribute '{name}'" ) def __dir__(self): default_attrs = list(super().__dir__()) lazy_attrs = list(self._sub_sdk_map.keys()) return sorted(list(set(default_attrs + lazy_attrs))) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if ( self.sdk_configuration.client is not None and not self.sdk_configuration.client_supplied ): self.sdk_configuration.client.close() self.sdk_configuration.client = None class GenAIWithRawResponse: def __init__(self, sdk: GenAI) -> None: self._sdk = sdk @property def interactions(self): return self._sdk.interactions.with_raw_response @property def webhooks(self): return self._sdk.webhooks.with_raw_response @property def agents(self): return self._sdk.agents.with_raw_response class GenAIWithStreamingResponse: def __init__(self, sdk: GenAI) -> None: self._sdk = sdk @property def interactions(self): return self._sdk.interactions.with_streaming_response @property def webhooks(self): return self._sdk.webhooks.with_streaming_response @property def agents(self): return self._sdk.agents.with_streaming_response class AsyncGenAI(AsyncBaseSDK): r"""Gemini API: The Gemini Interactions API allows developers to build generative AI applications using Gemini models. Gemini is our most capable model, built from the ground up to be multimodal. It can generalize and seamlessly understand, operate across, and combine different types of information including language, images, audio, video, and code. You can use the Gemini API for use cases like reasoning across text and images, content generation, dialogue agents, summarization and classification systems, and more.""" @property def with_raw_response(self): return AsyncGenAIWithRawResponse(self) @property def with_streaming_response(self): return AsyncGenAIWithStreamingResponse(self) interactions: "AsyncInteractions" webhooks: "AsyncWebhooks" agents: "AsyncAgents" _sub_sdk_map = { "interactions": (".interactions", "AsyncInteractions"), "webhooks": (".webhooks", "AsyncWebhooks"), "agents": (".agents", "AsyncAgents"), } def __init__( self, security: Optional[Union[types.Security, Callable[[], types.Security]]] = None, api_version: Optional[str] = None, api_revision: Optional[str] = None, user_project: Optional[str] = None, server_idx: Optional[int] = None, url_params: Optional[Dict[str, str]] = None, server_url: Optional[str] = None, async_client: Optional[AsyncHttpClient] = None, retry_config: OptionalNullable[RetryConfig] = UNSET, timeout_ms: Optional[int] = None, debug_logger: Optional[Logger] = None, ) -> None: r"""Instantiates the SDK configuring it with the provided parameters. :param security: The security details required for authentication :param api_version: Configures the api_version parameter for all supported operations :param api_revision: Configures the api_revision parameter for all supported operations :param user_project: Configures the user_project parameter for all supported operations :param server_idx: The index of the server to use for all methods :param server_url: The server URL to use for all methods :param url_params: Parameters to optionally template the server URL with :param async_client: The Async HTTP client to use for all asynchronous methods :param retry_config: The retry configuration to use for all supported methods :param timeout_ms: Optional request timeout applied to each operation in milliseconds """ async_client_supplied = True if async_client is None: async_client = httpx.AsyncClient(follow_redirects=True) async_client_supplied = False if debug_logger is None: debug_logger = get_default_logger() assert issubclass( type(async_client), AsyncHttpClient ), "The provided async_client must implement the AsyncHttpClient protocol." if server_url is not None: if url_params is not None: server_url = utils.template_url(server_url, url_params) _globals = models.internal.Globals( api_version=utils.get_global_from_env( api_version, "GOOGLE_GENAI_API_VERSION", str ), api_revision=utils.get_global_from_env( api_revision, "GOOGLE_GENAI_API_REVISION", str ), user_project=utils.get_global_from_env( user_project, "GOOGLE_GENAI_USER_PROJECT", str ), ) AsyncBaseSDK.__init__( self, SDKConfiguration( client=None, client_supplied=False, async_client=async_client, async_client_supplied=async_client_supplied, globals=_globals, security=security, server_url=server_url, server_idx=server_idx, retry_config=retry_config, timeout_ms=timeout_ms, debug_logger=debug_logger, ), parent_ref=self, ) hooks = SDKHooks() async_hooks = AsyncSDKHooks() # pylint: disable=protected-access self.sdk_configuration.__dict__["_hooks"] = hooks self.sdk_configuration.__dict__["_async_hooks"] = async_hooks init_async_hooks(async_hooks) self.sdk_configuration = hooks.sdk_init(self.sdk_configuration) weakref.finalize( self, close_clients_async, cast(ClientOwner, self.sdk_configuration), self.sdk_configuration.async_client, self.sdk_configuration.async_client_supplied, ) def dynamic_import(self, modname, retries=3): for attempt in range(retries): try: return importlib.import_module(modname, package=__package__) except KeyError: # Clear any half-initialized module and retry resolved = importlib.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 __getattr__(self, name: str): if name in self._sub_sdk_map: module_path, class_name = self._sub_sdk_map[name] try: module = self.dynamic_import(module_path) klass = getattr(module, class_name) instance = klass(self.sdk_configuration, parent_ref=self) setattr(self, name, instance) return instance except ImportError as e: raise AttributeError( f"Failed to import module {module_path} for attribute {name}: {e}" ) from e except AttributeError as e: raise AttributeError( f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}" ) from e raise AttributeError( f"'{type(self).__name__}' object has no attribute '{name}'" ) def __dir__(self): default_attrs = list(super().__dir__()) lazy_attrs = list(self._sub_sdk_map.keys()) return sorted(list(set(default_attrs + lazy_attrs))) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_val, exc_tb): if ( self.sdk_configuration.async_client is not None and not self.sdk_configuration.async_client_supplied ): await self.sdk_configuration.async_client.aclose() self.sdk_configuration.async_client = None class AsyncGenAIWithRawResponse: def __init__(self, sdk: AsyncGenAI) -> None: self._sdk = sdk @property def interactions(self): return self._sdk.interactions.with_raw_response @property def webhooks(self): return self._sdk.webhooks.with_raw_response @property def agents(self): return self._sdk.agents.with_raw_response class AsyncGenAIWithStreamingResponse: def __init__(self, sdk: AsyncGenAI) -> None: self._sdk = sdk @property def interactions(self): return self._sdk.interactions.with_streaming_response @property def webhooks(self): return self._sdk.webhooks.with_streaming_response @property def agents(self): return self._sdk.agents.with_streaming_response