Skip to content

Commit 7404f67

Browse files
matthew29tangcopybara-github
authored andcommitted
feat: Support api keys in initializer and create_client
PiperOrigin-RevId: 661401962
1 parent d352cec commit 7404f67

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

google/cloud/aiplatform/initializer.py

+25-3
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def _set_project_as_env_var_or_google_auth_default(self):
7474
the project and credentials have already been set.
7575
"""
7676

77-
if not self._project:
77+
if not self._project and not self._api_key:
7878
# Project is not set. Trying to get it from the environment.
7979
# See https://github.com/googleapis/python-aiplatform/issues/852
8080
# See https://github.com/googleapis/google-auth-library-python/issues/924
@@ -104,7 +104,7 @@ def _set_project_as_env_var_or_google_auth_default(self):
104104
self._credentials = self._credentials or credentials
105105
self._project = project
106106

107-
if not self._credentials:
107+
if not self._credentials and not self._api_key:
108108
credentials, _ = google.auth.default()
109109
self._credentials = credentials
110110

@@ -117,6 +117,7 @@ def __init__(self):
117117
self._network = None
118118
self._service_account = None
119119
self._api_endpoint = None
120+
self._api_key = None
120121
self._api_transport = None
121122
self._request_metadata = None
122123
self._resource_type = None
@@ -137,6 +138,7 @@ def init(
137138
network: Optional[str] = None,
138139
service_account: Optional[str] = None,
139140
api_endpoint: Optional[str] = None,
141+
api_key: Optional[str] = None,
140142
api_transport: Optional[str] = None,
141143
request_metadata: Optional[Sequence[Tuple[str, str]]] = None,
142144
):
@@ -197,6 +199,9 @@ def init(
197199
api_endpoint (str):
198200
Optional. The desired API endpoint,
199201
e.g., us-central1-aiplatform.googleapis.com
202+
api_key (str):
203+
Optional. The API key to use for service calls.
204+
NOTE: Not all services support API keys.
200205
api_transport (str):
201206
Optional. The transport method which is either 'grpc' or 'rest'.
202207
NOTE: "rest" transport functionality is currently in a
@@ -252,6 +257,8 @@ def init(
252257
self._service_account = service_account
253258
if request_metadata is not None:
254259
self._request_metadata = request_metadata
260+
if api_key is not None:
261+
self._api_key = api_key
255262
self._resource_type = None
256263

257264
# Finally, perform secondary state updates
@@ -304,6 +311,11 @@ def api_endpoint(self) -> Optional[str]:
304311
"""Default API endpoint, if provided."""
305312
return self._api_endpoint
306313

314+
@property
315+
def api_key(self) -> Optional[str]:
316+
"""API Key, if provided."""
317+
return self._api_key
318+
307319
@property
308320
def project(self) -> str:
309321
"""Default project."""
@@ -325,7 +337,7 @@ def project(self) -> str:
325337
except GoogleAuthError as exc:
326338
raise GoogleAuthError(project_not_found_exception_str) from exc
327339

328-
if not project_id:
340+
if not project_id and not self.api_key:
329341
raise ValueError(project_not_found_exception_str)
330342

331343
return project_id
@@ -403,6 +415,7 @@ def get_client_options(
403415
location_override: Optional[str] = None,
404416
prediction_client: bool = False,
405417
api_base_path_override: Optional[str] = None,
418+
api_key: Optional[str] = None,
406419
api_path_override: Optional[str] = None,
407420
) -> client_options.ClientOptions:
408421
"""Creates GAPIC client_options using location and type.
@@ -414,6 +427,7 @@ def get_client_options(
414427
Vertex AI.
415428
prediction_client (str): Optional. flag to use a prediction endpoint.
416429
api_base_path_override (str): Optional. Override default API base path.
430+
api_key (str): Optional. API key to use for the client.
417431
api_path_override (str): Optional. Override default api path.
418432
Returns:
419433
clients_options (google.api_core.client_options.ClientOptions):
@@ -447,6 +461,11 @@ def get_client_options(
447461
else api_path_override
448462
)
449463

464+
# Project/location take precedence over api_key
465+
if api_key and not self._project:
466+
return client_options.ClientOptions(
467+
api_endpoint=api_endpoint, api_key=api_key
468+
)
450469
return client_options.ClientOptions(api_endpoint=api_endpoint)
451470

452471
def common_location_path(
@@ -479,6 +498,7 @@ def create_client(
479498
location_override: Optional[str] = None,
480499
prediction_client: bool = False,
481500
api_base_path_override: Optional[str] = None,
501+
api_key: Optional[str] = None,
482502
api_path_override: Optional[str] = None,
483503
appended_user_agent: Optional[List[str]] = None,
484504
appended_gapic_version: Optional[str] = None,
@@ -493,6 +513,7 @@ def create_client(
493513
Optional. Custom auth credentials. If not provided will use the current config.
494514
location_override (str): Optional. location override.
495515
prediction_client (str): Optional. flag to use a prediction endpoint.
516+
api_key (str): Optional. API key to use for the client.
496517
api_base_path_override (str): Optional. Override default api base path.
497518
api_path_override (str): Optional. Override default api path.
498519
appended_user_agent (List[str]):
@@ -539,6 +560,7 @@ def create_client(
539560
"client_options": self.get_client_options(
540561
location_override=location_override,
541562
prediction_client=prediction_client,
563+
api_key=api_key,
542564
api_base_path_override=api_base_path_override,
543565
api_path_override=api_path_override,
544566
),

vertexai/generative_models/_generative_models.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ def _get_resource_name_from_model_name(
126126
) -> str:
127127
"""Returns the full resource name starting with projects/ given a model name."""
128128
if model_name.startswith("publishers/"):
129+
if not project:
130+
return model_name
129131
return f"projects/{project}/locations/{location}/{model_name}"
130132
elif model_name.startswith("projects/"):
131133
return model_name
@@ -337,7 +339,7 @@ def __init__(
337339

338340
location = aiplatform_utils.extract_project_and_location_from_parent(
339341
prediction_resource_name
340-
)["location"]
342+
).get("location")
341343

342344
self._model_name = model_name
343345
self._prediction_resource_name = prediction_resource_name

0 commit comments

Comments
 (0)