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

Cloud Functions调用Vertex AI生成式AI API遇401,如何获取认证凭据?

解决Google Cloud Function调用Vertex AI Generative AI API的401认证问题

直接通过axios发送HTTP请求时,不会自动触发Google Cloud的隐式认证流程,必须手动获取并携带服务账号的认证令牌。以下是两种可行的解决方式:

方式一:使用Google Auth库获取临时访问令牌

  1. 安装依赖:
npm install google-auth-library
  1. 修改代码,添加认证逻辑:
const {GoogleAuth} = require('google-auth-library');
const axios = require('axios');

// 初始化认证客户端
const auth = new GoogleAuth({
  scopes: 'https://www.googleapis.com/auth/cloud-platform'
});

async function callVertexAI() {
  try {
    // 获取访问令牌
    const client = await auth.getClient();
    const accessToken = await client.getAccessToken();

    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${accessToken.token}`
    };

    const chatparams = {
      instances: {
        context: "",
        examples: [],
        messages: [{
          "author": "user",
          "content": "how do i talk to you"
        }]
      },
      parameters: {
        temperature: 0.2,
        maxOutputTokens: maxtokens,
        topP: 0.8,
        topK: 40
      }
    };

    const result = await axios.post(
      "https://us-central1-aiplatform.googleapis.com/v1/projects/projectname/locations/us-central1/publishers/google/models/chat-bison@001:predict",
      chatparams,
      {headers}
    );
    return result.data;
  } catch (error) {
    console.log('调用Vertex AI出错:' + error);
    throw error;
  }
}

方式二:使用Vertex AI官方Node.js客户端库(推荐)

官方库会自动处理认证流程,无需手动管理令牌,更简洁可靠:

  1. 安装依赖:
npm install @google-cloud/vertexai
  1. 重构代码:
const {VertexAI} = require('@google-cloud/vertexai');

async function callVertexAI() {
  const vertexAI = new VertexAI({
    project: 'projectname',
    location: 'us-central1',
  });

  const model = vertexAI.preview.getGenerativeModel({
    model: 'chat-bison@001',
    generationConfig: {
      temperature: 0.2,
      maxOutputTokens: maxtokens,
      topP: 0.8,
      topK: 40,
    },
  });

  const request = {
    contents: [{role: 'user', parts: [{text: 'how do i talk to you'}]}],
  };

  try {
    const result = await model.generateContent(request);
    const response = await result.response;
    return response.candidates[0].content.parts[0].text;
  } catch (error) {
    console.log('调用Vertex AI出错:' + error);
    throw error;
  }
}

额外检查项

确保绑定的服务账号拥有AI Platform Predictor(roles/aiplatform.predictor)角色,或至少包含aiplatform.models.predict权限,否则即使令牌正确,也会因权限不足返回错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:15:05