Skip to main content

Structured Output with Gemini

Generate structured output from Gemini using the response_schema parameter. This is not supported by the thinking models. See the Model Feature Matrix for more details.

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


const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const schema = {
description: "List of questions and answers",
type: SchemaType.ARRAY,
items: {
type: SchemaType.OBJECT,
properties: {
question: {
type: SchemaType.STRING,
description: "Question",
nullable: false,
},
options: {
type: SchemaType.ARRAY,
description: "Options",
nullable: false,
items: {
type: SchemaType.STRING,
description: "Option",
nullable: false,
},
},
answer: {
type: SchemaType.INTEGER,
description: "Answer",
nullable: false,
},
},
required: ["question", "options", "answer"],
},
};

const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash",
generationConfig: {
responseMimeType: "application/json",
responseSchema: schema,
},
});

interface Question {
question: string;
options: string[];
answer: number;
}

export async function generateQuestionsForText(
text: string,
): Promise<Question[]> {
const prompt = `
You are an expert reading comprehension assessment creator.
Given the following text, create 4 multiple-choice questions that test reading comprehension at various difficulty levels.
Each question should have 4 options with only one correct answer.

Text:
"""
${text}
"""
`;

const result = await model.generateContent(prompt);
const response = await result.response;
return JSON.parse(response.text());
}