我在谷歌人工智能平台中保存了一个模型,当我在人工智能平台UI中测试预测时,它可以工作。
然而,当我尝试通过REST访问API时,我总是得到一个401
状态的响应。我想知道如何成功地做到这一点。
我的api URL如下所示:
'https://ml.googleapis.com/v1/projects/ml-project-name/models/my-model-names/versions/v2:predict
我希望能够在任何平台上的外部应用程序中访问这个端点,用它生成预测
谷歌云建议服务帐户授权,然而,它的所有方向都需要设置环境变量,以便应用程序可以自动对您进行身份验证。我更愿意在请求中直接提供它们,以使东西更便携,并与工作中其他地方的做法一致。
因此,我尝试获取API密钥。
根据本页:https://cloud.google.com/docs/authentication/api-keys您可以通过以下方式验证请求:
POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY
但是,当我运行以下代码时,我的请求状态是401
:
import requests
api_key = my_sample_api_key
url = f'https://ml.googleapis.com/v1/projects/project-name/models/model-name/versions/v2:predict?key={api_key}'
json = {"instances": [ {"input_1": ["Please predict this text"]}]}
res = request.post(url, json=json)
任何帮助都将不胜感激,谢谢。
Auto ML不支持在发送请求时使用API密钥。我建议根据您的请求使用auth令牌,或者使用可用的客户端库来发送预测。
以下是一个使用其python客户端库发送预测请求的代码片段:
# Create the AI Platform service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = googleapiclient.discovery.build('ml', 'v1')
def predict_json(project, model, instances, version=None):
"""Send json data to a deployed model for prediction.
Args:
project (str): project where the AI Platform Model is deployed.
model (str): model name.
instances ([Mapping[str: Any]]): Keys should be the names of Tensors
your deployed model expects as inputs. Values should be datatypes
convertible to Tensors, or (potentially nested) lists of datatypes
convertible to tensors.
version: str, version of the model to target.
Returns:
Mapping[str: any]: dictionary of prediction results defined by the
model.
"""
name = 'projects/{}/models/{}'.format(project, model)
if version is not None:
name += '/versions/{}'.format(version)
response = service.projects().predict(
name=name,
body={'instances': instances}
).execute()
if 'error' in response:
raise RuntimeError(response['error'])
return response['predictions']
以下是使用curl和auth令牌发送POST请求的示例:
curl -X POST
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token)
-H "Content-Type: application/json; charset=utf-8"
-d @request.json
https://ml.googleapis.com/v1/projects/your-project/models/you-model-name/versions/your-version-name:predict