Ranjeet Bhosale
Ranjeet Bhosale

Reputation: 1

Node.js Chatbot Error: GoogleGenerativeAIError - Content should have 'parts' property with an array of Parts

I'm building a Node.js chatbot using the @google/generative-ai library. I'm encountering an error when handling the chat history between the user and the model.

Here's a breakdown of the problem:

This suggests the model expects a specific format for the history object, which might not be being sent correctly.

Relevant Code Snippets:

App.js (Client-side):

const getResponse = async () => {
    if (!value) {
      setError("Please enter something!");
      return;
    }
    try {
      const options = {
        method: "POST",
        body: JSON.stringify({
          history: chatHistory,
          message: value,
        }),
        headers: {
          "Content-Type": "application/json",
        },
      };
      const response = await fetch("http://localhost:8000/gemini", options);
      const data = await response.text();
      console.log(data);
      setChatHistory((oldChatHistory) => [
        ...oldChatHistory,
        {
          role: "user",
          parts: value,
        },
        {
          role: "model",
          parts: data,
        },
      ]);
      setValue("");
    } catch (error) {
      console.log(error);
      setError("Something went wrong!");
    }
  };

server.js (Server-side):


app.post("/gemini", async (req, res) => {
  const model = genAI.getGenerativeModel({ model: "gemini-pro" });
  const chat = model.startChat({
    history: req.body.history,
  });
  const msg = req.body.message;
  const result = await chat.sendMessage(msg);
  const response = await result.response;
  const text = response.text();
  res.send(text);
});

Additional Information:

Node.js version: 18.17.0 @google/generative-ai version: 0.3.1

What I'm Asking:

Upvotes: 0

Views: 927

Answers (1)

ihsan cenkız
ihsan cenkız

Reputation: 21

I have same problem. I fixed but I dont know node.js nicely. :D

Changes I made:

setChatHistory((oldChatHistory) => [
  ...oldChatHistory,
  {
    role: "user",
    parts: [{ text: value }],
  }, {
    role: "model",
    parts: [{ text: data }],
  },
]);

At the above code, I checked the Google Gemini document and I saw part field. The parts field is an array in the document and I changed my code like the document. And Then..

{ chatItem.role } : { chatItem.parts[0].text }

In the above code, I got the answer and I wrote the answer on my project.

I hope, I have been help you.

Upvotes: 2

Related Questions