Skip to content

AI-powered fanfiction writing platform with CopilotKit + LangGraph.js. Features smart editor, creative wizard, fandom research, and HITL workflows. Deployed on Railway.

Notifications You must be signed in to change notification settings

ChanMeng666/fanfic-lab

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

120 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FanFic Lab

AI-Powered Fanfiction Writing Platform

An innovative AI-powered fanfiction writing platform built with Next.js 16, CopilotKit, and LangGraph.js.
Create amazing fanfiction with an AI assistant that understands your characters, respects canon, and helps bring your stories to life.
Featuring smart editing, creative wizard, fandom research, and Human-in-the-Loop approval workflows.

Live Demo Β· Report Bug Β· Request Feature


Visit FanFic Lab



Share FanFic Lab

Pioneering the future of AI-assisted creative writing. Built for the fanfiction community.


Tech Stack

Important

FanFic Lab combines cutting-edge AI technology with a deep understanding of fanfiction culture. It features CopilotKit for real-time AI suggestions, LangGraph.js for intelligent agent workflows, Tavily for fandom research, and a beautiful "Literary Atelier" design system with Teal + Amber color palette.

Table of Contents

TOC

✨ Overview

FanFic Lab is designed for the fanfiction community, providing:

  • Smart Editor - AI-powered writing assistance with inline suggestions
  • Creative Wizard - Conversational story setup with Human-in-the-Loop (HITL) forms
  • Fandom Research - Tavily-powered research for characters, ships, and world-building
  • Fandom Feed - Discover and filter stories by fandom, ships, and tags
  • Character Management - Track characters and detect out-of-character moments
  • Image Gallery - AI-generated character portraits and scene illustrations (coming soon)
graph TB
    subgraph "User Interface"
        A[Homepage] --> B[Creative Wizard]
        A --> C[Smart Editor]
        A --> D[Fandom Feed]
        B --> C
    end

    subgraph "AI Layer"
        E[CopilotKit Provider]
        F[LangGraph Agent]
        G[OpenAI GPT-4o]
        H[Tavily Search]
    end

    subgraph "Backend"
        I[Next.js API Routes]
        J[Prisma ORM]
        K[Neon PostgreSQL]
        L[Redis Cache]
    end

    C --> E
    B --> E
    E --> I
    I --> F
    F --> G
    F --> H
    I --> J
    J --> K
    I --> L
Loading

πŸš€ Key Features

1 Smart Editor with AI Assistance

Experience next-generation writing with AI-powered inline suggestions. The Smart Editor integrates CopilotKit for real-time assistance, helping you write better fanfiction faster.

Feature Description
CopilotTextarea Inline AI suggestions while typing
Magic Continue AI writes the next 200-300 words naturally
Expand Text Enhance selected text with more dialogue/description/emotion
Polish Prose Improve writing quality at light/medium/deep levels
Autosave Automatic saving with debounce to localStorage
HITL Approval Review and approve/edit AI-generated content

2 Creative Wizard with Fandom Research

Revolutionary story setup wizard that researches your fandom using Tavily API, understands your characters, and generates story outlines for your approval.

Feature Description
Fandom Selector Browse popular fandoms or enter custom
Source Research Tavily-powered research for characters, ships, world-building
Ship Builder Define romantic pairings with AI suggestions
Character Setup Add characters with AI-enhanced profiles
Outline Generation AI creates story outline for HITL approval
Step Progress Visual progress tracking through wizard

3 Character & OOC System

Intelligent character management with out-of-character detection to keep your characters authentic.

Feature Description
Character Sidebar Add/manage characters with personality traits
OOC Detection AI checks for out-of-character moments
Character Profiles Name, fandom, personality, speech patterns
Original Characters Support for OCs with custom definitions
Dialogue Suggestions In-character dialogue generation

4 Fandom Feed

Discover and filter stories by fandom, ships, tags, rating, and status.

Feature Description
Story Cards Display story info with cover images and metadata
Tag Filtering Filter by relationship, setting, tone, content
Fandom Tabs Quick navigation between fandoms
Rating/Status Filters Filter by age rating and completion status
Sorting Sort by recent, popular, comments, word count
Infinite Scroll Load more stories seamlessly

* Additional Features

  • πŸ’¨ Quick Setup: Deploy in under 5 minutes with Railway deployment
  • 🌐 Responsive Design: Beautiful UI on desktop and mobile
  • πŸ”’ Authentication: Stack Auth for secure user management
  • πŸ’Ž Literary Atelier Design: Teal + Amber color palette with elegant typography
  • πŸ—£οΈ Real-time AI: Live AI suggestions and generation
  • πŸ“Š Research Cache: Redis caching for Tavily search results (30-day TTL)
  • πŸ”Œ Extensible: Plugin-ready architecture for custom functionality
  • ☁️ Cloud Storage: Cloudinary integration for image hosting

✨ More features are continuously being added as the project evolves.

πŸ› οΈ Tech Stack

Next.js
Next.js 16
React
React 19
TypeScript
TypeScript 5
TailwindCSS
TailwindCSS 4
PostgreSQL
PostgreSQL
Redis
Redis
OpenAI
GPT-4o
Layer Technology Deployment
Framework Next.js 16 (App Router, Turbopack) Railway
UI React 19, TailwindCSS 4, shadcn/ui Railway
AI Runtime CopilotKit 1.x Railway
AI Agent LangGraph.js 1.0 Railway
LLM OpenAI GPT-4o / GPT-4o-mini OpenAI API
Search Tavily API Tavily
Database Neon PostgreSQL + Prisma 7 Neon
Cache Redis (ioredis) Upstash
Auth Stack Auth Stack Auth Cloud
Storage Cloudinary Cloudinary

πŸ—οΈ Architecture

System Architecture

Tip

FanFic Lab uses a unified Railway deployment: Both the Next.js frontend and LangGraph agent run on Railway, communicating via private networking for low latency and no timeout limits.

graph TB
    subgraph "Railway (Web Service)"
        A[Next.js 16] --> B[React 19]
        B --> C[CopilotKit 1.x]
        C --> D[API Routes]
        D --> E[Prisma 7]
    end

    subgraph "Railway (Agent Service)"
        F[LangGraph.js 1.0] --> G[chat_node]
        F --> H[research_node]
        F --> I[outline_node]
        F --> J[tool_node]
    end

    subgraph "External Services"
        K[OpenAI API]
        L[Tavily API]
        M[LangSmith]
    end

    subgraph "Data Layer"
        N[Neon PostgreSQL]
        O[Redis Cache]
        P[Cloudinary]
    end

    D -->|Private Network| F
    G --> K
    H --> L
    F --> M
    E --> N
    D --> O
    D --> P
Loading

Agent Workflow (LangGraph)

The agent uses dedicated graph nodes for HITL operations instead of tools. This is a workaround for the CopilotKit/LangGraph.js ToolMessage format incompatibility.

graph TD
    A[START] --> B{routeFromStart}
    B -->|Research Request| C[research_node]
    B -->|Outline Request| D[outline_node]
    B -->|Default| E[chat_node]

    C --> F[Tavily Search x4]
    F --> G[LLM Aggregation]
    G --> H[Emit State with researchData]
    H --> I[Return AIMessage]

    D --> J[Generate Outline]
    J --> K[Set pendingContent]
    K --> L[Emit State for HITL]
    L --> I

    E --> M{Has Tool Call?}
    M -->|Yes| N[tool_node]
    M -->|No| I

    N --> O[Execute Tool]
    O --> I

    I --> P[END]
Loading

HITL (Human-in-the-Loop) Pattern

sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant CK as CopilotKit
    participant Agent as LangGraph Agent

    Agent->>CK: copilotkitEmitState(pendingContent)
    CK->>FE: State Update
    FE->>FE: useCoAgentStateRender detects pendingContent
    FE->>U: Render Approval Card
    U->>FE: Approve/Edit/Reject
    FE->>CK: respond({ data })
    CK->>Agent: Continue with user input
Loading

πŸš€ Getting Started

Prerequisites

Important

Ensure you have the following installed:

  • Node.js 20.9.0+ (required by Prisma 7.2.0)
  • npm/yarn/pnpm package manager
  • Git
  • PostgreSQL database (Neon recommended)
  • OpenAI API key

Quick Installation

1. Clone Repository

git clone https://github.com/ChanMeng666/fanfic-lab.git
cd fanfic-lab

2. Install Dependencies

npm install

3. Environment Setup

cp .env.example .env.local
# Edit .env.local with your values

4. Database Setup

# Generate Prisma client
npx prisma generate

# Run database migrations
npx prisma migrate dev

5. Start Development

# Start both Next.js and LangGraph agent
npm run dev:all

πŸŽ‰ Success! Open http://localhost:3000 to view the application.

Development Commands

npm run dev        # Start Next.js dev server only
npm run dev:agent  # Start LangGraph agent only
npm run dev:all    # Start both services (recommended)
npm run build      # Build for production
npm run start      # Start production server
npm run lint       # Run ESLint

πŸ” Environment Variables

Local Development (.env.local)

# Database (Neon PostgreSQL)
DATABASE_URL=postgresql://user:pass@host.neon.tech/fanficlab?sslmode=require

# Stack Auth
STACK_SECRET_SERVER_KEY=ssk_...
NEXT_PUBLIC_STACK_PROJECT_ID=...
NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY=pck_...

# OpenAI (required for AI features)
OPENAI_API_KEY=sk-...

# LangGraph (local development)
LANGGRAPH_URL=http://localhost:8123

# Redis (for research caching)
REDIS_URL=redis://localhost:6379

# Cloudinary (for image hosting)
CLOUDINARY_CLOUD_NAME=...
CLOUDINARY_API_KEY=...
CLOUDINARY_API_SECRET=...

# Optional: Together AI for image generation (currently disabled)
TOGETHER_API_KEY=...

# Optional: LangSmith for tracing
LANGSMITH_API_KEY=lsv2_...

# Optional: Admin endpoint protection
ADMIN_SECRET=...

Production Environment Variables

Variable Description Required
DATABASE_URL Neon PostgreSQL connection string βœ…
STACK_SECRET_SERVER_KEY Stack Auth server key βœ…
NEXT_PUBLIC_STACK_PROJECT_ID Stack Auth project ID βœ…
NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY Stack Auth client key βœ…
LANGGRAPH_URL Railway agent URL βœ…
OPENAI_API_KEY OpenAI API key βœ…
REDIS_URL Redis connection string βœ…
CLOUDINARY_* Cloudinary credentials βœ…
LANGSMITH_API_KEY LangSmith API key πŸ”Ά
TAVILY_API_KEY Tavily API key (Railway) βœ…
ADMIN_SECRET Admin endpoint protection πŸ”Ά

βœ… Required, πŸ”Ά Optional

πŸ“Š Database Schema

erDiagram
    User ||--o{ Story : writes
    User ||--o{ Character : creates
    User ||--o{ Draft : has
    User ||--|| UserPreferences : configures
    User ||--o{ Follow : follows
    Story ||--o{ Chapter : contains
    Story ||--o{ StoryCharacter : features
    Story ||--o{ Like : receives
    Story ||--o{ Comment : has
    Character ||--o{ StoryCharacter : appears_in
    Story ||--o{ Image : includes

    User {
        string id PK
        string stackAuthId UK
        string email UK
        string username UK
        string displayName
        string avatarUrl
        string bio
    }

    Story {
        string id PK
        string title
        string summary
        string fandom
        string[] ships
        string[] tags
        enum rating
        enum status
        int wordCount
        string coverImageUrl
    }

    Character {
        string id PK
        string name
        string fandom
        string[] personalityTraits
        string speechPatterns
        boolean isOriginal
        string portraitUrl
    }

    SourceResearchCache {
        string id PK
        string sourceName
        string sourceType
        string normalizedName UK
        json researchData
        int searchCount
        datetime lastAccessedAt
    }
Loading

πŸ“ Project Structure

fanfic-lab/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/                          # Next.js App Router
β”‚   β”‚   β”œβ”€β”€ api/                      # API routes
β”‚   β”‚   β”‚   β”œβ”€β”€ copilotkit/          # CopilotKit runtime
β”‚   β”‚   β”‚   β”œβ”€β”€ research-cache/      # Redis caching
β”‚   β”‚   β”‚   β”œβ”€β”€ health/              # Health check
β”‚   β”‚   β”‚   β”œβ”€β”€ admin/cache-stats/   # Cache analytics
β”‚   β”‚   β”‚   └── upload/cover/        # Cover upload
β”‚   β”‚   β”œβ”€β”€ (main)/                   # Main routes
β”‚   β”‚   β”‚   β”œβ”€β”€ (protected)/         # Auth required
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ editor/          # Smart Editor
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ wizard/          # Creative Wizard
β”‚   β”‚   β”‚   β”‚   └── profile/         # User Profile
β”‚   β”‚   β”‚   └── feed/                # Fandom Feed (public)
β”‚   β”‚   └── handler/[...stack]/      # Stack Auth
β”‚   β”‚
β”‚   β”œβ”€β”€ components/                   # React components
β”‚   β”‚   β”œβ”€β”€ ui/                      # shadcn/ui components
β”‚   β”‚   β”œβ”€β”€ editor/                  # Editor components
β”‚   β”‚   β”œβ”€β”€ wizard/                  # Wizard components
β”‚   β”‚   β”œβ”€β”€ feed/                    # Feed components
β”‚   β”‚   β”œβ”€β”€ hitl/                    # HITL approval cards
β”‚   β”‚   β”œβ”€β”€ layout/                  # Layout components
β”‚   β”‚   └── providers/               # Context providers
β”‚   β”‚
β”‚   β”œβ”€β”€ agent/                        # LangGraph agent
β”‚   β”‚   β”œβ”€β”€ agent.ts                 # Workflow definition
β”‚   β”‚   β”œβ”€β”€ state.ts                 # State annotation
β”‚   β”‚   └── tools/                   # Agent tools
β”‚   β”‚
β”‚   └── lib/                          # Utilities
β”‚       β”œβ”€β”€ hooks/                   # Custom hooks
β”‚       β”œβ”€β”€ actions/                 # Server actions
β”‚       β”œβ”€β”€ types/                   # TypeScript types
β”‚       β”œβ”€β”€ db.ts                    # Database client
β”‚       β”œβ”€β”€ redis.ts                 # Redis client
β”‚       └── cloudinary.ts            # Cloudinary client
β”‚
β”œβ”€β”€ prisma/
β”‚   β”œβ”€β”€ schema.prisma                # Database schema
β”‚   └── migrations/                  # Migrations
β”‚
β”œβ”€β”€ docs/
β”‚   └── COPILOTKIT_LANGGRAPH_HITL_GUIDE.md
β”‚
└── public/                          # Static assets

πŸ“‘ API Reference

POST /api/copilotkit

CopilotKit runtime endpoint that routes requests to the LangGraph agent.

const runtime = new CopilotRuntime({
  agents: {
    fanfic_agent: new LangGraphAgent({
      deploymentUrl: process.env.LANGGRAPH_URL,
      graphId: "fanfic_agent",
    }),
  },
});

GET/POST /api/research-cache

Research results caching endpoint (Redis).

Method Query/Body Description
GET ?sourceName=X&sourceType=Y Check if cached research exists
POST { sourceName, sourceType, researchData } Save research results (30-day TTL)
DELETE ?sourceName=X Clear cache (requires ADMIN_SECRET)

GET /api/health

Service health check endpoint.

{
  "status": "healthy",
  "services": {
    "redis": { "status": "up", "latency": 5 },
    "database": { "status": "up", "latency": 12 }
  }
}

POST /api/upload/cover

Cover image upload endpoint.

  • Validates user authentication and story ownership
  • Accepts: jpeg, png, webp (max 5MB)
  • Uploads to Cloudinary
  • Returns: URL, publicId, dimensions

πŸ›³ Deployment

Cloud Deployment (Railway)

FanFic Lab runs entirely on Railway with two services communicating via private networking.

Deploy on Railway

Railway Services:

Service Config File Start Command
Web (Next.js) railway.json + nixpacks.toml npm run start
Agent (LangGraph) railway-agent.json + nixpacks-agent.toml npm run start:agent

Production URLs

Service URL
Frontend https://www.fanfic-lab.tech
Agent (Internal) http://fanfic-lab.railway.internal:8123

Architecture Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  Railway Project                   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚    Web Service      β”‚  β”‚   Agent Service     β”‚ β”‚
β”‚  β”‚    (Next.js 16)     β”‚  β”‚   (LangGraph.js)    β”‚ β”‚
β”‚  β”‚                     β”‚  β”‚                     β”‚ β”‚
β”‚  β”‚  β€’ React 19         β”‚  β”‚  β€’ chat_node        β”‚ β”‚
β”‚  β”‚  β€’ CopilotKit 1.x   β”‚  β”‚  β€’ research_node    β”‚ β”‚
β”‚  β”‚  β€’ Prisma 7         β”‚  β”‚  β€’ outline_node     β”‚ β”‚
β”‚  β”‚  β€’ Stack Auth       β”‚  β”‚  β€’ tool_node        β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚             β”‚    Private Network     β”‚            β”‚
β”‚             β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β–Ό                 β–Ό                 β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚   Neon   β”‚      β”‚  Upstash β”‚      β”‚Cloudinaryβ”‚
   β”‚PostgreSQLβ”‚      β”‚  Redis   β”‚      β”‚  Images  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🀝 Contributing

We welcome contributions! Here's how you can help improve FanFic Lab:

1. Fork & Clone

git clone https://github.com/ChanMeng666/fanfic-lab.git
cd fanfic-lab

2. Create Branch

git checkout -b feature/your-feature-name

3. Make Changes

  • Follow our coding standards in CLAUDE.md
  • Add tests for new features
  • Update documentation as needed

4. Submit PR

  • Provide clear description
  • Reference related issues
  • Ensure CI passes

πŸ‘₯ Team

Chan Meng
Chan Meng

Creator & Lead Developer

πŸ™‹β€β™€οΈ Author

Chan Meng

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Open Source Benefits:

  • βœ… Commercial use allowed
  • βœ… Modification allowed
  • βœ… Distribution allowed
  • βœ… Private use allowed

Built with ❀️ for the fanfiction community

AI-powered, community-driven.


⭐ Star us on GitHub β€” it helps!

About

AI-powered fanfiction writing platform with CopilotKit + LangGraph.js. Features smart editor, creative wizard, fandom research, and HITL workflows. Deployed on Railway.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •