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@0dd088e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • google/cloud/aiplatform
    • models.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
+168-31Lines changed: 168 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
# limitations under the License.
1616
#
1717
import itertools
18+
import httpx
1819
import json
1920
import pathlib
2021
import re
2122
import shutil
23+
import string
2224
import tempfile
2325
import requests
2426
from typing import (
@@ -626,6 +628,7 @@ def __init__(
626628
self._gca_resource = gca_endpoint_compat.Endpoint(name=endpoint_name)
627629

628630
self.authorized_session = None
631+
self.httpx_async_client = None
629632
self.raw_predict_request_url = None
630633
self.stream_raw_predict_request_url = None
631634

@@ -717,6 +720,18 @@ def private_service_connect_config(
717720
self._assert_gca_resource_is_available()
718721
return self._gca_resource.private_service_connect_config
719722

723+
@property
724+
def dedicated_endpoint_dns(self) -> string:
725+
"""The dedicated DNS for this Endpoint."""
726+
self._assert_gca_resource_is_available()
727+
return self._gca_resource.dedicated_endpoint_dns
728+
729+
@property
730+
def dedicated_endpoint_enabled(self) -> bool:
731+
"""Whether this endpoint is a dedicated endpoint."""
732+
self._assert_gca_resource_is_available()
733+
return self._gca_resource.dedicated_endpoint_enabled
734+
720735
@classmethod
721736
def create(
722737
cls,
@@ -734,6 +749,7 @@ def create(
734749
enable_request_response_logging=False,
735750
request_response_logging_sampling_rate: Optional[float] = None,
736751
request_response_logging_bq_destination_table: Optional[str] = None,
752+
dedicated_endpoint_enabled=False,
737753
) -> "Endpoint":
738754
"""Creates a new endpoint.
739755
@@ -801,6 +817,10 @@ def create(
801817
request_response_logging_bq_destination_table (str):
802818
Optional. The request response logging bigquery destination. If not set, will create a table with name:
803819
``bq://{project_id}.logging_{endpoint_display_name}_{endpoint_id}.request_response_logging``.
820+
dedicated_endpoint_enabled (bool):
821+
Optional. If enabled, a dedicated dns will be created and your
822+
traffic will be fully isolated from other customers' traffic and
823+
latency will be significantly reduced.
804824
805825
Returns:
806826
endpoint (aiplatform.Endpoint):
@@ -845,6 +865,7 @@ def create(
845865
create_request_timeout=create_request_timeout,
846866
endpoint_id=endpoint_id,
847867
predict_request_response_logging_config=predict_request_response_logging_config,
868+
dedicated_endpoint_enabled=dedicated_endpoint_enabled,
848869
)
849870

850871
@classmethod
@@ -870,6 +891,7 @@ def _create(
870891
private_service_connect_config: Optional[
871892
gca_service_networking.PrivateServiceConnectConfig
872893
] = None,
894+
dedicated_endpoint_enabled=False,
873895
) -> "Endpoint":
874896
"""Creates a new endpoint by calling the API client.
875897
@@ -936,6 +958,10 @@ def _create(
936958
private_service_connect_config (aiplatform.service_network.PrivateServiceConnectConfig):
937959
If enabled, the endpoint can be accessible via [Private Service Connect](https://cloud.google.com/vpc/docs/private-service-connect).
938960
Cannot be enabled when network is specified.
961+
dedicated_endpoint_enabled (bool):
962+
Optional. If enabled, a dedicated dns will be created and your
963+
traffic will be fully isolated from other customers' traffic and
964+
latency will be significantly reduced.
939965
940966
Returns:
941967
endpoint (aiplatform.Endpoint):
@@ -954,6 +980,7 @@ def _create(
954980
network=network,
955981
predict_request_response_logging_config=predict_request_response_logging_config,
956982
private_service_connect_config=private_service_connect_config,
983+
dedicated_endpoint_enabled=dedicated_endpoint_enabled,
957984
)
958985

959986
operation_future = api_client.create_endpoint(
@@ -1012,6 +1039,7 @@ def _construct_sdk_resource_from_gapic(
10121039
credentials=credentials,
10131040
)
10141041
endpoint.authorized_session = None
1042+
endpoint.httpx_async_client = None
10151043
endpoint.raw_predict_request_url = None
10161044
endpoint.stream_raw_predict_request_url = None
10171045

@@ -2101,6 +2129,42 @@ def predict(
21012129
_RAW_PREDICT_MODEL_VERSION_ID_KEY, None
21022130
),
21032131
)
2132+
if self.dedicated_endpoint_enabled:
2133+
if self.dedicated_endpoint_dns is None:
2134+
raise ValueError(
2135+
"Dedicated endpoint DNS is empty. Please make sure endpoint"
2136+
" and model are ready before making a prediction."
2137+
)
2138+
2139+
if not self.authorized_session:
2140+
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
2141+
self.authorized_session = google_auth_requests.AuthorizedSession(
2142+
self.credentials
2143+
)
2144+
2145+
headers = {
2146+
"Content-Type": "application/json",
2147+
}
2148+
2149+
url = f"https://{self.dedicated_endpoint_dns}/v1/{self.resource_name}:predict"
2150+
response = self.authorized_session.post(
2151+
url=url,
2152+
data=json.dumps({
2153+
"instances": instances,
2154+
"parameters": parameters,
2155+
}),
2156+
headers=headers,
2157+
)
2158+
2159+
prediction_response = json.loads(response.data)
2160+
2161+
return Prediction(
2162+
predictions=prediction_response.get("predictions"),
2163+
metadata=prediction_response.get("metadata"),
2164+
deployed_model_id=prediction_response.get("deployedModelId"),
2165+
model_resource_name=prediction_response.get("model"),
2166+
model_version_id=prediction_response.get("modelVersionId"),
2167+
)
21042168
else:
21052169
prediction_response = self._prediction_client.predict(
21062170
endpoint=self._gca_resource.name,
@@ -2166,27 +2230,65 @@ async def predict_async(
21662230
"""
21672231
self.wait()
21682232

2169-
prediction_response = await self._prediction_async_client.predict(
2170-
endpoint=self._gca_resource.name,
2171-
instances=instances,
2172-
parameters=parameters,
2173-
timeout=timeout,
2174-
)
2175-
if prediction_response._pb.metadata:
2176-
metadata = json_format.MessageToDict(prediction_response._pb.metadata)
2233+
if self.dedicated_endpoint_enabled:
2234+
if self.dedicated_endpoint_dns is None:
2235+
raise ValueError(
2236+
"Dedicated endpoint DNS is empty. Please make sure endpoint"
2237+
" and model are ready before making a prediction."
2238+
)
2239+
2240+
if not self.httpx_async_client:
2241+
self.credentials._scopes = constants.base.DEFAULT_AUTHED_SCOPES
2242+
self.httpx_async_client = httpx.AsyncClient(
2243+
auth=self.credentials,
2244+
)
2245+
2246+
headers = {
2247+
"Content-Type": "application/json",
2248+
}
2249+
2250+
url = f"https://{self.dedicated_endpoint_dns}/v1/{self.resource_name}:predict"
2251+
async with self.httpx_async_client as client:
2252+
response = (await client.post(
2253+
url=url,
2254+
data=json.dumps({
2255+
"instances": instances,
2256+
"parameters": parameters,
2257+
}),
2258+
headers=headers
2259+
)).json()
2260+
2261+
prediction_response = json.loads(response.data)
2262+
2263+
return Prediction(
2264+
predictions=prediction_response.get("predictions"),
2265+
metadata=prediction_response.get("metadata"),
2266+
deployed_model_id=prediction_response.get("deployedModelId"),
2267+
model_resource_name=prediction_response.get("model"),
2268+
model_version_id=prediction_response.get("modelVersionId"),
2269+
)
21772270
else:
2178-
metadata = None
2271+
prediction_response = await self._prediction_async_client.predict(
2272+
endpoint=self._gca_resource.name,
2273+
instances=instances,
2274+
parameters=parameters,
2275+
timeout=timeout,
2276+
)
2277+
if prediction_response._pb.metadata:
2278+
metadata = json_format.MessageToDict(prediction_response._pb.metadata)
2279+
else:
2280+
metadata = None
21792281

2180-
return Prediction(
2181-
predictions=[
2182-
json_format.MessageToDict(item)
2183-
for item in prediction_response.predictions.pb
2184-
],
2185-
metadata=metadata,
2186-
deployed_model_id=prediction_response.deployed_model_id,
2187-
model_version_id=prediction_response.model_version_id,
2188-
model_resource_name=prediction_response.model,
2189-
)
2282+
return Prediction(
2283+
predictions=[
2284+
json_format.MessageToDict(item)
2285+
for item in prediction_response.predictions.pb
2286+
],
2287+
metadata=metadata,
2288+
deployed_model_id=prediction_response.deployed_model_id,
2289+
model_version_id=prediction_response.model_version_id,
2290+
model_resource_name=prediction_response.model,
2291+
)
21902292

21912293
def raw_predict(
21922294
self, body: bytes, headers: Dict[str, str]
@@ -2220,9 +2322,17 @@ def raw_predict(
22202322
if self.raw_predict_request_url is None:
22212323
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"
22222324

2223-
return self.authorized_session.post(
2224-
url=self.raw_predict_request_url, data=body, headers=headers
2225-
)
2325+
url = self.raw_predict_request_url
2326+
2327+
if self.dedicated_endpoint_enabled:
2328+
if self.dedicated_endpoint_dns is None:
2329+
raise ValueError(
2330+
"Dedicated endpoint DNS is empty. Please make sure endpoint"
2331+
" and model are ready before making a prediction."
2332+
)
2333+
url = f"https://{self.dedicated_endpoint_dns}/v1/{self.resource_name}:rawPredict"
2334+
2335+
return self.authorized_session.post(url=url, data=body, headers=headers)
22262336

22272337
def stream_raw_predict(
22282338
self, body: bytes, headers: Dict[str, str]
@@ -2261,8 +2371,18 @@ def stream_raw_predict(
22612371
if self.stream_raw_predict_request_url is None:
22622372
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"
22632373

2374+
url = self.raw_predict_request_url
2375+
2376+
if self.dedicated_endpoint_enabled:
2377+
if self.dedicated_endpoint_dns is None:
2378+
raise ValueError(
2379+
"Dedicated endpoint DNS is empty. Please make sure endpoint"
2380+
" and model are ready before making a prediction."
2381+
)
2382+
url = f"https://{self.dedicated_endpoint_dns}/v1/{self.resource_name}:rawPredict"
2383+
22642384
with self.authorized_session.post(
2265-
url=self.stream_raw_predict_request_url,
2385+
url=url,
22662386
data=body,
22672387
headers=headers,
22682388
stream=True,
@@ -2306,6 +2426,9 @@ def direct_predict(
23062426
"""
23072427
self.wait()
23082428

2429+
if self.dedicated_endpoint_enabled:
2430+
raise ValueError(
2431+
"This method is not supported for dedicated endpoints.")
23092432
prediction_response = self._prediction_client.direct_predict(
23102433
request={
23112434
"endpoint": self._gca_resource.name,
@@ -2369,6 +2492,9 @@ async def direct_predict_async(
23692492
"""
23702493
self.wait()
23712494

2495+
if self.dedicated_endpoint_enabled:
2496+
raise ValueError(
2497+
"This method is not supported for dedicated endpoints.")
23722498
prediction_response = await self._prediction_async_client.direct_predict(
23732499
request={
23742500
"endpoint": self._gca_resource.name,
@@ -2424,6 +2550,9 @@ def stream_direct_predict(
24242550
The resulting streamed predictions.
24252551
"""
24262552
self.wait()
2553+
if self.dedicated_endpoint_enabled:
2554+
raise ValueError(
2555+
"This method is not supported for dedicated endpoints.")
24272556
for resp in self._prediction_client.stream_direct_predict(
24282557
requests=(
24292558
{
@@ -2474,6 +2603,9 @@ def direct_raw_predict(
24742603
"""
24752604
self.wait()
24762605

2606+
if self.dedicated_endpoint_enabled:
2607+
raise ValueError(
2608+
"This method is not supported for dedicated endpoints.")
24772609
prediction_response = self._prediction_client.direct_raw_predict(
24782610
request={
24792611
"endpoint": self._gca_resource.name,
@@ -2520,6 +2652,9 @@ async def direct_raw_predict_async(
25202652
"""
25212653
self.wait()
25222654

2655+
if self.dedicated_endpoint_enabled:
2656+
raise ValueError(
2657+
"This method is not supported for dedicated endpoints.")
25232658
prediction_response = await self._prediction_async_client.direct_raw_predict(
25242659
request={
25252660
"endpoint": self._gca_resource.name,
@@ -2569,6 +2704,9 @@ def stream_direct_raw_predict(
25692704
"""
25702705
self.wait()
25712706

2707+
if self.dedicated_endpoint_enabled:
2708+
raise ValueError(
2709+
"This method is not supported for dedicated endpoints.")
25722710
for resp in self._prediction_client.stream_direct_raw_predict(
25732711
requests=(
25742712
{
@@ -2632,6 +2770,9 @@ def explain(
26322770
"""
26332771
self.wait()
26342772

2773+
if self.dedicated_endpoint_enabled:
2774+
raise ValueError(
2775+
"This method is not supported for dedicated endpoints.")
26352776
explain_response = self._prediction_client.explain(
26362777
endpoint=self.resource_name,
26372778
instances=instances,
@@ -2696,6 +2837,9 @@ async def explain_async(
26962837
"""
26972838
self.wait()
26982839

2840+
if self.dedicated_endpoint_enabled:
2841+
raise ValueError(
2842+
"This method is not supported for dedicated endpoints.")
26992843
explain_response = await self._prediction_async_client.explain(
27002844
endpoint=self.resource_name,
27012845
instances=instances,
@@ -3403,19 +3547,12 @@ def raw_predict(
34033547
"Invalid endpoint override provided. Please only use IP"
34043548
"address or DNS."
34053549
)
3406-
if not self.credentials.valid:
3407-
self.credentials.refresh(google_auth_requests.Request())
3408-
3409-
token = self.credentials.token
3410-
headers_with_token = dict(headers)
3411-
headers_with_token["Authorization"] = f"Bearer {token}"
3412-
34133550
url = f"https://{endpoint_override}/v1/projects/{self.project}/locations/{self.location}/endpoints/{self.name}:rawPredict"
34143551
return self._http_request(
34153552
method="POST",
34163553
url=url,
34173554
body=body,
3418-
headers=headers_with_token,
3555+
headers=headers,
34193556
)
34203557

34213558
def explain(self):

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.