Google Cloud Functions调用Recommendation AI predict API示例求助
Google Cloud Functions 调用Retail Predict API可运行实现方案
前置配置
- 提前为服务账号授予
roles/retail.predictCaller权限,这是调用预测接口的最小必要权限 - 云函数部署时绑定已授权的服务账号,无需在代码中硬编码服务账号密钥
requirements.txt需添加以下依赖:
google-auth==2.23.0 requests==2.31.0
完整可运行代码
以下代码自动使用云函数绑定的服务账号完成身份验证,无需手动处理密钥逻辑:
import google.auth from google.auth.transport.requests import AuthorizedSession import json # 全局初始化授权会话,冷启动仅执行一次,提升运行效率 credentials, project_id = google.auth.default( scopes=["https://www.googleapis.com/auth/cloud-platform"] ) authed_session = AuthorizedSession(credentials) # 需替换为实际项目参数 PROJECT_ID = "*你的GCP项目ID*" REGION = "*模型部署区域,如global、us-central1*" PLACEMENT_ID = "*你的预测模型Placement ID*" ENDPOINT = f"https://retail.googleapis.com/v2/projects/{PROJECT_ID}/locations/{REGION}/placements/{PLACEMENT_ID}:predict" def predict(request): # 若为HTTP触发,可从request中获取调用端传入的用户行为等参数 request_json = request.get_json(silent=True) or {} # 构造Predict接口请求体 predict_request = { "userEvent": { "eventType": "detail-page-view", "visitorId": request_json.get("visitor_id", "*测试用visitor ID*"), "userInfo": { "userId": request_json.get("user_id", ""), "ipAddress": request.get("origin", ""), "userAgent": request.headers.get("User-Agent", "") }, "productDetails": request_json.get("product_details", [ {"product": {"id": "*测试商品ID*"}} ]) }, "pageSize": 10, "filter": "", "params": { "strictFiltering": True, "returnProduct": True }, "labels": {} } try: response = authed_session.post( ENDPOINT, json=predict_request, headers={"Content-Type": "application/json"} ) response.raise_for_status() return (json.dumps(response.json()), 200, {"Content-Type": "application/json"}) except Exception as e: return (json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"})
使用注意事项
- 代码中所有带
*标记的占位内容,需替换为你自己的项目实际值后再部署 - 若要测试接口,可直接给HTTP触发的云函数发送POST请求,请求体传入自定义的用户行为、商品ID等参数
- 若返回权限错误,先确认云函数绑定的服务账号已授予Retail预测调用权限,且项目已启用Retail API
内容的提问来源于stack exchange,提问作者Rafael Silvestre
相关产品推荐
相关产品推荐

