---
name: Alakazam
description: Use when building AI-rendered, playable worlds; creating interactive characters; embedding worlds in web apps; editing world graphs; managing sessions and player memory; or integrating generative game content into applications. Reach for this skill when working with the Alakazam API to generate, program, and deploy interactive worlds.
metadata:
    mintlify-proj: alakazam
    version: "1.0"
---

# Alakazam Skill

## Product summary

Alakazam is an API for generating and embedding programmable, playable AI worlds. A world is a graph of states (scenes) and events (player choices) that renders live as players navigate it. You generate a world from a text premise or image, program its logic via HTTP, and embed it in your app using the `@alakazamworld/embed` SDK. The API has two surfaces: **Creation API** (secret key, server-side) for generating and editing worlds, and **Runtime & Embed API** (session tokens, browser-safe) for playing worlds. Key files: environment variable `ALAKAZAM_SECRET_KEY` (server) and `ALAKAZAM_PUBLISHABLE_KEY` (browser reads). Primary docs: https://docs.alakazam.gg

## When to use

Use this skill when:
- **Generating worlds**: Creating playable worlds from text premises, images, or book chapters
- **Programming worlds**: Adding states, wiring transitions, editing the graph, validating changes
- **Creating characters**: Building talk-to-able AI characters with personas, voices, and stance graphs
- **Embedding worlds**: Mounting worlds in web apps with session tokens and the embed SDK
- **Managing sessions**: Minting tokens, handling player memory, refreshing streams for long sessions
- **Versioning**: Snapshotting, branching, checking out, and diffing world versions
- **Testing**: Using test keys for sandbox development before shipping with live keys

## Quick reference

### API endpoints (core)

| Method | Path | Purpose |
|--------|------|---------|
| `POST` | `/v1/worlds` | Generate a world from premise/image/text; import a compiled world |
| `GET` | `/v1/worlds/{id}` | Read world metadata |
| `GET` | `/v1/worlds/{id}/scene` | Read the full graph (states + events) |
| `POST` | `/v1/worlds/{id}/states` | Add a state node |
| `POST` | `/v1/worlds/{id}/events` | Add an event edge (transition or override) |
| `POST` | `/v1/worlds/{id}/ops` | Batch graph operations (atomic) |
| `POST` | `/v1/sessions/token` | Mint a short-lived session token (server-side) |
| `POST` | `/v1/characters` | Create a character (import, explicit, or authored) |
| `POST` | `/v1/characters/{id}/say` | Talk to a character (one turn) |
| `POST` | `/v1/worlds/{id}/versions` | Snapshot the current graph |
| `GET` | `/v1/worlds/{id}/versions` | List the version tree |
| `POST` | `/v1/worlds/{id}/checkout` | Restore a version snapshot |

### Key concepts

- **World**: A programmable graph of states (nodes) and events (edges). Generated from a premise, then edited via API.
- **State**: A scene node with prose description (`base`). Players see it and make choices.
- **Event**: A transition (moves player to another state) or override (re-renders current state). Addressed by unique `name`, not index.
- **Session token**: Short-lived, scoped to one world + one player + one origin. Minted server-side, passed to browser. Never use secret key in browser.
- **Character**: A special world subtype with a brain (persona, lore, voice) and stance graph. Talk to it with `/say`.
- **Version**: A full snapshot of the graph at a point in time. Supports branching, checkout, and rollback.
- **Idempotency-Key**: Header to safely retry requests without duplicate charges. Scoped per (app, mode, key value).

### Authentication

```bash
# Server-side (secret key, never in browser)
export ALAKAZAM_SECRET_KEY="sk_live_…"

# Browser-safe (publishable key, read-only)
export ALAKAZAM_PUBLISHABLE_KEY="pk_live_…"

# Mint a session token on your server
curl -X POST https://api.alakazam.gg/v1/sessions/token \
  -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{"worldId":"<id>","playerIdentity":"user-123","origin":"https://yourgame.com"}'
```

### Embedding (browser)

```javascript
import { createEmbed } from "@alakazamworld/embed";

const embed = createEmbed({
  container: "#game",
  slug: "mystical-forest",
  token: SESSION_TOKEN,  // from your server
  theme: { colorPrimary: "#86ffba" },
  onReady: () => console.log("playing"),
  onChoice: (c) => console.log("player chose", c),
  onEnding: (e) => console.log("ending reached", e),
});

// later
embed.destroy();
```

### Test vs live keys

| Aspect | Test (`sk_test_…`) | Live (`sk_live_…`) |
|--------|-------------------|-------------------|
| **GPU spend** | None — mocked responses | Real generation |
| **Quota** | Generative endpoints uncapped; session tokens metered separately | All operations metered against daily quota |
| **Billing** | Never | Runtime only (session_seconds) |
| **Data isolation** | Separate namespace, private, no slugs | Public/unlisted/featured, shareable |
| **Use case** | Development, CI, testing | Production |

## Decision guidance

### When to use X vs Y

| Scenario | Use | Why |
|----------|-----|-----|
| **Generating a world** | `POST /v1/worlds` with `premise` | Fast, deterministic, good for one-off worlds |
| **Generating from a book** | `POST /v1/worlds` with `text` (single chapter) or `POST /v1/campaigns` (multi-chapter) | Book pipeline reads prose, builds bible, authors acts |
| **Editing the graph** | Deterministic tier (`POST /states`, `/events`, `/ops`) | Precise, scripted control; validates fail-closed |
| **Editing the graph** | Agent tier (`POST /v1/worlds/{id}/edit`) | Natural language; agent authors the change |
| **Embedding a world** | `@alakazamworld/embed` SDK | Zero-dependency, works with any framework, origin-validated |
| **Embedding a character** | Same SDK + `/v1/characters/{id}/say` | Character is a world subtype; same embedding flow |
| **Player memory** | Set `playerIdentity` on session token | Scopes memory per (app, character, player); enables "welcome back" |
| **Long sessions** | `POST /v1/sessions/refresh` + double-buffer | Swaps runtime stream without ending logical session; avoids drift |
| **Versioning** | Snapshot before risky changes; branch to explore alternatives | Git-style tree; checkout to rollback; diff to audit |

## Workflow

### Generate and embed a world

1. **Mint a secret key** on the dashboard (https://play.alakazam.gg/?view=developer). Start with `sk_test_…` for sandbox.
2. **Generate a world** from your server:
   ```bash
   curl -X POST https://api.alakazam.gg/v1/worlds \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"name":"My World","premise":"A mystical forest with glowing mushrooms"}'
   ```
   Save the `worldId` and `slug`.
3. **Read the graph** to understand its structure:
   ```bash
   curl https://api.alakazam.gg/v1/worlds/{worldId}/scene \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY"
   ```
4. **Edit the graph** if needed (add states, wire transitions, validate):
   ```bash
   curl -X POST https://api.alakazam.gg/v1/worlds/{worldId}/states \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"id":"cellar","base":"a low stone cellar, one guttering candle"}'
   ```
5. **Snapshot a version** before shipping:
   ```bash
   curl -X POST https://api.alakazam.gg/v1/worlds/{worldId}/versions \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"title":"v1.0","source":"save"}'
   ```
6. **Mint a session token** on your server for each player:
   ```bash
   curl -X POST https://api.alakazam.gg/v1/sessions/token \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"worldId":"{worldId}","playerIdentity":"user-123","origin":"https://yourgame.com"}'
   ```
7. **Embed in the browser** with the token:
   ```javascript
   createEmbed({ container: "#game", slug: "mystical-forest", token });
   ```

### Create and talk to a character

1. **Create a character** (import, explicit, or authored):
   ```bash
   curl -X POST https://api.alakazam.gg/v1/characters \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"authored":true,"premise":"a grizzled lighthouse keeper"}'
   ```
2. **Mint a session token** for the character (same as worlds):
   ```bash
   curl -X POST https://api.alakazam.gg/v1/sessions/token \
     -H "Authorization: Bearer $ALAKAZAM_SECRET_KEY" \
     -d '{"worldId":"{characterId}","playerIdentity":"user-123"}'
   ```
3. **Talk to the character** from the browser:
   ```javascript
   const turn = await fetch(`https://api.alakazam.gg/v1/characters/{id}/say`, {
     method: "POST",
     body: JSON.stringify({
       token: SESSION_TOKEN,
       text: "what are you working on?",
       currentStance: "neutral",
       history: [{ role: "user", text: "hi" }, { role: "character", text: "Oh — hello." }],
     }),
   }).then(r => r.json());
   // → { reply, stance, emotion, affect, action }
   ```
4. **Voice the reply** (optional):
   ```javascript
   const audio = await fetch(`https://api.alakazam.gg/v1/characters/{id}/tts`, {
     method: "POST",
     body: JSON.stringify({ token: SESSION_TOKEN, text: turn.reply }),
   }).then(r => r.blob());
   new Audio(URL.createObjectURL(audio)).play();
   ```

## Common gotchas

- **Never ship a secret key to the browser.** Always mint a session token on your server and pass that to the client. The two-token rule is non-negotiable.
- **Session tokens are short-lived.** Provide `onTokenExpiring` callback in the embed to refresh from your server. Without it, long sessions will fail mid-play.
- **Events are addressed by `name`, not index.** When updating or deleting an event, use its unique `name` field. Indices change as the graph evolves.
- **Graph writes are fail-closed.** If a mutation would produce an invalid world (dangling refs, cycles, doctrine violations), the API rejects it `422` with `diagnostics`. Nothing persists. Fix the issues and retry.
- **Idempotency keys are scoped per (app, mode, key value).** Test and live keep separate caches. Reusing the same key across modes is safe.
- **Test keys return mocks, not real data.** A test-mode world gets a real UUID but no slug (private). Test-mode `/say` returns canned replies. Swap to a live key to get real generation.
- **Batch ops are atomic.** `POST /v1/worlds/{id}/ops` applies all ops or none. One bad op in the batch doesn't sink the rest — bad ops are collected in `applyErrors`, but a `422` means the final graph failed validation.
- **Concurrency is guarded by `rev` (ETag).** Every read returns a `rev`. Pass it back on your next write as `If-Match` or `expectedRev`. If it's stale, you get `409` — reload and retry.
- **You can't prune the version HEAD points at.** Check out another version first, then prune the one you no longer need.
- **Character memory is per (app, character, playerIdentity).** Anonymous players (`playerIdentity: "anon"`) are never persisted. Pass a real user id to opt in to cross-session memory.
- **Prompt budget is 1900 tokens.** When editing a world, the assembled state/event prose must stay under this limit. `POST /v1/worlds/{id}/lint` reports the budget and current usage.

## Verification checklist

Before submitting work with Alakazam:

- [ ] **Secret key is server-side only.** No `sk_…` in browser code, logs, or version control.
- [ ] **Session tokens are minted per player.** Each player gets their own token, scoped to the world and origin.
- [ ] **Graph is valid.** Run `POST /v1/worlds/{id}/validate` or `lint` before shipping. No dangling refs, no cycles.
- [ ] **Version is snapshotted.** Before major changes, snapshot a version so you can rollback.
- [ ] **Embed has token refresh.** Provide `onTokenExpiring` callback to keep long sessions alive.
- [ ] **Test key works end-to-end.** Verify wiring with `sk_test_…` (mocked, free) before swapping to `sk_live_…`.
- [ ] **Player identity is set.** If you want cross-session memory, pass `playerIdentity` when minting the token (not `"anon"`).
- [ ] **Idempotency key is set on risky ops.** Use `Idempotency-Key` header on `POST /v1/worlds`, `/characters`, `/edit`, `/arcadeify` to safely retry.
- [ ] **Origin is registered.** If embedding cross-origin, register the origin in your app settings and pass it when minting the token.
- [ ] **Concurrency is handled.** If multiple writers edit the same world, pass `If-Match` / `expectedRev` and handle `409` conflicts.

## Resources

- **Full page navigation**: https://docs.alakazam.gg/llms.txt
- **API reference**: https://docs.alakazam.gg/api-reference
- **Graph editing guide**: https://docs.alakazam.gg/graph-editing
- **Embedding guide**: https://docs.alakazam.gg/embedding
- **Characters guide**: https://docs.alakazam.gg/characters

---

> For additional documentation and navigation, see: https://docs.alakazam.gg/llms.txt