@@ -715,19 +715,23 @@ def __init__(
715715 self ._async_httpx_client = self ._http_options .httpx_async_client
716716 else :
717717 self ._async_httpx_client = AsyncHttpxClient (** async_client_args )
718+
719+ # Initialize the aiohttp client session.
720+ self ._aiohttp_session : Optional [aiohttp .ClientSession ] = None
718721 if self ._use_aiohttp ():
719722 try :
720723 import aiohttp # pylint: disable=g-import-not-at-top
721- # Do it once at the genai.Client level. Share among all requests.
722- self ._async_client_session_request_args = self ._ensure_aiohttp_ssl_ctx (
723- self ._http_options
724- )
724+
725+ if self ._http_options .aiohttp_client :
726+ self ._aiohttp_session = self ._http_options .aiohttp_client
727+ else :
728+ # Do it once at the genai.Client level. Share among all requests.
729+ self ._async_client_session_request_args = (
730+ self ._ensure_aiohttp_ssl_ctx (self ._http_options )
731+ )
725732 except ImportError :
726733 pass
727734
728- # Initialize the aiohttp client session.
729- self ._aiohttp_session : Optional [aiohttp .ClientSession ] = None
730-
731735 retry_kwargs = retry_args (self ._http_options .retry_options )
732736 self ._websocket_ssl_ctx = self ._ensure_websocket_ssl_ctx (self ._http_options )
733737 self ._retry = tenacity .Retrying (** retry_kwargs )
@@ -1892,7 +1896,7 @@ async def aclose(self) -> None:
18921896 # close the client when the object is garbage collected.
18931897 if not self ._http_options .httpx_async_client :
18941898 await self ._async_httpx_client .aclose ()
1895- if self ._aiohttp_session :
1899+ if self ._aiohttp_session and not self . _http_options . aiohttp_client :
18961900 await self ._aiohttp_session .close ()
18971901
18981902 def __del__ (self ) -> None :
0 commit comments