Trouble receiving data from Google Generative AI API using Express and Node.js

I’m trying to build an API endpoint with Express to interact with Google’s Generative AI. The goal is to generate text based on a user-provided message and return it as a JSON response. However, I’m encountering issues where I’m not sure if my application is properly receiving data from the Google Generative AI API.

Here’s my current setup:
{{

const { message } = req.query;

}} this is now working ☝️☝️☝️☝️

I want to use this for my react native app

const express = require('express');
const { GoogleGenerativeAI } = require('@google/generative-ai');

const app = express();
const port = process.env.PORT || 3000;

// Load environment variables from .env
require('dotenv').config();

// Initialize Google Generative AI with API key
const genAI = new GoogleGenerativeAI({ apiKey: process.env.API_KEY });

app.use(express.json());

app.get('/chat', async (req, res) => {
  const { message } = req.query; // Access message from query parameters
  console.log('Received message:', message);
  if (!message) {
    return res.status(400).json({ error: 'Message parameter is required.' });
  }
  
  try {
    // Initialize model here
    const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
    const result = await model.generateContent(message);

    // Log the result for debugging
    console.log('Generate content result:', result);

    // Extracting the text content from the response
    const response = await result.response;
    if (!response) {
      throw new Error('Empty response received from API.');
    }
    const text = await response.text(); // Use await to get the text content

    console.log('Generated text:', text);

    res.json({ success: true, response: text });
  } catch (error) {
    console.error('Error generating content:', error);
    res.json({ success: false, error: `Error generating content: ${error.message}` });
  }
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

**

Issues I’m facing:**

  1. When I make a request to /chat with a message parameter, sometimes I receive an empty response from the API.

  2. I’m unsure how to properly handle errors and debug issues when communicating with the Google Generative AI API.

Expected behavior:

  • When I send a request to /chat?message=Hello, I expect to receive a JSON response containing the generated text.

What did you try and what were you expecting?

  • I tried making requests using Postman to http://localhost:3000/chat?message=Hello.

  • I expected to receive a JSON response with the generated text.

Additional Information:

  • I have verified that the .env file is correctly configured with my Google Generative AI API key.

  • I’m using the @google/generative-ai package to interact with the API.

Questions:

  • How can I ensure that my application is properly receiving data from the Google Generative AI API?

  • What are best practices for handling errors and debugging when integrating third-party APIs like the Google Generative AI?

Any help or guidance would be greatly appreciated. Thank you!