I'm following a tutor on how to implement Google Gemini's API. He used Next.js API routes but I'm using NestJS as a seperate backend. We're using the same prompts, specifying to Gemini that the data must be returned in JSON format.
His response comes correct in a JSON format like this:
But mine comes as a text/string:
This is my code:
async generateVideo(prompt: string) {
try {
const model = this.genAI.getGenerativeModel({
model: 'gemini-1.5-flash',
});
const generationConfig = {
temperature: 1,
topP: 0.95,
topK: 64,
maxOutputTokens: 8192,
responseMimeType: 'application/json',
};
const chatSession = model.startChat({
generationConfig,
history: [ /*Removed because it was too long */ ],
});
const result = await chatSession.sendMessage(prompt.toString());
console.log(result.response.text());
return {
data: result.response.text(), // I guess I made an error here?
};
} catch (error) {}
This modification uses JSON.parse to convert the text response into a JSON object before returning it. Now, data will hold the parsed JSON instead of a raw string.
const result = await chatSession.sendMessage(prompt.toString()); console.log(result.response.text());
const parsedData = JSON.parse(result.response.text()); // Parse the JSON response
return {
data: parsedData,
};