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

NodeJS中Google Cloud Vertex AI预测结果截断问题求助

Google Cloud AIPlatform NodeJS客户端预测结果截断问题解决办法

核心问题定位

你的代码里设置了maxOutputTokens: 5,这个参数限制了模型返回的最大token数量,导致结果被强制截断成仅能容纳5个token的内容。而你用curl请求时应该没有设置这么严格的token限制,所以能拿到完整的10个城市列表。

解决步骤

1. 调整输出token限制参数

把parameter里的maxOutputTokens修改为合适的数值,比如200(足够容纳10个城市列表的内容):

const parameter = {
    temperature: 0.2,
    maxOutputTokens: 200, // 增大这个值
    topP: 0.95,
    topK: 40,
};

2. 正确解析IValue结果

可以使用SDK提供的helpers.fromValue方法,把protobuf的IValue对象转换为普通JavaScript对象,避免手动处理JSON.stringify可能带来的解析问题:

for (let p of response[0]!.predictions!) {
  const result = helpers.fromValue(p);
  console.log(result);
}

修改后的完整代码

/**
 * TODO(developer): Uncomment these variables before running the sample.
 * (Not necessary if passing values as arguments)
 */
import * as sdk from "@google-cloud/aiplatform";

const project = "generativeai-390315";
const loc = 'us-central1';

// Imports the Google Cloud Prediction service client
const { PredictionServiceClient } = sdk.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const { helpers } = sdk;

const credentials = {
    client_email: "your-client-email",
    private_key: "your-private-key",
};

// Specifies the location of the api endpoint
const clientOptions = {
    credentials,
    apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};

const publisher = 'google';
const model = 'text-bison@001';


// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function callPredict() {
    // Configure the parent resource
    const endpoint = `projects/${project}/locations/${loc}/publishers/${publisher}/models/${model}`;

    const prompt = {
        prompt:
            'what are the 10 largest cities in Europe?',
    };
    const instanceValue = helpers.toValue(prompt);
    const instances = [instanceValue] as protobuf.common.IValue[];

    const parameter = {
        temperature: 0.2,
        maxOutputTokens: 200, // 调整为合适的token数
        topP: 0.95,
        topK: 40,
    };
    const parameters = helpers.toValue(parameter);

    const request = {
        endpoint,
        instances,
        parameters,
    };

    // Predict request
    const response = await predictionServiceClient.predict(request);
    console.log('Get text prompt response');
    console.log("\n\n");

    // 正确解析IValue为普通JS对象
    for (let p of response[0]!.predictions!) {
      const result = helpers.fromValue(p);
      console.log(result);
    }
    return response;
}

(async ()=>{
    const response = await callPredict();
})()

补充说明

Google Cloud AIPlatform的NodeJS客户端是可以正常集成使用的,只要参数配置正确、解析方式得当,就能获取完整的预测结果。

内容的提问来源于stack exchange,提问作者Loebre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:13:22