# How to Trigger the Scene Generation Pipeline via the OpenMAIC API

> Trigger the OpenMAIC scene generation pipeline using the API. Send an authenticated POST request to /api/v1/scenes with your course or session ID and instruction.

- Repository: [MAIC/OpenMAIC](https://github.com/THU-MAIC/OpenMAIC)
- Tags: how-to-guide
- Published: 2026-09-02

---

**You trigger the OpenMAIC scene generation pipeline by sending an authenticated POST request to `/api/v1/scenes` with a JSON payload containing `courseId` (or `sessionId`), `order`, and an optional `instruction` string.**

The OpenMAIC API provides a straightforward REST endpoint for programmatically running the **scene generation pipeline**. This endpoint connects to the backend agent runtime, which orchestrates LLM-based slide creation and real-time frontend updates. Whether you're building custom integrations, automating content workflows, or extending OpenMAIC's classroom features, understanding this API enables seamless programmatic control.

## API Endpoint and Authentication

### Route and Method

```

POST /api/v1/scenes

```

The endpoint follows OpenMAIC's conventional REST pattern, implemented in [`lib/server/api/scenes.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/scenes.ts) (or [`app/api/v1/scenes/route.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/app/api/v1/scenes/route.ts) in the App Router).

### Authentication

Every request must include a valid API key or JWT in the `Authorization` header:

```bash
Authorization: Bearer YOUR_API_TOKEN

```

The validation logic resides in [`lib/server/api/auth.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/auth.ts), which the handler imports and applies before processing any scene generation request.

## Request Payload Structure

The API expects a JSON object with the following fields:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `courseId` | string | Yes* | Identifier of the target course |
| `sessionId` | string | Yes* | Identifier of the target classroom session |
| `order` | number | Yes | Position of the new page (e.g., `1` for first slide) |
| `instruction` | string | No | Free-form guidance for the LLM (e.g., "Add an example about neural networks") |

*Either `courseId` or `sessionId` must be provided.

Example payload:

```json
{
  "courseId": "course-123",
  "order": 3,
  "instruction": "Add a diagram that explains the pipeline"
}

```

## How the Pipeline Executes

When your request reaches the OpenMAIC server, the following sequence occurs according to the source code:

1. **Request validation** – The handler in [`lib/server/api/scenes.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/scenes.ts) authenticates the caller and validates field presence.

2. **Tool dispatch** – The handler invokes the **agent runtime** through [`lib/server/agent-runtime/agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/agent.ts), which maps the tool name `generate_scene` to its implementation.

3. **Generation execution** – The `generate_scene` tool defined in [`lib/server/agent-runtime/tools/generate_scene.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/tools/generate_scene.ts):
   - Constructs the LLM prompt using course context and your `instruction`
   - Calls the language model for content generation
   - Creates scene objects with slide content and action definitions
   - Persists results to the stage store

4. **Real-time notification** – The tool broadcasts updates through OpenMAIC's real-time channel so connected frontends reflect new content immediately.

5. **Response return** – The API responds with HTTP 200 and scene metadata, or an appropriate error code.

The tool schema and preview rendering are additionally defined in [`lib/server/agent-runtime/scene-preview.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/scene-preview.ts), which bridges backend generation with frontend display.

## Code Examples

### cURL

```bash
curl -X POST https://your-openmaic-host.com/api/v1/scenes \
     -H "Authorization: Bearer YOUR_API_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
           "courseId": "course-123",
           "order": 3,
           "instruction": "Add a diagram that explains the pipeline"
         }'

```

### JavaScript (Fetch)

```javascript
async function triggerScene(courseId, order, instruction) {
  const response = await fetch('/api/v1/scenes', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.OPENMAIC_API_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ courseId, order, instruction })
  })

  if (!response.ok) {
    const err = await response.json()
    throw new Error(`API error: ${err.message}`)
  }
  return response.json()   // { id, order, preview, ... }
}

```

### Python (Requests)

```python
import requests

url = 'https://your-openmaic-host.com/api/v1/scenes'
headers = {
    'Authorization': f'Bearer {YOUR_API_TOKEN}',
    'Content-Type': 'application/json'
}
payload = {
    'courseId': 'course-123',
    'order': 2,
    'instruction': 'Explain the data flow with a simple diagram'
}

r = requests.post(url, json=payload, headers=headers)
r.raise_for_status()
scene = r.json()
print(scene)

```

## Success and Error Responses

On success, the API returns HTTP 200 with a JSON object containing:

- `id` – The newly created scene's unique identifier
- `order` – The confirmed page position
- `preview` – A short excerpt of generated content

Error conditions return:

- **401 Unauthorized** – Missing or invalid `Authorization` header (handled by [`lib/server/api/auth.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/auth.ts))
- **400 Bad Request** – Missing required fields (`courseId`/`sessionId` or `order`)
- **500 Internal Server Error** – LLM or runtime failures during generation

## Key Source Files Reference

- **[`lib/server/api/scenes.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/scenes.ts)** – HTTP POST handler receiving requests and forwarding to agent runtime
- **[`lib/server/agent-runtime/scene-preview.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/scene-preview.ts)** – Defines `generate_scene` tool schema and UI preview
- **[`lib/server/agent-runtime/tools/generate_scene.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/tools/generate_scene.ts)** – Core LLM prompt construction and scene creation logic
- **[`lib/server/agent-runtime/agent.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/agent.ts)** – Central tool dispatcher mapping names to implementations
- **[`lib/server/api/auth.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/auth.ts)** – Shared authentication helper for API route protection

## Summary

- **Send a POST request to `/api/v1/scenes`** with `courseId` or `sessionId`, numeric `order`, and optional `instruction` to trigger OpenMAIC scene generation.
- **Include `Authorization: Bearer YOUR_API_TOKEN`** in every request for authentication.
- The pipeline runs through **`generate_scene`** in the agent runtime, which calls the LLM, persists results, and notifies frontends in real time.
- Use the provided **cURL, JavaScript, or Python examples** to integrate into your applications.
- Reference the source files in `lib/server/api/` and `lib/server/agent-runtime/` for implementation details and customization.

## Frequently Asked Questions

### What authentication does the OpenMAIC scene generation API require?

The API requires a Bearer token in the `Authorization` header. You can use either an API key or a JWT issued by the OpenMAIC authentication system. The validation is handled by [`lib/server/api/auth.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/api/auth.ts) before any scene generation logic executes.

### Can I generate scenes without providing instructional text?

Yes. The `instruction` field is optional. When omitted, the `generate_scene` tool relies solely on course context and the LLM's default behavior to produce slide content. Providing instructions, however, yields more targeted and pedagogically relevant results.

### How do I know which order number to use for a new scene?

Query your course or session's existing scenes first via `GET /api/v1/scenes?courseId=XXX` to determine current page positions. The `order` field accepts any positive integer; OpenMAIC does not automatically renumber existing scenes when you insert at an arbitrary position.

### What happens if the LLM fails during scene generation?

If the language model call fails or returns invalid content, the `generate_scene` tool in [`lib/server/agent-runtime/tools/generate_scene.ts`](https://github.com/THU-MAIC/OpenMAIC/blob/main/lib/server/agent-runtime/tools/generate_scene.ts) propagates the error upward. The API returns HTTP 500 with an error message containing failure details, and no partial scene record is committed to the stage store.