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

如何在Vertex AI的Gemini API Node.js调用中指定SystemInstruction

在Vertex AI Node.js SDK中设置Gemini的System Instruction并修复报错

错误原因

你当前代码的问题在于错误地尝试通过发送system角色的消息来设置系统指令,而Vertex AI的Node.js SDK并不支持这种方式。此外,sendMessageStream的调用格式不符合要求,导致触发No content is provided for sending chat message错误。

在Node.js SDK中,系统指令需要在初始化生成式模型(getGenerativeModel)或启动对话(startChat)时直接配置,而非作为独立消息发送。

正确实现方案

有两种标准方式可以设置system instruction:

方式1:初始化GenerativeModel时指定全局系统指令

在调用getGenerativeModel时添加systemInstruction参数,该指令会应用到所有基于此模型创建的对话:

const { VertexAI } = require('@google-cloud/vertexai')

let generativeModel;

const projectId = 'myProjectId';
const location = 'us-central1';
const model = 'gemini-1.0-pro-002';

function initializeGenerativeModel() {
    try {
        const vertex_ai = new VertexAI({ project: projectId, location: location });

        generativeModel = vertex_ai.preview.getGenerativeModel({
            model: model,
            generationConfig: {
                'maxOutputTokens': 8192,
                'temperature': 1,
                'topP': 0.95,
            },
            safetySettings: [
                {
                    'category': 'HARM_CATEGORY_HATE_SPEECH',
                    'threshold': 'BLOCK_MEDIUM_AND_ABOVE'
                },
                {
                    'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
                    'threshold': 'BLOCK_MEDIUM_AND_ABOVE'
                },
                {
                    'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
                    'threshold': 'BLOCK_MEDIUM_AND_ABOVE'
                },
                {
                    'category': 'HARM_CATEGORY_HARASSMENT',
                    'threshold': 'BLOCK_MEDIUM_AND_ABOVE'
                }
            ],
            // 全局系统指令配置
            systemInstruction: {
                parts: [{ text: 'You are an ai assistant' }]
            }
        });
    } catch (error) {
        console.error('Error initializing VertexAI:', error);
        throw error;
    }
}

initializeGenerativeModel();

async function gemini_1_0_pro(query) {
  try {
      const chat = generativeModel.startChat();
      
      // 直接发送用户消息,系统指令已生效
      const result = await chat.sendMessageStream({
          content: query
      });

      for await (const item of result.stream) {
          const response = item.candidates[0].content.parts[0].text;
          console.log(response)
      }
      const aggregatedResponse = await result.response;
      console.log(aggregatedResponse)
  } catch (error) {
      console.error('Error in gemini_1_0_pro:', error);
  }
}

module.exports = { gemini_1_0_pro };

方式2:启动对话时单独设置系统指令

如果需要为不同对话配置不同的系统指令,可在调用startChat时传入参数:

async function gemini_1_0_pro(query) {
  try {
      // 为当前对话单独设置系统指令
      const chat = generativeModel.startChat({
          systemInstruction: {
              parts: [{ text: 'You are an ai assistant' }]
          }
      });
      
      const result = await chat.sendMessageStream({
          content: query
      });

      for await (const item of result.stream) {
          const response = item.candidates[0].content.parts[0].text;
          console.log(response)
      }
      const aggregatedResponse = await result.response;
      console.log(aggregatedResponse)
  } catch (error) {
      console.error('Error in gemini_1_0_pro:', error);
  }
}

关键修改点说明

  1. 移除system角色消息发送代码:该操作不符合SDK规范,是触发报错的核心原因。
  2. 规范systemInstruction格式:无论在模型初始化还是对话启动时,系统指令都需要以{ parts: [{ text: "指令内容" }] }的格式传入。
  3. 简化用户消息发送:发送用户消息时只需传入content字段,SDK默认识别为用户消息,无需额外指定role。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:55