-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
VertexAI.java
369 lines (319 loc) · 12.4 KB
/
VertexAI.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.vertexai;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.auth.Credentials;
import com.google.cloud.vertexai.api.LlmUtilityServiceClient;
import com.google.cloud.vertexai.api.LlmUtilityServiceSettings;
import com.google.cloud.vertexai.api.PredictionServiceClient;
import com.google.cloud.vertexai.api.PredictionServiceSettings;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class holds default settings and credentials to make Vertex AI API calls.
*
* <p><b>Note:</b> The VertexAI instance will start a service client when the first API call is
* made. Please close the VertexAI instance after making any API calls so that clients get closed as
* well.
*
* <pre>{@code
* try (VertexAI vertexAi = new VertexAI("my-project", "us-central1"); ) {
* GenerativeModel model = new GenerativeModel("gemini-pro", vertexAi)
* // Do something with the model.
* }
* }</pre>
*/
public class VertexAI implements AutoCloseable {
private final String projectId;
private final String location;
private final String apiEndpoint;
private final Transport transport;
private final CredentialsProvider credentialsProvider;
private final transient Supplier<PredictionServiceClient> predictionClientSupplier;
private final transient Supplier<LlmUtilityServiceClient> llmClientSupplier;
/**
* Constructs a VertexAI instance.
*
* @param projectId the default project to use when making API calls
* @param location the default location to use when making API calls
*/
public VertexAI(String projectId, String location) {
this(
projectId,
location,
Transport.GRPC,
ImmutableList.of(),
/* credentials= */ Optional.empty(),
/* apiEndpoint= */ Optional.empty(),
/* predictionClientSupplierOpt= */ Optional.empty(),
/* llmClientSupplierOpt= */ Optional.empty());
}
private VertexAI(
String projectId,
String location,
Transport transport,
List<String> scopes,
Optional<Credentials> credentials,
Optional<String> apiEndpoint,
Optional<Supplier<PredictionServiceClient>> predictionClientSupplierOpt,
Optional<Supplier<LlmUtilityServiceClient>> llmClientSupplierOpt) {
if (!scopes.isEmpty() && credentials.isPresent()) {
throw new IllegalArgumentException(
"At most one of Credentials and scopes should be specified.");
}
checkArgument(!Strings.isNullOrEmpty(projectId), "projectId can't be null or empty");
checkArgument(!Strings.isNullOrEmpty(location), "location can't be null or empty");
checkNotNull(transport, "transport can't be null");
this.projectId = projectId;
this.location = location;
this.transport = transport;
if (credentials.isPresent()) {
this.credentialsProvider = FixedCredentialsProvider.create(credentials.get());
} else {
this.credentialsProvider =
scopes.isEmpty()
? PredictionServiceSettings.defaultCredentialsProviderBuilder().build()
: GoogleCredentialsProvider.newBuilder()
.setScopesToApply(scopes)
.setUseJwtAccessWithScope(true)
.build();
}
this.predictionClientSupplier =
Suppliers.memoize(predictionClientSupplierOpt.orElse(this::newPredictionServiceClient));
this.llmClientSupplier =
Suppliers.memoize(llmClientSupplierOpt.orElse(this::newLlmUtilityClient));
this.apiEndpoint = apiEndpoint.orElse(String.format("%s-aiplatform.googleapis.com", location));
}
public static Builder builder() {
return new Builder();
}
/** Builder for {@link VertexAI}. */
public static class Builder {
private String projectId;
private String location;
private Transport transport = Transport.GRPC;
private ImmutableList<String> scopes = ImmutableList.of();
private Optional<Credentials> credentials = Optional.empty();
private Optional<String> apiEndpoint = Optional.empty();
private Supplier<PredictionServiceClient> predictionClientSupplier;
private Supplier<LlmUtilityServiceClient> llmClientSupplier;
Builder() {}
public VertexAI build() {
checkNotNull(projectId, "projectId must be set.");
checkNotNull(location, "location must be set.");
return new VertexAI(
projectId,
location,
transport,
scopes,
credentials,
apiEndpoint,
Optional.ofNullable(predictionClientSupplier),
Optional.ofNullable(llmClientSupplier));
}
public Builder setProjectId(String projectId) {
checkArgument(!Strings.isNullOrEmpty(projectId), "projectId can't be null or empty");
this.projectId = projectId;
return this;
}
public Builder setLocation(String location) {
checkArgument(!Strings.isNullOrEmpty(location), "location can't be null or empty");
this.location = location;
return this;
}
public Builder setApiEndpoint(String apiEndpoint) {
checkArgument(!Strings.isNullOrEmpty(apiEndpoint), "apiEndpoint can't be null or empty");
this.apiEndpoint = Optional.of(apiEndpoint);
return this;
}
public Builder setTransport(Transport transport) {
checkNotNull(transport, "transport can't be null");
this.transport = transport;
return this;
}
public Builder setCredentials(Credentials credentials) {
checkNotNull(credentials, "credentials can't be null");
this.credentials = Optional.of(credentials);
return this;
}
@CanIgnoreReturnValue
public Builder setPredictionClientSupplier(
Supplier<PredictionServiceClient> predictionClientSupplier) {
this.predictionClientSupplier = predictionClientSupplier;
return this;
}
@CanIgnoreReturnValue
public Builder setLlmClientSupplier(Supplier<LlmUtilityServiceClient> llmClientSupplier) {
this.llmClientSupplier = llmClientSupplier;
return this;
}
public Builder setScopes(List<String> scopes) {
checkNotNull(scopes, "scopes can't be null");
this.scopes = ImmutableList.copyOf(scopes);
return this;
}
}
/**
* Returns the default {@link Transport} layer to use to send API requests.
*
* @return {@link Transport} layer used when sending API requests.
*/
public Transport getTransport() {
return transport;
}
/**
* Returns the default project to use when making API calls.
*
* @return Project ID in string format.
*/
public String getProjectId() {
return projectId;
}
/**
* Returns the default location to use when making API calls.
*
* @return Location in string format.
*/
public String getLocation() {
return location;
}
/**
* Returns the default endpoint to use when making API calls.
*
* @return API endpoint in string format.
*/
public String getApiEndpoint() {
return apiEndpoint;
}
/**
* Returns the default credentials to use when making API calls.
*
* @return {@link Credentials} to use when making API calls.
*/
public Credentials getCredentials() throws IOException {
return credentialsProvider.getCredentials();
}
/**
* Returns the {@link PredictionServiceClient} with GRPC or REST, based on the Transport type. The
* client will be instantiated when the first prediction API call is made.
*
* @return {@link PredictionServiceClient} that send requests to the backing service through
* method calls that map to the API methods.
*/
@InternalApi
public PredictionServiceClient getPredictionServiceClient() {
return predictionClientSupplier.get();
}
private PredictionServiceClient newPredictionServiceClient() {
// Disable the warning message logged in getApplicationDefault
Logger defaultCredentialsProviderLogger =
Logger.getLogger("com.google.auth.oauth2.DefaultCredentialsProvider");
Level previousLevel = defaultCredentialsProviderLogger.getLevel();
defaultCredentialsProviderLogger.setLevel(Level.SEVERE);
try {
return PredictionServiceClient.create(getPredictionServiceSettings());
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
defaultCredentialsProviderLogger.setLevel(previousLevel);
}
}
private PredictionServiceSettings getPredictionServiceSettings() throws IOException {
PredictionServiceSettings.Builder builder;
if (transport == Transport.REST) {
builder = PredictionServiceSettings.newHttpJsonBuilder();
} else {
builder = PredictionServiceSettings.newBuilder();
}
builder.setEndpoint(String.format("%s:443", apiEndpoint));
builder.setCredentialsProvider(credentialsProvider);
HeaderProvider headerProvider =
FixedHeaderProvider.create(
"user-agent",
String.format(
"%s/%s",
Constants.USER_AGENT_HEADER,
GaxProperties.getLibraryVersion(PredictionServiceSettings.class)));
builder.setHeaderProvider(headerProvider);
return builder.build();
}
/**
* Returns the {@link LlmUtilityServiceClient} with GRPC or REST, based on the Transport type. The
* client will be instantiated when the first API call is made.
*
* @return {@link LlmUtilityServiceClient} that makes calls to the backing service through method
* calls that map to the API methods.
*/
@InternalApi
public LlmUtilityServiceClient getLlmUtilityClient() {
return llmClientSupplier.get();
}
private LlmUtilityServiceClient newLlmUtilityClient() {
// Disable the warning message logged in getApplicationDefault
Logger defaultCredentialsProviderLogger =
Logger.getLogger("com.google.auth.oauth2.DefaultCredentialsProvider");
Level previousLevel = defaultCredentialsProviderLogger.getLevel();
defaultCredentialsProviderLogger.setLevel(Level.SEVERE);
try {
return LlmUtilityServiceClient.create(getLlmUtilityServiceClientSettings());
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
defaultCredentialsProviderLogger.setLevel(previousLevel);
}
}
private LlmUtilityServiceSettings getLlmUtilityServiceClientSettings() throws IOException {
LlmUtilityServiceSettings.Builder settingsBuilder;
if (transport == Transport.REST) {
settingsBuilder = LlmUtilityServiceSettings.newHttpJsonBuilder();
} else {
settingsBuilder = LlmUtilityServiceSettings.newBuilder();
}
settingsBuilder.setEndpoint(String.format("%s:443", apiEndpoint));
settingsBuilder.setCredentialsProvider(credentialsProvider);
HeaderProvider headerProvider =
FixedHeaderProvider.create(
"user-agent",
String.format(
"%s/%s",
Constants.USER_AGENT_HEADER,
GaxProperties.getLibraryVersion(LlmUtilityServiceSettings.class)));
settingsBuilder.setHeaderProvider(headerProvider);
return settingsBuilder.build();
}
/** Closes the VertexAI instance together with all its instantiated clients. */
@Override
public void close() {
predictionClientSupplier.get().close();
llmClientSupplier.get().close();
}
}