使用 upload_model 方法上传模型。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
Java
在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Java 设置说明执行操作。如需了解详情,请参阅 Vertex AI Java API 参考文档。
如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.Model;
import com.google.cloud.aiplatform.v1.ModelContainerSpec;
import com.google.cloud.aiplatform.v1.ModelServiceClient;
import com.google.cloud.aiplatform.v1.ModelServiceSettings;
import com.google.cloud.aiplatform.v1.UploadModelOperationMetadata;
import com.google.cloud.aiplatform.v1.UploadModelResponse;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class UploadModelSample {
public static void main(String[] args)
throws InterruptedException, ExecutionException, TimeoutException, IOException {
// TODO(developer): Replace these variables before running the sample.
String project = "YOUR_PROJECT_ID";
String modelDisplayName = "YOUR_MODEL_DISPLAY_NAME";
String metadataSchemaUri =
"gs://google-cloud-aiplatform/schema/trainingjob/definition/custom_task_1.0.0.yaml";
String imageUri = "YOUR_IMAGE_URI";
String artifactUri = "gs://your-gcs-bucket/artifact_path";
uploadModel(project, modelDisplayName, metadataSchemaUri, imageUri, artifactUri);
}
static void uploadModel(
String project,
String modelDisplayName,
String metadataSchemaUri,
String imageUri,
String artifactUri)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
ModelServiceSettings modelServiceSettings =
ModelServiceSettings.newBuilder()
.setEndpoint("us-central1-aiplatform.googleapis.com:443")
.build();
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ModelServiceClient modelServiceClient = ModelServiceClient.create(modelServiceSettings)) {
String location = "us-central1";
LocationName locationName = LocationName.of(project, location);
ModelContainerSpec modelContainerSpec =
ModelContainerSpec.newBuilder().setImageUri(imageUri).build();
Model model =
Model.newBuilder()
.setDisplayName(modelDisplayName)
.setMetadataSchemaUri(metadataSchemaUri)
.setArtifactUri(artifactUri)
.setContainerSpec(modelContainerSpec)
.build();
OperationFuture<UploadModelResponse, UploadModelOperationMetadata> uploadModelResponseFuture =
modelServiceClient.uploadModelAsync(locationName, model);
System.out.format(
"Operation name: %s\n", uploadModelResponseFuture.getInitialFuture().get().getName());
System.out.println("Waiting for operation to finish...");
UploadModelResponse uploadModelResponse = uploadModelResponseFuture.get(5, TimeUnit.MINUTES);
System.out.println("Upload Model Response");
System.out.format("Model: %s\n", uploadModelResponse.getModel());
}
}
}
Node.js
在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Node.js 设置说明执行操作。如需了解详情,请参阅 Vertex AI Node.js API 参考文档。
如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
/**
* TODO(developer): Uncomment these variables before running the sample.\
*/
// const modelDisplayName = 'YOUR_MODEL_DISPLAY_NAME';
// const metadataSchemaUri = 'YOUR_METADATA_SCHEMA_URI';
// const imageUri = 'YOUR_IMAGE_URI';
// const artifactUri = 'YOUR_ARTIFACT_URI';
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// Imports the Google Cloud Model Service Client library
const {ModelServiceClient} = require('@google-cloud/aiplatform');
// Specifies the location of the api endpoint
const clientOptions = {
apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};
// Instantiates a client
const modelServiceClient = new ModelServiceClient(clientOptions);
async function uploadModel() {
// Configure the parent resources
const parent = `projects/${project}/locations/${location}`;
// Configure the model resources
const model = {
displayName: modelDisplayName,
metadataSchemaUri: '',
artifactUri: artifactUri,
containerSpec: {
imageUri: imageUri,
command: [],
args: [],
env: [],
ports: [],
predictRoute: '',
healthRoute: '',
},
};
const request = {
parent,
model,
};
console.log('PARENT AND MODEL');
console.log(parent, model);
// Upload Model request
const [response] = await modelServiceClient.uploadModel(request);
console.log(`Long running operation : ${response.name}`);
// Wait for operation to complete
await response.promise();
const result = response.result;
console.log('Upload model response ');
console.log(`\tModel : ${result.model}`);
}
uploadModel();
Python
在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。如需了解详情,请参阅 Vertex AI Python API 参考文档。
如需向 Vertex AI 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。
from google.cloud import aiplatform
def upload_model_sample(
project: str,
display_name: str,
metadata_schema_uri: str,
image_uri: str,
artifact_uri: str,
location: str = "us-central1",
api_endpoint: str = "us-central1-aiplatform.googleapis.com",
timeout: int = 1800,
):
# The AI Platform services require regional API endpoints.
client_options = {"api_endpoint": api_endpoint}
# Initialize client that will be used to create and send requests.
# This client only needs to be created once, and can be reused for multiple requests.
client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
model = {
"display_name": display_name,
"metadata_schema_uri": metadata_schema_uri,
# The artifact_uri should be the path to a GCS directory containing
# saved model artifacts. The bucket must be accessible for the
# project's AI Platform service account and in the same region as
# the api endpoint.
"artifact_uri": artifact_uri,
"container_spec": {
"image_uri": image_uri,
"command": [],
"args": [],
"env": [],
"ports": [],
"predict_route": "",
"health_route": "",
},
}
parent = f"projects/{project}/locations/{location}"
response = client.upload_model(parent=parent, model=model)
print("Long running operation:", response.operation.name)
upload_model_response = response.result(timeout=timeout)
print("upload_model_response:", upload_model_response)
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。