reactjsjsxgoogle-gemini

"TypeError: request is not iterable" when using Google Gemini API generateContent method in React


I'm working on a React project where I use the Google Gemini API to retrieve information based on inputs collected from a form. However, when I call the generateContent method, I get the following error:

Error generating content: TypeError: request is not iterable
    at formatNewContent (index.mjs:881:36)
    at formatGenerateContentInput (index.mjs:962:25)
    at GenerativeModel.generateContent (index.mjs:1309:33)
    at run (gemini.jsx:32:36)
    at onSent (Context.jsx:59:64)
    at handleSubmit (Main.jsx:20:5)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:25)

Error Context This error seems to suggest that the request object isn't formatted correctly or that the Gemini API method expects a different input format. Here's the relevant part of my code where I'm attempting to generate content based on form inputs.

import {
    GoogleGenerativeAI,
    HarmCategory,
    HarmBlockThreshold,
} from "@google/generative-ai";

const apiKey = process.env.REACT_APP_GEN_AI_API_KEY; // Ensure this is set in your environment
const genAI = new GoogleGenerativeAI(apiKey);

const model = genAI.getGenerativeModel({
    model: "gemini-1.5-flash",
});

const generationConfig = {
    temperature: 1,
    topP: 0.95,
    topK: 64,
    maxOutputTokens: 8192,
    responseMimeType: "text/plain",
};

export async function run({ education, technologies, level, projects, firstCourse }) {
    try {
        // Log inputs for debugging
        console.log("Inputs for career suggestion:", { education, technologies, level, projects, firstCourse });

        // Career suggestion
        const prompt = `Education: ${education}, skills: ${technologies}, Level: ${level}, Projects_done: ${projects}. Based on my education, skills, and level, which career should I opt for ${firstCourse}? Just tell me one branch in one word.`;
        console.log("Prompt for career suggestion:", prompt);
        
        // Ensure the call to generateContent has the correct structure
        const result = await model.generateContent({ 
            prompt, 
            generationConfig 
        });

        if (!result || typeof result.text !== 'string') {
            throw new Error("Invalid response from model for career suggestion");
        }

        const decision = result.text.trim() || "Unable to determine";

        // Best courses
        const prompt_2 = `${decision} was suggested by a friend. Give me the 5 best free courses with links to master this field, ordered from beginner to advanced. Only list 5 links, no description.`;
        console.log("Prompt for courses:", prompt_2);
        
        const result_2 = await model.generateContent({ 
            prompt: prompt_2, 
            generationConfig 
        });

        if (!result_2 || typeof result_2.text !== 'string') {
            throw new Error("Invalid response from model for courses");
        }

        const courseDisplay = result_2.text.trim() || "No courses found";

        //Trending projects
        const prompt_3 = `For a ${decision} career, suggest 5 trending projects to build my skills at ${level} level.`;
        console.log("Prompt for projects:", prompt_3);
        
        const result_3 = await model.generateContent({ 
            prompt: prompt_3, 
            generationConfig 
        });

        if (!result_3 || typeof result_3.text !== 'string') {
            throw new Error("Invalid response from model for projects");
        }

        const project = result_3.text.trim() || "No projects available";

        return { decision, courseDisplay, project };
    } catch (error) {
        console.error("Error generating content:", error);
        return { decision: "Error", courseDisplay: "Error fetching courses", project: "Error fetching projects" };
    }
}

 export default run;

I want to get response in three things career suggestions, courses and projects kindly help me out in this error.

What I’ve Tried I verified that my REACT_APP_GEN_AI_API_KEY is set correctly in my environment variables. Checked that generateContent receives prompt and generationConfig. Printed prompt and generationConfig to the console, and they appear formatted as expected.


Solution

  • Modification points:

    When these points are simply reflected in your showing script, it becomes as follows.

    Modified script:

    import {
      GoogleGenerativeAI,
      HarmCategory,
      HarmBlockThreshold,
    } from "@google/generative-ai";
    
    const apiKey = process.env.REACT_APP_GEN_AI_API_KEY; // Ensure this is set in your environment
    const genAI = new GoogleGenerativeAI(apiKey);
    
    const generationConfig = {
      temperature: 1,
      topP: 0.95,
      topK: 64,
      maxOutputTokens: 8192,
      responseMimeType: "text/plain",
    };
    
    const model = genAI.getGenerativeModel({
      model: "gemini-1.5-flash",
      generationConfig,
    });
    
    export async function run({ education, technologies, level, projects, firstCourse }) {
      try {
        // Log inputs for debugging
        console.log("Inputs for career suggestion:", { education, technologies, level, projects, firstCourse });
    
        // Career suggestion
        const prompt = `Education: ${education}, skills: ${technologies}, Level: ${level}, Projects_done: ${projects}. Based on my education, skills, and level, which career should I opt for ${firstCourse}? Just tell me one branch in one word.`;
        console.log("Prompt for career suggestion:", prompt);
    
        // Ensure the call to generateContent has the correct structure
        const result = await model.generateContent(prompt);
    
        if (!result || typeof result.response.text() !== "string") {
          throw new Error("Invalid response from model for career suggestion");
        }
    
        const decision = result.response.text().trim() || "Unable to determine";
    
        // Best courses
        const prompt_2 = `${decision} was suggested by a friend. Give me the 5 best free courses with links to master this field, ordered from beginner to advanced. Only list 5 links, no description.`;
        console.log("Prompt for courses:", prompt_2);
    
        const result_2 = await model.generateContent(prompt_2);
    
        if (!result_2 || typeof result_2.response.text() !== "string") {
          throw new Error("Invalid response from model for courses");
        }
    
        const courseDisplay = result_2.response.text().trim() || "No courses found";
    
        //Trending projects
        const prompt_3 = `For a ${decision} career, suggest 5 trending projects to build my skills at ${level} level.`;
        console.log("Prompt for projects:", prompt_3);
    
        const result_3 = await model.generateContent(prompt_3);
    
        if (!result_3 || typeof result_3.response.text() !== "string") {
          throw new Error("Invalid response from model for projects");
        }
    
        const project = result_3.response.text().trim() || "No projects available";
    
        return { decision, courseDisplay, project };
      } catch (error) {
        console.error("Error generating content:", error);
        return {
          decision: "Error",
          courseDisplay: "Error fetching courses",
          project: "Error fetching projects",
        };
      }
    }
    
    export default run;
    

    Reference: