GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: Use the dedicated endpoint DNS to access the Prediction Dedicat… · googleapis/python-aiplatform@d4dab5d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • google/cloud/aiplatform
    • models.py
  • setup.py
  • tests/unit/aiplatform
    • test_endpoints.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎google/cloud/aiplatform/models.py‎

Copy file name to clipboardExpand all lines: google/cloud/aiplatform/models.py
+164-6Lines changed: 164 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# limitations under the License.
1616
#
1717
import itertools
18+
import httpx
1819
import json
1920
import pathlib
2021
import re
@@ -674,6 +675,7 @@ def __init__(
674675
self._gca_resource = gca_endpoint_compat.Endpoint(name=endpoint_name)
675676

676677
self.authorized_session = None
678+
self.httpx_async_client = None
677679
self.raw_predict_request_url = None
678680
self.stream_raw_predict_request_url = None
679681

@@ -782,6 +784,7 @@ def create(
782784
enable_request_response_logging=False,
783785
request_response_logging_sampling_rate: Optional[float] = None,
784786
request_response_logging_bq_destination_table: Optional[str] = None,
787+
dedicated_endpoint_enabled=False,
785788
) -> "Endpoint":
786789
"""Creates a new endpoint.
787790
@@ -849,6 +852,10 @@ def create(
849852
request_response_logging_bq_destination_table (str):
850853
Optional. The request response logging bigquery destination. If not set, will create a table with name:
851854
``bq://{project_id}.logging_{endpoint_display_name}_{endpoint_id}.request_response_logging``.
855+
dedicated_endpoint_enabled (bool):
856+
Optional. If enabled, a dedicated dns will be created and your
857+
traffic will be fully isolated from other customers' traffic and
858+
latency will be significantly reduced.
852859
853860
Returns:
854861
endpoint (aiplatform.Endpoint):
@@ -893,6 +900,7 @@ def create(
893900
create_request_timeout=create_request_timeout,
894901
endpoint_id=endpoint_id,
895902
predict_request_response_logging_config=predict_request_response_logging_config,
903+
dedicated_endpoint_enabled=dedicated_endpoint_enabled,
896904
)
897905

898906
@classmethod
@@ -918,6 +926,7 @@ def _create(
918926
private_service_connect_config: Optional[
919927
gca_service_networking.PrivateServiceConnectConfig
920928
] = None,
929+
dedicated_endpoint_enabled=False,
921930
) -> "Endpoint":
922931
"""Creates a new endpoint by calling the API client.
923932
@@ -984,6 +993,10 @@ def _create(
984993
private_service_connect_config (aiplatform.service_network.PrivateServiceConnectConfig):
985994
If enabled, the endpoint can be accessible via [Private Service Connect](https://cloud.google.com/vpc/docs/private-service-connect).
986995
Cannot be enabled when network is specified.
996+
dedicated_endpoint_enabled (bool):
997+
Optional. If enabled, a dedicated dns will be created and your
998+
traffic will be fully isolated from other customers' traffic and
999+
latency will be significantly reduced.
9871000
9881001
Returns:
9891002
endpoint (aiplatform.Endpoint):
@@ -1002,6 +1015,7 @@ def _create(
10021015
network=network,
10031016
predict_request_response_logging_config=predict_request_response_logging_config,
10041017
private_service_connect_config=private_service_connect_config,
1018+
dedicated_endpoint_enabled=dedicated_endpoint_enabled,
10051019
)
10061020

10071021
operation_future = api_client.create_endpoint(
@@ -1060,6 +1074,7 @@ def _construct_sdk_resource_from_gapic(
10601074
credentials=credentials,
10611075
)
10621076
endpoint.authorized_session = None
1077+
endpoint.httpx_async_client = None
10631078
endpoint.raw_predict_request_url = None
10641079
endpoint.stream_raw_predict_request_url = None
10651080

@@ -2167,6 +2182,7 @@ def predict(
21672182
parameters: Optional[Dict] = None,
21682183
timeout: Optional[float] = None,
21692184
use_raw_predict: Optional[bool] = False,
2185+
use_dedicated_endpoint: Optional[bool] = False,
21702186
) -> Prediction:
21712187
"""Make a prediction against this Endpoint.
21722188
@@ -2194,6 +2210,9 @@ def predict(
21942210
use_raw_predict (bool):
21952211
Optional. Default value is False. If set to True, the underlying prediction call will be made
21962212
against Endpoint.raw_predict().
2213+
use_dedicated_endpoint (bool):
2214+
Optional. Default value is False. If set to True, the underlying prediction call will be made
2215+
using the dedicated endpoint dns.
21972216
21982217
Returns:
21992218
prediction (aiplatform.Prediction):
@@ -2219,6 +2238,51 @@ def predict(
22192238
_RAW_PREDICT_MODEL_VERSION_ID_KEY, None
22202239
),
22212240
)
2241+
2242+
if use_dedicated_endpoint:
2243+
self._sync_gca_resource_if_skipped()
2244+
if (
2245+
not self._gca_resource.dedicated_endpoint_enabled
2246+
or self._gca_resource.dedicated_endpoint_dns is None
2247+
):
2248+
raise ValueError(
2249+
"Dedicated endpoint is not enabled or DNS is empty."
2250+
"Please make sure endpoint has dedicated endpoint enabled"
2251+
"and model are ready before making a prediction."
2252+
)
2253+
2254+
if not self.authorized_session:
2255+
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
2256+
self.authorized_session = google_auth_requests.AuthorizedSession(
2257+
self.credentials
2258+
)
2259+
2260+
headers = {
2261+
"Content-Type": "application/json",
2262+
}
2263+
2264+
url = f"https://{self._gca_resource.dedicated_endpoint_dns}/v1/{self.resource_name}:predict"
2265+
response = self.authorized_session.post(
2266+
url=url,
2267+
data=json.dumps(
2268+
{
2269+
"instances": instances,
2270+
"parameters": parameters,
2271+
}
2272+
),
2273+
headers=headers,
2274+
)
2275+
2276+
prediction_response = json.loads(response.text)
2277+
2278+
return Prediction(
2279+
predictions=prediction_response.get("predictions"),
2280+
metadata=prediction_response.get("metadata"),
2281+
deployed_model_id=prediction_response.get("deployedModelId"),
2282+
model_resource_name=prediction_response.get("model"),
2283+
model_version_id=prediction_response.get("modelVersionId"),
2284+
)
2285+
22222286
else:
22232287
prediction_response = self._prediction_client.predict(
22242288
endpoint=self._gca_resource.name,
@@ -2248,6 +2312,7 @@ async def predict_async(
22482312
*,
22492313
parameters: Optional[Dict] = None,
22502314
timeout: Optional[float] = None,
2315+
use_dedicated_endpoint: Optional[bool] = False,
22512316
) -> Prediction:
22522317
"""Make an asynchronous prediction against this Endpoint.
22532318
Example usage:
@@ -2277,13 +2342,66 @@ async def predict_async(
22772342
[PredictSchemata's][google.cloud.aiplatform.v1beta1.Model.predict_schemata]
22782343
``parameters_schema_uri``.
22792344
timeout (float): Optional. The timeout for this request in seconds.
2345+
use_dedicated_endpoint (bool):
2346+
Optional. Default value is False. If set to True, the underlying prediction call will be made
2347+
using the dedicated endpoint dns.
22802348
22812349
Returns:
22822350
prediction (aiplatform.Prediction):
22832351
Prediction with returned predictions and Model ID.
22842352
"""
22852353
self.wait()
22862354

2355+
if use_dedicated_endpoint:
2356+
self._sync_gca_resource_if_skipped()
2357+
if (
2358+
not self._gca_resource.dedicated_endpoint_enabled
2359+
or self._gca_resource.dedicated_endpoint_dns is None
2360+
):
2361+
raise ValueError(
2362+
"Dedicated endpoint is not enabled or DNS is empty."
2363+
"Please make sure endpoint has dedicated endpoint enabled"
2364+
"and model are ready before making a prediction."
2365+
)
2366+
2367+
if not self.httpx_async_client:
2368+
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
2369+
self.httpx_async_client = httpx.AsyncClient()
2370+
2371+
if not self.credentials.valid:
2372+
self.credentials.refresh(google_auth_requests.Request())
2373+
2374+
token = self.credentials.token
2375+
headers = {
2376+
"Authorization": f"Bearer {token}",
2377+
"Content-Type": "application/json",
2378+
}
2379+
2380+
url = f"https://{self._gca_resource.dedicated_endpoint_dns}/v1/{self.resource_name}:predict"
2381+
async with self.httpx_async_client as client:
2382+
response = (
2383+
await client.post(
2384+
url=url,
2385+
data=json.dumps(
2386+
{
2387+
"instances": instances,
2388+
"parameters": parameters,
2389+
}
2390+
),
2391+
headers=headers,
2392+
)
2393+
).json()
2394+
2395+
prediction_response = json.loads(response.text)
2396+
2397+
return Prediction(
2398+
predictions=prediction_response.get("predictions"),
2399+
metadata=prediction_response.get("metadata"),
2400+
deployed_model_id=prediction_response.get("deployedModelId"),
2401+
model_resource_name=prediction_response.get("model"),
2402+
model_version_id=prediction_response.get("modelVersionId"),
2403+
)
2404+
22872405
prediction_response = await self._prediction_async_client.predict(
22882406
endpoint=self._gca_resource.name,
22892407
instances=instances,
@@ -2307,7 +2425,10 @@ async def predict_async(
23072425
)
23082426

23092427
def raw_predict(
2310-
self, body: bytes, headers: Dict[str, str]
2428+
self,
2429+
body: bytes,
2430+
headers: Dict[str, str],
2431+
use_dedicated_endpoint: Optional[bool] = False,
23112432
) -> requests.models.Response:
23122433
"""Makes a prediction request using arbitrary headers.
23132434
@@ -2325,6 +2446,9 @@ def raw_predict(
23252446
The body of the prediction request in bytes. This must not exceed 1.5 mb per request.
23262447
headers (Dict[str, str]):
23272448
The header of the request as a dictionary. There are no restrictions on the header.
2449+
use_dedicated_endpoint (bool):
2450+
Optional. Default value is False. If set to True, the underlying prediction call will be made
2451+
using the dedicated endpoint dns.
23282452
23292453
Returns:
23302454
A requests.models.Response object containing the status code and prediction results.
@@ -2338,12 +2462,28 @@ def raw_predict(
23382462
if self.raw_predict_request_url is None:
23392463
self.raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:rawPredict"
23402464

2341-
return self.authorized_session.post(
2342-
url=self.raw_predict_request_url, data=body, headers=headers
2343-
)
2465+
url = self.raw_predict_request_url
2466+
2467+
if use_dedicated_endpoint:
2468+
self._sync_gca_resource_if_skipped()
2469+
if (
2470+
not self._gca_resource.dedicated_endpoint_enabled
2471+
or self._gca_resource.dedicated_endpoint_dns is None
2472+
):
2473+
raise ValueError(
2474+
"Dedicated endpoint is not enabled or DNS is empty."
2475+
"Please make sure endpoint has dedicated endpoint enabled"
2476+
"and model are ready before making a prediction."
2477+
)
2478+
url = f"https://{self._gca_resource.dedicated_endpoint_dns}/v1/{self.resource_name}:rawPredict"
2479+
2480+
return self.authorized_session.post(url=url, data=body, headers=headers)
23442481

23452482
def stream_raw_predict(
2346-
self, body: bytes, headers: Dict[str, str]
2483+
self,
2484+
body: bytes,
2485+
headers: Dict[str, str],
2486+
use_dedicated_endpoint: Optional[bool] = False,
23472487
) -> Iterator[requests.models.Response]:
23482488
"""Makes a streaming prediction request using arbitrary headers.
23492489
@@ -2365,6 +2505,9 @@ def stream_raw_predict(
23652505
headers (Dict[str, str]):
23662506
The header of the request as a dictionary. There are no
23672507
restrictions on the header.
2508+
use_dedicated_endpoint (bool):
2509+
Optional. Default value is False. If set to True, the underlying prediction call will be made
2510+
using the dedicated endpoint dns.
23682511
23692512
Yields:
23702513
predictions (Iterator[requests.models.Response]):
@@ -2379,8 +2522,23 @@ def stream_raw_predict(
23792522
if self.stream_raw_predict_request_url is None:
23802523
self.stream_raw_predict_request_url = f"https://{self.location}-{constants.base.API_BASE_PATH}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:streamRawPredict"
23812524

2525+
url = self.raw_predict_request_url
2526+
2527+
if use_dedicated_endpoint:
2528+
self._sync_gca_resource_if_skipped()
2529+
if (
2530+
not self._gca_resource.dedicated_endpoint_enabled
2531+
or self._gca_resource.dedicated_endpoint_dns is None
2532+
):
2533+
raise ValueError(
2534+
"Dedicated endpoint is not enabled or DNS is empty."
2535+
"Please make sure endpoint has dedicated endpoint enabled"
2536+
"and model are ready before making a prediction."
2537+
)
2538+
url = f"https://{self._gca_resource.dedicated_endpoint_dns}/v1/{self.resource_name}:streamRawPredict"
2539+
23822540
with self.authorized_session.post(
2383-
url=self.stream_raw_predict_request_url,
2541+
url=url,
23842542
data=body,
23852543
headers=headers,
23862544
stream=True,
Collapse file

‎setup.py‎

Copy file name to clipboardExpand all lines: setup.py
+6-2Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
"tensorflow >=2.3.0, <3.0.0dev; python_version<='3.11'"
5656
] + profiler_extra_require
5757

58-
metadata_extra_require = ["pandas >= 1.0.0", "numpy>=1.15.0"]
58+
metadata_extra_require = ["pandas >= 1.0.0", "numpy>=1.15.0, <2.0.0"]
5959
xai_extra_require = ["tensorflow >=2.3.0, <3.0.0dev"]
6060
lit_extra_require = [
6161
"tensorflow >= 2.3.0, <3.0.0dev",
@@ -89,7 +89,10 @@
8989
"uvicorn[standard] >= 0.16.0",
9090
]
9191

92-
endpoint_extra_require = ["requests >= 2.28.1"]
92+
endpoint_extra_require = [
93+
"requests >= 2.28.1",
94+
"httpx >=0.23.0, <0.25.0",
95+
]
9396

9497
private_endpoints_extra_require = [
9598
"urllib3 >=1.21.1, <1.27",
@@ -256,6 +259,7 @@
256259
"google-cloud-bigquery >= 1.15.0, < 4.0.0dev, !=3.20.0",
257260
"google-cloud-resource-manager >= 1.3.3, < 3.0.0dev",
258261
"shapely < 3.0.0dev",
262+
"httpx >=0.23.0, <0.25.0",
259263
)
260264
+ genai_requires,
261265
extras_require={

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.