Genera respuestas de texto con la API de Gemini con llamadas a funciones externas en una situación de chat

Genera respuestas de texto con la API de Gemini con llamadas a funciones externas. En este ejemplo, se muestra una situación de chat con dos funciones y dos prompts secuenciales.

Muestra de código

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración para Node.js incluidas en la guía de inicio rápido de Vertex AI sobre cómo usar bibliotecas cliente. Para obtener más información, consulta la documentación de referencia de la API de Vertex AI Node.js.

Para autenticarte en Vertex AI, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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);
}

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .