如何使用 HTTP 请求对 GCP AI Platform Predictions 进行身份验证

问题描述

我已按照此 tutorial 成功将模型部署到 AI Platform Predictions。现在,我想通过 HTTP 请求对这个模型进行预测。

按照@Ismail 的建议,我遵循了 Method: projects.predict 文档。

我正在向 https://ml.googleapis.com/v1/projects/${PROJECT_ID}/models/${MODEL_NAME}:predict 发送具有以下正文的 POST 请求:

{
  "instances": [
    [51.0,17.0,6.0,1.0,0.0,0.0]
  ]
}

数字是模型的输入。

我收到以下回复

{
    "error": {
        "code": 401,"message": "Request is missing required authentication credential. Expected OAuth 2 access token,login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","status": "UNAUTHENTICATED"
    }
}

我使用 RestMan chrome 扩展发送了 POST 请求。我希望能够使用 RestMan 进行预测。

我的问题是:如何验证我的 HTTP POST 请求?我应该在请求的标头中发送一些信息吗?

解决方法

访问 Google API 时,您需要在标头中添加访问令牌。使用 CLI,您可以像这样生成它:

gcloud auth print-access-token

当然,当前凭证需要在AI平台预测服务上授权。

如果您执行 curl,则可以在 linux(和云外壳)上执行此操作

curl -X POST -d @bodyfile.json -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  https://ml.googleapis.com/v1/projects/${PROJECT_ID}/models/${MODEL_NAME}:predic

如果您使用 RestMan,我不确定它是否能够为您生成访问令牌。解决方案是公开您的模型。不推荐,但限时使用,仅供测试,何乐而不为!

为此,授予 allUsers 在您的模型上的角色 roles/ml.modelUser


编辑 1

我没有找到如何在带有控制台的模型上执行此操作。我以前没有,但有一些更新......很奇怪。我使用 gcloud CLI 实现了这一点

gcloud ai-platform models add-iam-policy-binding --region=us-central1 --member=allUsers --role=roles/ml.modelUser test
,

遵循 Method: projects.predict 文档。

POST https://{endpoint}/v1/{name=projects/**}:predict