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:
- First Query Success: The initial user query works fine, likely because the history sent to the model is empty.
- Second Query Error: Subsequent user queries result in the following error: GoogleGenerativeAIError: [GoogleGenerativeAI Error]: Content should have 'parts' property with an array of Parts
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:
- How can I ensure the history object sent to the model is formatted correctly with the parts property as an array of Parts?
- Are there any specific considerations for handling empty history on the server-side?
- Any other suggestions to resolve the "Content should have 'parts' property with an array of Parts" error.