在 Cloud Functions 中使用适用于 AI Platform统一的 Python 客户端

问题描述

我正在尝试将适用于 AI 平台(统一)的 Google Python 客户端“包装”到云函数中。

import json
from google.cloud import aiplatform
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value

def infer(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    request_json = request.get_json()

    project="simple-1234"
    endpoint_id="7106293183897665536"
    location="europe-west4"

    api_endpoint = "europe-west4-aiplatform.googleapis.com"

    # 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.PredictionServiceClient(client_options=client_options)
    # for more info on the instance schema,please use get_model_sample.py
    # and look at the yaml found in instance_schema_uri

    endpoint = client.endpoint_path(
        project=project,location=location,endpoint=endpoint_id
    )

    instance = request.json["instances"]
    instances = [instance]

    parameters_dict = {}
    parameters = json_format.ParseDict(parameters_dict,Value())
    
    try:
        response = client.predict(endpoint=endpoint,instances=instances,parameters=parameters)
        if 'error' in response:
            return (json.dumps({"msg": 'Error during prediction'}),500)
    except Exception as e:
        print("Exception when calling predict: ",e)
        return (json.dumps({"msg": 'Exception when calling predict'}),500)
    
    print(" deployed_model_id:",response.deployed_model_id)
    # See gs://google-cloud-aiplatform/schema/predict/prediction/tables_classification.yaml for the format of the predictions.
    predictions = response.predictions
    for prediction in predictions:
        print(" prediction:",dict(prediction))
    return (json.dumps({"prediction": response['predictions']}),200)

调用 client.predict() 时出现异常 400

{"error": "required property Values is not found"}

我做错了什么?

解决方法

我认为您的 parameters 变量不正确,在 documentation example 中,该变量是这样设置的,例如:

parameters = predict.params.ImageClassificationPredictionParams(
                 confidence_threshold=0.5,max_predictions=5,).to_value()

这可能是错误提示未找到属性的原因。您必须设置自己的参数,然后调用 predict 方法。