OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter Rohit Gusain
  • Start date Start date
R

Rohit Gusain

Guest
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:
{{

Code:
const { message } = req.query;

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

I want to use this for my react native app

Code:
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!

<p>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.</p>
<p>Here's my current setup:<br />
{{</p>
<pre><code>const { message } = req.query;
</code></pre>
<p>}} this is now working ☝️☝️☝️☝️</p>
<p>I want to use this for my react native app</p>
<pre><code>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}`);
});
</code></pre>
<p>**</p>
<p>Issues I'm facing:**</p>
<ol>
<li><p>When I make a request to <code>/chat</code> with a message parameter, sometimes I receive an empty response from the API.</p>
</li>
<li><p>I'm unsure how to properly handle errors and debug issues when communicating with the Google Generative AI API.</p>
</li>
</ol>
<p><strong>Expected behavior:</strong></p>
<ul>
<li>When I send a request to <code>/chat?message=Hello</code>, I expect to receive a JSON response containing the generated text.</li>
</ul>
<p><strong>What did you try and what were you expecting?</strong></p>
<ul>
<li><p>I tried making requests using Postman to <code>http://localhost:3000/chat?message=Hello</code>.</p>
</li>
<li><p>I expected to receive a JSON response with the generated text.</p>
</li>
</ul>
<p><strong>Additional Information:</strong></p>
<ul>
<li><p>I have verified that the <code>.env</code> file is correctly configured with my Google Generative AI API key.</p>
</li>
<li><p>I'm using the <code>@google/generative-ai</code> package to interact with the API.</p>
</li>
</ul>
<p><strong>Questions:</strong></p>
<ul>
<li><p>How can I ensure that my application is properly receiving data from the Google Generative AI API?</p>
</li>
<li><p>What are best practices for handling errors and debugging when integrating third-party APIs like the Google Generative AI?</p>
</li>
</ul>
<p>Any help or guidance would be greatly appreciated. Thank you!</p>
 
Top