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.
- Typescript
- Python
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());
}
from google import genai
from pydantic import BaseModel
from typing import List
class Question(BaseModel):
question: str
options: List[str]
answer: int
def generate_questions_for_text(text: str) -> List[Question]:
client = genai.Client(api_key="GEMINI_API_KEY")
prompt = f"""
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}
'''
"""
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=prompt,
config={
'response_mime_type': 'application/json',
'response_schema': List[Question],
},
)
questions: List[Question] = response.parsed
# Validate the questions format
if not isinstance(questions, list) or len(questions) == 0:
raise ValueError("Invalid questions format returned from API")
for i, q in enumerate(questions):
if (not q.question or
not isinstance(q.options, list) or
len(q.options) != 4 or
not isinstance(q.answer, int) or
q.answer < 0 or
q.answer > 3):
raise ValueError(f"Question at index {i} has invalid format")
return questions