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

NextJS中实例化PredictionServiceClient时挂起并最终超时问题

NextJS中实例化PredictionServiceClient超时问题的解决方案
  • 切换到Node.js Runtime
    Next.js App Router的路由默认使用Edge Runtime,而Google Cloud AI Platform的v1beta1客户端库依赖Node.js专属API(如fs、net),Edge环境不支持这些API会导致初始化挂起。在路由函数顶部添加以下代码强制使用Node.js Runtime:

    export const runtime = 'nodejs';
    
  • 完善身份验证配置
    若使用OIDC验证,需确保authClient正确初始化并拥有AI Platform预测权限。如果依赖Application Default Credentials(ADC),在部署环境(如Vercel)中需配置GOOGLE_APPLICATION_CREDENTIALS环境变量,或直接传入服务账号密钥:

    import { v1beta1 } from '@google-cloud/aiplatform';
    import { GoogleAuth } from 'google-auth-library';
    
    export const runtime = 'nodejs';
    
    export async function GET(request: Request) {
      try {
        // 初始化OIDC authClient
        const authClient = new GoogleAuth({
          scopes: ['https://www.googleapis.com/auth/cloud-platform'],
          // 若使用服务账号密钥,可直接传入credentials
          credentials: JSON.parse(process.env.GOOGLE_SERVICE_ACCOUNT_KEY || '')
        });
    
        const client = new v1beta1.PredictionServiceClient({
          apiEndpoint: 'europe-west3-aiplatform.googleapis.com',
          authClient: await authClient.getClient()
        });
    
        return new Response(JSON.stringify('ok'));
      } catch (err) {
        // 捕获错误并返回,便于排查问题
        console.error('初始化客户端失败:', err);
        return new Response(JSON.stringify({error: (err as Error).message}), {status: 500});
      }
    }
    
  • 添加错误捕获与日志
    原代码没有错误处理,导致超时后无法获取具体错误信息。用try-catch包裹客户端初始化逻辑,打印错误日志,能快速定位是权限问题、网络问题还是环境不兼容问题。

  • 确认区域与模型部署位置
    确保你的AI模型部署在europe-west3区域,客户端使用的API端点与模型区域一致,跨区域调用可能导致延迟过高甚至超时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:04:53