Node.js调用GCP Vertex AI多分类模型API参数错误排查
解决GCP Vertex AI Node.js调用端点的参数错误问题
你遇到的invalid argument错误,核心原因是请求中instances的格式不符合Vertex AI API要求。以下是两种方法的正确参数格式:
一、使用rawPredict()方法的正确格式
rawPredict()需要严格对应HTTP请求的结构,关键点:
instances必须是数组类型(即使只有单个预测样本)httpBody需指定contentType为application/json,与你的cURL请求一致
修正后的代码:
const cred = require("./credentials.json"); const { PredictionServiceClient } = require("@google-cloud/aiplatform"); const projectId = "你的项目ID"; const location = "us-central1"; const endpointId = "你的端点ID"; const clientOptions = { apiEndpoint: "us-central1-aiplatform.googleapis.com", credentials: cred, }; async function predict(sentences) { const client = new PredictionServiceClient(clientOptions); const parent = `projects/${projectId}/locations/${location}/endpoint/${endpointId}`; const [response] = await client.rawPredict({ endpoint: parent, httpBody: { contentType: "application/json", // instances必须是数组,每个元素为一个预测样本对象 instances: [ { mimeType: "text/plain", content: sentences || "Dogs rule" } ] } }); return response.predictions; }
二、使用predict()方法的正确格式
predict()是SDK封装后的方法,无需手动构造httpBody,直接传入instances数组即可:
async function predict(sentences) { const client = new PredictionServiceClient(clientOptions); const parent = `projects/${projectId}/locations/${location}/endpoint/${endpointId}`; const [response] = await client.predict({ endpoint: parent, // 同样,instances必须是数组格式 instances: [ { mimeType: "text/plain", content: sentences || "Dogs rule" } ] }); return response.predictions; }
错误原因说明
你的原始代码中,将instances设置为单个对象而非数组,违反了Vertex AI API的规范——无论预测样本数量多少,instances都必须是数组类型。而你的cURL请求能运行,可能是因为API对单个对象的格式做了兼容,但Node.js SDK对参数格式的校验更严格。
内容的提问来源于stack exchange,提问作者Rogerio
相关产品推荐
相关产品推荐

