Cloud Functions调用Vertex AI生成式AI API遇401,如何获取认证凭据?
解决Google Cloud Function调用Vertex AI Generative AI API的401认证问题
直接通过axios发送HTTP请求时,不会自动触发Google Cloud的隐式认证流程,必须手动获取并携带服务账号的认证令牌。以下是两种可行的解决方式:
方式一:使用Google Auth库获取临时访问令牌
- 安装依赖:
npm install google-auth-library
- 修改代码,添加认证逻辑:
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客户端库(推荐)
官方库会自动处理认证流程,无需手动管理令牌,更简洁可靠:
- 安装依赖:
npm install @google-cloud/vertexai
- 重构代码:
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
相关产品推荐
相关产品推荐

