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

Google Gemini GenerationConfig构建报错:Builder()私有访问问题

解决GenerationConfig.Builder私有构造方法的编译错误

错误原因

com.google.cloud.vertexai.api.GenerationConfig是Protobuf自动生成的类,其Builder的构造方法被设为私有,无法直接通过new GenerationConfig.Builder()实例化,必须使用类提供的静态工厂方法获取Builder实例。同时,Protobuf Builder的属性不能直接通过字段赋值,需要调用对应的setter方法。

修正后的代码

import com.google.cloud.vertexai.GenerativeModel;
import com.google.cloud.vertexai.api.GenerationConfig;
import com.google.cloud.vertexai.generativeai.preview.GenerativeModelFutures;
import java.util.Arrays;

public class GeminiConfigExample {
    public static void main(String[] args) throws Exception {
        // 通过静态newBuilder()方法获取Builder实例
        GenerationConfig.Builder configBuilder = GenerationConfig.newBuilder();
        
        // 使用setter方法配置生成参数
        configBuilder.setTemperature(0.9f);
        configBuilder.setTopK(16);
        configBuilder.setTopP(0.1f);
        configBuilder.setMaxOutputTokens(200);
        configBuilder.addStopSequences("red"); // 单个添加停止序列
        // 若需批量添加可使用:configBuilder.addAllStopSequences(Arrays.asList("red", "end"));

        GenerationConfig generationConfig = configBuilder.build();

        GenerativeModel gm = new GenerativeModel(
                "MODEL_NAME",
                BuildConfig.apiKey,
                generationConfig
        );

        GenerativeModelFutures model = GenerativeModelFutures.from(gm);
    }
}

额外建议

  • 你使用的0.1.0版本是该SDK的早期预览版,API可能存在不稳定或变更情况,建议升级到最新稳定版本(如1.1.0),避免潜在的兼容问题:
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vertexai</artifactId>
    <version>1.1.0</version>
</dependency>

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:33:27