使用 Vertex AI 建立多回合非即時對話

這個範例示範如何設定 Vertex AI SDK,以及如何建立非串流對話,並連續傳送三則訊息給模型。

程式碼範例

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Node.js API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function createNonStreamingChat(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.0-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const chat = generativeModel.startChat({});

  const result1 = await chat.sendMessage('Hello');
  const response1 = await result1.response;
  console.log('Chat response 1: ', JSON.stringify(response1));

  const result2 = await chat.sendMessage(
    'Can you tell me a scientific fun fact?'
  );
  const response2 = await result2.response;
  console.log('Chat response 2: ', JSON.stringify(response2));

  const result3 = await chat.sendMessage('How can I learn more about that?');
  const response3 = await result3.response;
  console.log('Chat response 3: ', JSON.stringify(response3));
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽器