Inspiration
Textbooks, lecture slides, and conversational AI chatbots present learners with static paragraphs, abstract equations, and flat diagrams. However, physical intuition and deep computational understanding are not developed through passive reading—they are forged by poking a dynamic system, adjusting its parameters, and observing emergent phase shifts.
Traditional interactive simulations (like PhET or NetLogo) take weeks of manual development per topic and cannot scale dynamically to any arbitrary user query. Raw LLM code generation fails in the other direction: it frequently hallucinates broken canvas calls, introduces infinite loops that freeze browser tabs, and produces "dead sliders" that look interactive but do not affect the underlying mathematics.
We built PlayTheory to solve this: an autonomous compound AI engine that transforms any natural-language concept into a verified, sandboxed, and fully playable simulation in seconds—backed by automated AST loop guards and live self-repair.
What it does
PlayTheory takes any user query—from "TCP congestion control (AIMD)" to "Lotka-Volterra predator-prey dynamics" or "how vaccines train herd immunity"—and automatically designs, codes, verifies, and hosts a live interactive laboratory:
- Live Interactive Canvas & Controls: Generates real-time 60Hz physics simulations with live parameter sliders and multi-series timeseries / phase-space plots.
- Pedagogical Guided Tours: Implements Physics Education Research (PER) principles with predict-then-reveal milestones and misconception callouts.
- Conceptual Mastery Quizzes: Dynamically generates interactive multiple-choice checkpoints that test what the user just observed.
- Autonomous 12-Point Verifier & Self-Repair: Executes static AST security checks, validates finite bounds (no NaN/Infinity), ensures parameter sensitivity, and runs a headless 600-step simulation before rendering. If code fails, an autonomous repair loop patches syntax or runtime errors on the fly.
- Dual Engine Inference: Supports cloud execution via Google Gemini or 100% offline, private on-device generation with local Gemma models (e.g., Gemma 4 12B) via LM Studio with direct in-browser fetching and zero tunnel requirements.
How we built it
PlayTheory is built as a compound AI system that separates architectural planning, code synthesis, and runtime verification:
- Stage 1 (Architectural Planner): Translates the prompt into a strictly validated Zod
SimSpecJSON document defining the physical archetype, state vectors, differential equations, parameter bounds, and visual plots. - Stage 2 (Constrained JS Synthesizer): Synthesizes a self-contained ES2020 simulation engine strictly adhering to the contract
init(params),step(dt, params),draw(ctx, width, height), andmetrics(). - Stage 3 (Acorn AST Loop-Guard Instrumentation): A custom Babel/Acorn AST parser statically inspects loops (
for,while,do-while) and injects runtime counter guards (__pt_loop_ctr_X) to mathematically eliminate browser-freezing infinite loops. - Stage 4 (12-Point Automated Verifier): Headless 600-step execution engine running in an isolated worker/iframe to verify numerical stability, canvas pixel variance, and slider sensitivity.
- Stage 5 (Self-Repair Loop): Cryptographically signed HMAC-SHA256 job tokens cap self-repair attempts at 3, feeding compiler line diagnostics back to the LLM to patch failing checks.
- Stage 6 (Storage & Telemetry): Serverless persistence via Upstash Redis REST API with live sub-50ms roundtrip ping telemetry (
storePingMs).
Challenges we ran into
- Infinite Loops and Browser Lockups: LLM-generated simulation loops can easily freeze the client tab with
while(true)conditions or edge-case numerical traps. We solved this not with brittle regex or timeouts, but by building a true Acorn AST parser that injects iteration counters into every loop block before execution. - Dead Sliders & Fake Interactivity: Generated simulations often had UI sliders that did not alter the simulation state. We built an automated sensitivity check in our headless verifier that sweeps every parameter from min to max across 600 frames, rejecting code where state variance remains flat.
- Connecting Browser to Local LM Studio: Web browsers enforce strict Private Network Access and CORS policies. We designed a direct client-side fetch pipeline allowing users to connect their local Gemma 4 12B model in LM Studio (
http://localhost:1234) directly in-browser with zero remote tunnels or reverse proxies needed.
Accomplishments that we're proud of
- 100% Pass Rate Across 30 Benchmark Concepts: Validated across 30 diverse concepts spanning physics, biology, economics, network systems, and mathematics with a 1.4 ms median verification execution time.
- True Deterministic Self-Repair: Watching the system catch a syntax error or NaN runaway during headless verification, patch the failing lines through targeted compiler diagnostics, and pass on attempt 2 without human intervention.
- Dual Cloud and Local Hybrid Execution: Seamlessly switching between datacenter Gemini models and an offline 12B parameter model running locally on Apple Silicon.
- Real-Time Telemetry: Building a production status dashboard with live Upstash Redis pings, zero mock data, and continuous health verification.
What we learned
- Compound AI beats monolithic prompts: Separating planning (
SimSpec) from code synthesis drastically reduced hallucinations and increased code validity from ~60% to over 95% on the first try. - Deterministic verification is non-negotiable: An LLM cannot grade its own code reliably. Relying on deterministic tools (Acorn AST parsing, 600-step headless execution, and pixel variance math) is essential for real runtime safety.
What's next for PlayTheory
- WebGL & Three.js 3D Archetypes: Expanding beyond 2D Canvas into 3D orbital mechanics, gravitational n-body simulations, and molecular dynamics.
- Audio & Sonification: Synthesizing Web Audio API oscillators to allow users to hear frequency resonance, wave beats, and queue backpressure.
- Classroom Mode & Live Collaboration: Enabling educators to broadcast simulations with synced sliders and student response telemetry.
Built With
- acorn
- ast
- container-queries
- gemma
- google-gemini
- html5
- javascript
- lm-studio
- next.js
- node.js
- react
- redis
- speculation-rules-api
- tailwindcss
- typescript
- upstash-redis
- vercel
- vitest
- web-platform-apis
- zod