# AI Quiz Crafter (`thescrapelab/apify-quiz-generator`) Actor

AI-powered quiz generator that creates fact-checked multiple-choice and short-answer questions on any topic. Supports easy, medium, and hard difficulty with a built-in AI review pass. Exports clean, validated JSON for e-learning, trivia apps, and training assessments.

- **URL**: https://apify.com/thescrapelab/apify-quiz-generator.md
- **Developed by:** [Inus Grobler](https://apify.com/thescrapelab) (community)
- **Categories:** Social media, AI, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

from $7.00 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## AI Quiz Generator — Create Multiple Choice & Short Answer Questions Instantly

Generate structured, fact-checked quizzes on **any topic** in seconds using AI. This Apify Actor calls a large language model via [OpenRouter](https://openrouter.ai) to produce ready-to-use quiz questions — complete with answer options, correct answers, ideal answers, and explanations — exported as clean JSON.

Perfect for building e-learning platforms, trivia apps, training assessments, revision tools, and automated test sets.

---

### Features

- 🧠 **Multiple question formats** — multiple-choice (4 options + correct answer) and short-answer (ideal answer for grading), both with explanations
- 🎯 **Adjustable difficulty** — Easy, Medium, or Hard. Hard difficulty actively filters and rewrites any questions that aren't genuinely challenging via a two-pass AI review
- ⚡ **Two AI tiers** — Standard (cost-effective) and Premium (faster, higher accuracy)
- ✅ **Validated output** — every response is validated with Pydantic before being saved; failed batches are retried automatically
- 🔄 **Smart batching** — large quizzes are split across multiple API calls to avoid token limits
- 📦 **Clean JSON dataset** — flat, camelCase records ready to export as CSV, JSONL, or connect via the Apify API

---

### Inputs

| Field | Type | Default | Description |
|---|---|---|---|
| `topic` | String | — | What the quiz is about. **Be specific** — *"Causes of World War I"* gives far better results than *"History"*. |
| `total_questions` | Integer | `10` | Total questions to generate. Min: 1, Max: 100. |
| `multiple_choice_count` | Integer | `7` | How many questions should be multiple-choice. The rest will be short-answer. Must not exceed `total_questions`. |
| `difficulty` | Select | `medium` | `easy` · `medium` · `hard`. On medium/hard, a second AI pass reviews and rewrites any under-difficulty questions. |
| `quality_tier` | Select | `standard` | `standard` (OpenAI GPT-4o Mini) or `premium` (Gemini 2.5 Flash Lite). Premium adds a small per-question charge. |

#### Example Input

```json
{
    "topic": "The causes and key events of World War I",
    "total_questions": 20,
    "multiple_choice_count": 14,
    "difficulty": "hard",
    "quality_tier": "premium"
}
````

***

### Output

Each dataset item is one quiz question. Multiple-choice and short-answer questions share the same flat schema — type-specific fields are `null` when not applicable.

#### Multiple-Choice Example

```json
{
    "questionNumber": 1,
    "type": "multiple_choice",
    "question": "Which event directly triggered the outbreak of World War I?",
    "options": [
        "The assassination of Archduke Franz Ferdinand",
        "The sinking of the Lusitania",
        "The invasion of Poland",
        "The fall of the Ottoman Empire"
    ],
    "correctAnswer": "The assassination of Archduke Franz Ferdinand",
    "idealAnswer": null,
    "explanation": "The assassination of Archduke Franz Ferdinand in Sarajevo on 28 June 1914 triggered a chain of diplomatic crises that led directly to the outbreak of World War I.",
    "metaTopic": "The causes and key events of World War I",
    "metaDifficulty": "hard",
    "metaQualityTier": "premium",
    "metaModel": "google/gemini-2.5-flash-lite",
    "metaGeneratedAt": "2025-04-24T16:00:00.000000+00:00"
}
```

#### Short-Answer Example

```json
{
    "questionNumber": 15,
    "type": "short_answer",
    "question": "What was the name of the military alliance that opposed the Triple Alliance in World War I?",
    "options": null,
    "correctAnswer": null,
    "idealAnswer": "The Triple Entente, consisting of France, Russia, and Great Britain.",
    "explanation": "The Triple Entente was formed by France, Russia, and the United Kingdom. It opposed the Central Powers — the Triple Alliance of Germany, Austria-Hungary, and Italy.",
    "metaTopic": "The causes and key events of World War I",
    "metaDifficulty": "hard",
    "metaQualityTier": "premium",
    "metaModel": "google/gemini-2.5-flash-lite",
    "metaGeneratedAt": "2025-04-24T16:00:00.000000+00:00"
}
```

#### Output Field Reference

| Field | Type | Description |
|---|---|---|
| `questionNumber` | Number | Sequential position in the quiz (1-indexed) |
| `type` | String | `"multiple_choice"` or `"short_answer"` |
| `question` | String | The full question text |
| `options` | Array / null | Four answer choices — multiple-choice only |
| `correctAnswer` | String / null | Exact text of the correct option — multiple-choice only |
| `idealAnswer` | String / null | Model answer for grading — short-answer only |
| `explanation` | String | Why the answer is correct. Useful for learning and review. |
| `metaTopic` | String | The topic provided as input |
| `metaDifficulty` | String | Difficulty level: `"easy"`, `"medium"`, or `"hard"` |
| `metaQualityTier` | String | `"standard"` or `"premium"` |
| `metaModel` | String | OpenRouter model slug used to generate the question |
| `metaGeneratedAt` | Date | ISO 8601 UTC timestamp |

***

### Difficulty Levels

| Level | Target Audience | How It Works |
|---|---|---|
| 🟢 **Easy** | Anyone | Well-known facts. Distractors are clearly wrong to someone with basic familiarity. |
| 🟡 **Medium** | Enthusiasts | Requires specific knowledge. Distractors need careful thought to eliminate. Includes an AI review pass. |
| 🔴 **Hard** | Experts & specialists | Niche details, exact dates, minor characters, production trivia. Forbidden from asking any "famous" facts. Distractors must be real entities from the same domain. Includes a strict AI review and rewrite pass. |

***

### Quality Tiers

| Tier | Model | Best For |
|---|---|---|
| ⚡ **Standard** | `openai/gpt-4o-mini` | General topics, high volume, cost-sensitive use |
| 🏆 **Premium** | `google/gemini-2.5-flash-lite` | Technical, academic, or specialised topics needing higher accuracy (+charge per question) |

***

### Setup

This Actor requires an **OpenRouter API key**. Add it as an encrypted secret environment variable in your Actor's settings.

#### Steps

1. Get a free API key at [openrouter.ai/keys](https://openrouter.ai/keys)
2. In the Apify Console, go to your Actor → **Settings** → **Environment variables**
3. Add a variable named `OPENROUTER_API_KEY`, paste your key, and toggle **Secret** ✅

#### Environment Variables

| Variable | Required | Default | Description |
|---|---|---|---|
| `OPENROUTER_API_KEY` | ✅ Yes | — | Your OpenRouter API key |
| `OPENROUTER_MODEL_STANDARD` | No | `openai/gpt-4o-mini` | Override the standard-tier model |
| `OPENROUTER_MODEL_PREMIUM` | No | `google/gemini-2.5-flash-lite` | Override the premium-tier model |

***

### How It Works

1. **Validate inputs** — fails immediately with a clear message if anything is misconfigured
2. **Plan batches** — splits your question count into batches of ≤12 to stay within LLM token limits, distributing MCQ and short-answer questions evenly
3. **Generate** — each batch is sent to the LLM with a structured system prompt at temperature 0.3 for factual accuracy
4. **Validate** — every batch is validated with Pydantic; invalid batches are retried up to 3 times
5. **Critique** *(medium/hard only)* — a second LLM call reviews the batch and rewrites any questions that don't meet the difficulty standard
6. **Push** — validated records are pushed to the Apify dataset as flat, camelCase JSON

***

### Use Cases

- 📚 **E-learning & LMS platforms** — auto-generate quizzes for any lesson or module
- 🎓 **Student revision tools** — create practice tests and flashcard-style question sets
- 🧩 **Trivia & quiz apps** — bulk-generate questions across topics and difficulties
- 📊 **Corporate training & HR** — build knowledge-check assessments at scale
- 🤖 **LLM benchmarking** — generate domain-specific evaluation sets
- 🧪 **Research** — create question datasets for NLP and education research

***

### Tips for Best Results

- **Be specific with your topic.** *"Mitochondrial DNA replication in eukaryotes"* produces much better questions than *"Biology"*.
- **Use a 70/30 MCQ-to-short-answer split.** A good default for most learning contexts.
- **Use Hard + Premium for specialist domains.** Medical, legal, and highly technical topics benefit most from both settings.
- **Test with 10 questions first.** Validate the quality before generating a full set of 100.
- **Run multiple times for variety.** Each run generates a fresh set — useful for building large question banks.

***

### Pricing

- **Standard tier** — no additional charge beyond Apify compute fees.
- **Premium tier** — a small Pay Per Event charge is applied per successfully generated question.

***

### License

MIT

# Actor input Schema

## `topic` (type: `string`):

Describe what the quiz should be about (e.g. 'The causes and consequences of World War I' or 'Basic Python programming concepts').

## `total_questions` (type: `integer`):

How many questions to generate in total. Maximum is 50.

## `multiple_choice_count` (type: `integer`):

How many of the total questions should be multiple-choice. Must not exceed Total Questions. The remaining questions will be short-answer. Example: 10 total, 7 multiple-choice → 3 short-answer.

## `quality_tier` (type: `string`):

'standard' uses OpenAI GPT-4o Mini — solid, cost-effective. 'premium' uses Gemini 2.5 Flash Lite — faster and more accurate. A small additional charge applies per question for the premium tier.

## `difficulty` (type: `string`):

Controls how challenging the questions are. 'easy' uses well-known facts. 'medium' requires more specific knowledge. 'hard' tests niche, obscure, or expert-level detail.

## Actor input object example

```json
{
  "topic": "Harry Potter",
  "total_questions": 1,
  "multiple_choice_count": 0,
  "quality_tier": "standard",
  "difficulty": "medium"
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("thescrapelab/apify-quiz-generator").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("thescrapelab/apify-quiz-generator").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call thescrapelab/apify-quiz-generator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=thescrapelab/apify-quiz-generator",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "AI Quiz Crafter",
        "description": "AI-powered quiz generator that creates fact-checked multiple-choice and short-answer questions on any topic. Supports easy, medium, and hard difficulty with a built-in AI review pass. Exports clean, validated JSON for e-learning, trivia apps, and training assessments.",
        "version": "0.0",
        "x-build-id": "3ArTl4dE7eQkfemQn"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/thescrapelab~apify-quiz-generator/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-thescrapelab-apify-quiz-generator",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/thescrapelab~apify-quiz-generator/runs": {
            "post": {
                "operationId": "runs-sync-thescrapelab-apify-quiz-generator",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/thescrapelab~apify-quiz-generator/run-sync": {
            "post": {
                "operationId": "run-sync-thescrapelab-apify-quiz-generator",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "topic",
                    "total_questions",
                    "multiple_choice_count"
                ],
                "properties": {
                    "topic": {
                        "title": "Quiz Topic",
                        "minLength": 5,
                        "maxLength": 300,
                        "type": "string",
                        "description": "Describe what the quiz should be about (e.g. 'The causes and consequences of World War I' or 'Basic Python programming concepts').",
                        "default": "Harry Potter"
                    },
                    "total_questions": {
                        "title": "Total Questions",
                        "minimum": 1,
                        "maximum": 50,
                        "type": "integer",
                        "description": "How many questions to generate in total. Maximum is 50.",
                        "default": 1
                    },
                    "multiple_choice_count": {
                        "title": "Multiple-Choice Questions",
                        "minimum": 0,
                        "maximum": 50,
                        "type": "integer",
                        "description": "How many of the total questions should be multiple-choice. Must not exceed Total Questions. The remaining questions will be short-answer. Example: 10 total, 7 multiple-choice → 3 short-answer.",
                        "default": 0
                    },
                    "quality_tier": {
                        "title": "Quality Tier",
                        "enum": [
                            "standard",
                            "premium"
                        ],
                        "type": "string",
                        "description": "'standard' uses OpenAI GPT-4o Mini — solid, cost-effective. 'premium' uses Gemini 2.5 Flash Lite — faster and more accurate. A small additional charge applies per question for the premium tier.",
                        "default": "standard"
                    },
                    "difficulty": {
                        "title": "Difficulty",
                        "enum": [
                            "easy",
                            "medium",
                            "hard"
                        ],
                        "type": "string",
                        "description": "Controls how challenging the questions are. 'easy' uses well-known facts. 'medium' requires more specific knowledge. 'hard' tests niche, obscure, or expert-level detail.",
                        "default": "medium"
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
