You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:55:31