Generate text responses using Gemini API with external function calls in a chat scenario

Generate text responses using Gemini API with external function calls. This example demonstrates a chat scenario with two functions and two sequential prompts.

Code sample

Node.js

Before trying this sample, follow the Node.js setup instructions in the Vertex AI quickstart using client libraries. For more information, see the Vertex AI Node.js API reference documentation.

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

const {GoogleGenAI} = require('@google/genai');

const tools = [
  {
    functionDeclarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: 'OBJECT',
          properties: {
            location: {type: 'STRING'},
            unit: {type: 'STRING', enum: ['celsius', 'fahrenheit']},
          },
          required: ['location'],
        },
      },
    ],
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamChat(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-2.5-flash'
) {
  // Initialize client with your Cloud project and location
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  // Create a chat session and pass your function declarations
  const chat = client.chats.create({
    model: model,
    config: {tools: tools},
  });

  // This should include a functionCall response from the model
  const result1 = await chat.sendMessage({
    message: 'What is the weather in Boston?',
  });
  console.log(
    'Function call requested:',
    JSON.stringify(result1.functionCalls, null, 2)
  );

  // Send a follow up message with a FunctionResponse
  const result2 = await chat.sendMessage({
    message: [
      {
        functionResponse: {
          name: 'get_current_weather',
          response: {result: {weather: 'super nice'}},
        },
      },
    ],
  });

  // This should include a text response from the model using the response content
  // provided above
  console.log(result2.text);
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.