# What Is the Purpose of the lib/generation Directory in OpenMAIC?

> Discover the purpose of the lib/generation directory in OpenMAIC. This core directory powers OpenMAIC's AI content generation pipeline, transforming user inputs into slides, quizzes, and interactive content.

- Repository: [MAIC/OpenMAIC](https://github.com/THU-MAIC/OpenMAIC)
- Tags: internals
- Published: 2026-09-12

---

**The lib/generation directory serves as the type-safe core of OpenMAIC's two-stage AI-driven content generation pipeline, bridging user inputs to LLM-powered slide, quiz, and interactive content creation.**

The lib/generation directory in OpenMAIC houses the essential type definitions and server-side runtime logic that power the platform's automated educational content authoring. As implemented in THU-MAIC/OpenMAIC, this module transforms raw user uploads and requirements into structured scene outlines and fully rendered teaching materials through a strongly-typed contract.

## Type Definitions in lib/types/generation.ts

The foundation of the generation system lives in [`lib/types/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/types/generation.ts), which establishes strict TypeScript interfaces for the two-stage transformation process. These definitions enforce **what data enters the generation pipeline, how it is transformed, and what the final product looks like** before reaching the frontend.

### Stage 1 Input and Output Structures

Stage 1 begins with **UploadedDocument** and **UserRequirements** types that capture PDF or DOCX uploads alongside free-form text requirements. The AI processes these inputs to produce **SceneOutline** and **WidgetOutline** objects—high-level blueprints for each slide, quiz, interactive element, or PBL page. According to the source comments, this stage converts "User requirements + documents → Scene Outlines (per-page)" in preparation for full content generation.

### Stage 3 Final Output Types

The concrete deliverables are defined as **GeneratedSlideContent**, **GeneratedQuizContent**, **GeneratedInteractiveContent**, and **GeneratedPBLContent**. These DSL objects represent the finalized teaching materials that the frontend renders directly, completing the transformation from "Scene Outlines → Full Scenes (slide/quiz/interactive/PBL with actions)" as documented in [`lib/types/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/types/generation.ts).

## Runtime Orchestration in lib/server/agent-runtime/

The execution layer within `lib/server/agent-runtime/` bridges the frontend UI to the AI backend through four critical files that handle validation, transformation, and persistence.

### The AgentTool Suite (generation-tools.ts)

The [`lib/server/agent-runtime/generation-tools.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/generation-tools.ts) file exposes the **AgentTool** bundle containing `generate_scene`, `list_scenes`, `generate_actions`, and `duplicate_scene`. Each tool validates parameters, invokes the generation engine via `generateSceneContent` or `generateSceneActions` from `@openmaic/generation`, and persists results using `putSceneBringingCurrent`. The tools enforce **type safety** and **checkpoint recording** throughout the process.

### Content Transformation (generation-content.ts)

The [`generation-content.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/generation-content.ts) module converts persisted scenes into the **GenerationContent** contract expected by the generation engine. This helper ensures that canvas data from existing scenes properly conforms to the input requirements of the AI models.

### AI Call Factory (generation-ai-call.ts)

The [`generation-ai-call.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/generation-ai-call.ts) file implements `createGenerationAiCallFactory`, which constructs LLM prompt wrappers for scene-content and scene-actions generation. This factory handles abort signals and manages the raw AI invocation layer, isolating network logic from business rules.

## Supporting Infrastructure and Constraints

Several auxiliary modules within lib/generation enforce limits and permissions.

- **[`lib/constants/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/constants/generation.ts)** defines bounds such as `MAX_GENERATE_SCENE_MEDIA` and enumerates allowed scene types.
- **[`lib/classroom/generation-permission.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/classroom/generation-permission.ts)** verifies user authorization to execute generation tools within classroom contexts.
- **Test coverage** in `tests/agent-runtime/generation-*.test.ts` and smoke tests in `scripts/generation-node-smoke.mjs` validate end-to-end behavior.

## Practical Implementation Examples

### Generating a New Scene

The `generate_scene` tool accepts structured parameters and orchestrates the full creation flow:

```typescript
// Parameters for a new slide
const params = {
  stageId: 'stage-abc',
  order: 3,
  title: 'Quantum Entanglement',
  type: 'slide',
  brief: 'Explain entanglement in simple terms.',
  materialFacts: ['EPR paradox', 'Bell’s theorem'],
  media: [
    { src: 'https://example.com/entanglement.png', description: 'Entanglement diagram' }
  ],
};

// The agent calls the tool defined in generation-tools.ts
await agent.call('generate_scene', params);

```

This invocation validates media URLs via `concreteMediaSrc` (referenced at lines 35-44), builds a `SceneOutline`, executes `generateSceneContent`, and persists the scene (lines 86-98 in [`generation-tools.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/generation-tools.ts)).

### Listing Existing Scenes

To retrieve metadata for all pages in a stage:

```typescript
const list = await agent.call('list_scenes', { stageId: 'stage-abc' });
console.log(list); // → { pageCount: 5, pages: [{id,…}] }

```

The `list_scenes` implementation (lines 99-108) returns a sorted array of scene metadata without triggering new generation.

### Duplicating Pages

The duplication tool clones existing content while handling order shifts:

```typescript
await agent.call('duplicate_scene', {
  stageId: 'stage-abc',
  templateOrder: 2,
  targetOrder: 6,
  title: 'Copied Slide',
});

```

This operation (lines 80-91 and 104-121) clones the source scene, increments subsequent order indices, and writes the new scene to storage.

## Summary

- The **lib/generation** directory implements OpenMAIC's two-stage AI content pipeline through strict TypeScript contracts and runtime orchestration.
- **[`lib/types/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/types/generation.ts)** defines the data structures for inputs (`UploadedDocument`, `UserRequirements`), intermediate outlines (`SceneOutline`), and final outputs (`GeneratedSlideContent`, etc.).
- **[`lib/server/agent-runtime/generation-tools.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/generation-tools.ts)** provides the AgentTool suite (`generate_scene`, `list_scenes`, etc.) that validates parameters and persists results.
- **Supporting modules** handle AI call factories, content transformation, permission checks, and generation constants like `MAX_GENERATE_SCENE_MEDIA`.

## Frequently Asked Questions

### What data structures define the generation pipeline in OpenMAIC?

The pipeline relies on types defined in [`lib/types/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/types/generation.ts): **UploadedDocument** and **UserRequirements** for inputs, **SceneOutline** for intermediate AI planning, and **GeneratedSlideContent** (plus quiz, interactive, and PBL variants) for final rendered output. These structures enforce type safety across the two-stage transformation process.

### How does the runtime execute generation tools?

The runtime in [`lib/server/agent-runtime/generation-tools.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/generation-tools.ts) exposes **AgentTool** functions that validate inputs, call `generateSceneContent` or `generateSceneActions` from the `@openmaic/generation` package, and persist results via `putSceneBringingCurrent`. Each tool records checkpoints and handles error states before returning success confirmations to the frontend.

### What safety mechanisms protect the generation process?

Safety is enforced through multiple layers: **type validation** via TypeScript contracts, **permission checks** in [`lib/classroom/generation-permission.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/classroom/generation-permission.ts) ensuring classroom users have appropriate rights, and **constraint enforcement** via constants like `MAX_GENERATE_SCENE_MEDIA` defined in [`lib/constants/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/constants/generation.ts).

### Where are generation constants and limits configured?

System limits reside in [`lib/constants/generation.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/constants/generation.ts), which exports values such as `MAX_GENERATE_SCENE_MEDIA` and supported scene type enumerations. These constants govern resource allocation and content boundaries across the generation pipeline.