|
13 | 13 | # limitations under the License. |
14 | 14 | # |
15 | 15 |
|
| 16 | +import asyncio |
16 | 17 | import importlib |
17 | 18 | from typing import Optional, Union, Any |
| 19 | +from types import TracebackType |
18 | 20 |
|
19 | 21 | import google.auth |
20 | 22 | from google.cloud.aiplatform import version as aip_version |
@@ -48,7 +50,7 @@ def _add_tracking_headers(headers: dict[str, str]) -> None: |
48 | 50 | class AsyncClient: |
49 | 51 | """Async Gen AI Client for the Vertex SDK.""" |
50 | 52 |
|
51 | | - def __init__(self, api_client: genai_client.Client): |
| 53 | + def __init__(self, api_client: genai_client.BaseApiClient): |
52 | 54 | self._api_client = api_client |
53 | 55 | self._live = live.AsyncLive(self._api_client) |
54 | 56 | self._evals = None |
@@ -132,6 +134,40 @@ def datasets(self): |
132 | 134 | ) |
133 | 135 | return self._datasets.AsyncDatasets(self._api_client) |
134 | 136 |
|
| 137 | + async def aclose(self) -> None: |
| 138 | + """Closes the async client explicitly. |
| 139 | +
|
| 140 | + Example usage: |
| 141 | +
|
| 142 | + from vertexai import Client |
| 143 | +
|
| 144 | + async_client = vertexai.Client( |
| 145 | + project='my-project-id', location='us-central1' |
| 146 | + ).aio |
| 147 | + prompt_1 = await async_client.prompts.create(...) |
| 148 | + prompt_2 = await async_client.prompts.create(...) |
| 149 | + # Close the client to release resources. |
| 150 | + await async_client.aclose() |
| 151 | + """ |
| 152 | + await self._api_client.aclose() |
| 153 | + |
| 154 | + async def __aenter__(self) -> "AsyncClient": |
| 155 | + return self |
| 156 | + |
| 157 | + async def __aexit__( |
| 158 | + self, |
| 159 | + exc_type: Optional[Exception], |
| 160 | + exc_value: Optional[Exception], |
| 161 | + traceback: Optional[TracebackType], |
| 162 | + ) -> None: |
| 163 | + await self.aclose() |
| 164 | + |
| 165 | + def __del__(self) -> None: |
| 166 | + try: |
| 167 | + asyncio.get_running_loop().create_task(self.aclose()) |
| 168 | + except Exception: |
| 169 | + pass |
| 170 | + |
135 | 171 |
|
136 | 172 | class Client: |
137 | 173 | """Gen AI Client for the Vertex SDK. |
|
0 commit comments