# Project export: ChatRealm

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: ChatRealm: Context-aware chat rooms powered by 5 AI agent bureaus and LinkedIn scraper service. Specialized rooms for D&D, AA, and therapy with intelligent, personalized moderation.
- Devpost: https://devpost.com/software/chatrealm
- GitHub: https://github.com/saurabh98s/calhacks24.git
- Video: https://www.youtube.com/embed/huHLto3601A?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (The Bright Data: Best Use of Bright Data)
- Team: 2 GitHub contributor(s) — Saurabh Suman (6 commits), saurav (2 commits)

## Devpost submission (written by the team)

### Inspiration

We started ChatRealm because we saw too many people suffering in silence. In online support groups, we watched quiet voices get drowned out. In therapy sessions, we saw people struggling to share their deepest fears. In recovery communities, we noticed how one person's courage to speak could inspire a whole room, but only if someone was there to hold space for them. Our north star was simple: uplift the people who are scared to speak up. We wanted to build something that amplifies voices that might otherwise go unheard, keeps the room engaged and supportive, and most importantly, keeps people calm and safe when they're sharing the things that frighten them most. Because everyone deserves to be heard, and no one should face their darkest moments alone.

### What it does

ChatRealm is a safe space where AI doesn't replace human connection, it protects and nurtures it. Think of it as having a thoughtful friend in every conversation who notices when someone needs encouragement, steps in when things get heated, and celebrates every small victory. We built three specialized rooms where people need this support most: Dungeons & Dragons rooms aren't just about rolling dice. They're about shy players finding their voice through their characters, building confidence in a world where they can be heroes. Our AI Dungeon Master makes sure everyone gets their moment to shine. Alcoholics Anonymous rooms are sacred spaces where people share their struggles with addiction. Our AI recognizes when someone's celebrating "day one sober" and rallies the room to support them. When someone's struggling with temptation at 2 AM, it's there with resources and encouragement, buying time until human support arrives. Group Therapy rooms are where people work through trauma, anxiety, and depression. Our AI creates the calm, non-judgmental presence that helps people open up. It recognizes when someone's triggered and gently guides the conversation to safer ground, all while making sure quieter voices get heard. Here's what makes us different: our AI learns from your LinkedIn profile (if you choose to share it) to understand who you really are. It's not about stalking, it's about context. When you share your story, the AI knows whether you're a college student facing finals stress or a veteran dealing with PTSD. It tailors its support to meet you where you are.

### How we built it

We knew from day one that this couldn't be a typical chatbot. People's mental health and recovery are too important to trust to a single AI making snap judgments. So we built something different: five specialized AI agents working together like a support team. The Response Coordinator is the team leader, deciding when to speak up and when to stay quiet. Sometimes the best support is silent presence. The Context Manager remembers everything. Not just what you said five minutes ago, but patterns over weeks. It knows if you're improving, struggling, or stuck. The Wellness Guardian is our safety net. It watches for crisis signals, words that suggest someone's in danger, and quietly alerts the system to provide immediate resources. The Emotion Tracker reads the room. It notices when someone's message seems cheerful but their word choice suggests they're masking pain. It picks up on the subtle cries for help. The Toxicity Detector is our bouncer. It keeps the space safe by catching harmful content before it derails someone's healing journey. Tech we used: FastAPI and Python for the backend brain React and TypeScript for the interface people see Socket.IO because conversations happen in real-time, not in turns Anthropic Claude for the AI that actually understands nuance and empathy Fetch.ai's uagents for coordinating our five-agent support team PostgreSQL and Redis for remembering every conversation and context BrightData API for optional LinkedIn profile understanding Docker to keep everything running smoothly We gave ChatRealm a retro pixel-art look on purpose. When you're about to share your deepest fear, a friendly pixel avatar feels less intimidating than a corporate interface. It's approachable while still taking your story seriously. Challenges we ran through Making AI actually empathetic was harder than we thought. Getting five AI agents to work together without tripping over each other required us to completely rethink our architecture. We failed. A lot. Our first version would timeout, crash, or give tone-deaf responses. We learned that real empathy comes from context, so we spent weeks teaching our AI to understand the difference between someone saying "I'm struggling" in a D&D game versus in an AA meeting. Building trust is everything. When someone's sharing that they relapsed, or that they had suicidal thoughts, the AI can't just spit out a generic response. It needs to understand the weight of that moment. We built a sophisticated context system that reads not just words, but the person behind them. LinkedIn integration helps, but so does remembering every interaction and learning from the community's patterns. Knowing when to intervene is an art, not a science. We wanted our AI to feel like a supportive friend, not a surveillance system. Too quiet and people feel abandoned. Too chatty and it drowns out human voices. We're still tuning this, but we built an intelligent intervention system that considers conversation flow, room energy, and individual needs. Sometimes the most supportive thing is silence. Real-time everything, always. Mental health crises don't wait for page refreshes. Someone saying "I can't do this anymore" needs immediate response. We built WebSocket connections, Redis caching, and background processing to ensure the AI is always listening and ready to help within milliseconds.

### Accomplishments we're proud of

Honestly? We're most proud of the moments our AI gets it right. When it notices someone's been quiet for 20 messages and gently asks, "Hey [name], what do you think?" That's amplifying a voice. When someone shares they hit 30 days sober and the AI celebrates with genuine warmth while encouraging others to share their own milestones. That's building community. When it detects crisis language and immediately provides suicide prevention resources while keeping the person engaged until human help arrives. That's saving lives. We built a five-agent AI system that actually works in production. We made it smart enough to know that "let's play" means something completely different in a D&D room versus a therapy session. We created an interface that feels like a game but holds space for the most serious conversations. But the real accomplishment? We built something that makes people feel safe enough to speak up.

### What we learned

Technology is easy. Empathy is hard. We spent months on the technical architecture, but the real challenge was teaching AI to understand human pain and respond with genuine compassion. We learned that more context always beats smarter algorithms. Knowing someone's background, reading conversation history, and understanding room dynamics matters more than any fancy model. Silent support is still support. Our early versions talked too much. We learned that sometimes the AI's job is to just be present, ready to help, while humans connect with humans. The best moderation is invisible until it's needed. People want to be seen. The LinkedIn integration isn't about fancy tech. It's about making someone feel recognized. When the AI understands you're a nurse dealing with burnout, or a student facing academic pressure, its support becomes real instead of generic. Recovery isn't linear, and neither is conversation. Building room-specific AI taught us that every community has its own rhythm, vocabulary, and needs. One size fits nobody when it comes to supporting mental health and recovery.

### What's next

We want to keep building safe spaces: More communities that need support: Veterans with PTSD, LGBTQ+ youth, chronic pain sufferers, grief support groups, neurodivergent communities finding their people. Voice channels where people can talk instead of type, because sometimes speaking your truth out loud is what healing requires. Peer matching that connects you with others who've walked your path. Not random strangers, but people whose stories resonate with yours. Crisis response network that connects to real counselors when AI support isn't enough. We never want to replace human help, just make sure you have support while waiting for it. Long-term progress tracking so you can see how far you've come, even on days when it doesn't feel like it. Community building tools that help natural leaders emerge and peer support flourish. Most importantly, we want to keep listening. To the quiet voices, the scared voices, the voices that have been told to be silent. Because at ChatRealm, everyone gets heard.

## README (from the GitHub repository)

# ChatRealm - Multiplayer AI Chat Arena

**ChatRealm** is a gamified, real-time multiplayer chat platform where users enter virtual "rooms" as avatars, interact with an AI character that maintains individual user context, group dynamics, and conversation flow across diverse scenarios (study groups, support groups, casual hangouts).

## 🌟 Core Features

- **Spatial Chat UI** - Users "walk" into rooms like a 2D game using Phaser.js
- **Context-Aware AI** - Tracks each user's emotional state, participation level, and conversation history
- **Universal Adaptability** - AI persona adapts to room type (study TA, support counselor, casual bartender)
- **Real-time Multiplayer** - WebSocket-based communication for instant updates
- **Gamified Experience** - Avatar customization, room exploration, and engagement tracking

## 🏗️ Architecture

### Frontend
- **React 18** + TypeScript - Modern UI framework
- **Phaser.js 3** - 2D game engine for avatar movement
- **Socket.io-client** - Real-time WebSocket communication
- **Zustand** - Lightweight state management
- **TailwindCSS** + Framer Motion - Styling and animations

### Backend
- **FastAPI** - High-performance async Python API
- **Socket.io** - Bidirectional real-time communication
- **PostgreSQL** - Persistent data storage
- **Redis** - Hot state cache for user/room context
- **SQLAlchemy 2.0** - Database ORM

### AI Integration
- **Janitor AI API** - Primary AI inference (25K token context)
- **Anthropic Claude** - Fallback and validation using Claude 3.5 Sonnet (200K token context)

### Infrastructure
- **Docker** + Docker Compose - Containerized services
- **Nginx** - Reverse proxy and load balancing

## 🚀 Quick Start

### Prerequisites

- Docker and Docker Compose
- Node.js 18+ (for local development)
- Python 3.11+ (for local development)
- Janitor AI API Key
- Anthropic API Key (for Claude)

### Installation

1. **Clone the repository**
```bash
git clone <repository-url>
cd hackathon-cal
```

2. **Set up environment variables**
```bash
cp .env.example .env
```

Edit `.env` and add your API keys:
```env
JANITOR_AI_API_KEY=your-janitor-ai-key
ANTHROPIC_API_KEY=your-anthropic-api-key
SECRET_KEY=your-secret-key-generate-with-openssl
```

Get your Anthropic API key from: https://console.anthropic.com/

3. **Start the application with Docker Compose**
```bash
docker-compose up -d
```

This will start:
- **Frontend** on http://localhost:3000
- **Backend** on http://localhost:8000
- **Nginx** on http://localhost:80
- **PostgreSQL** on localhost:5432
- **Redis** on localhost:6379

4. **Initialize default rooms** (first time only)

Visit http://localhost:8000/docs and use the Swagger UI to call:
```
POST /api/rooms/initialize-defaults
```

Or use curl:
```bash
curl -X POST http://localhost:8000/api/rooms/initialize-defaults \
  -H "Authorization: Bearer YOUR_TOKEN"
```

5. **Access the application**

Open http://localhost:80 in your browser

## 🎮 User Flow

1. **Landing Page** - Welcome screen with animated preview
2. **Avatar Creation** - Customize your character (style, color, mood, bio)
3. **Tutorial Hallway** - Interactive guide showing how to navigate
4. **Room Selection** - Choose from:
   - 🎓 Study Group - Collaborative learning with Dr. Chen (AI)
   - 🤝 Support Circle - Safe space with Sam (AI counselor)
   - 🎮 Casual Lounge - Hang out with Rex (AI bartender)
   - 🏠 Private Room - Solo chat with AI
5. **Room Experience** - Chat, move around, interact with AI and users

## 🛠️ Development

### Frontend Development

```bash
cd frontend
npm install
npm run dev
```

Frontend will be available at http://localhost:3000

### Backend Development

```bash
cd backend
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
uvicorn app.main:app --reload
```

Backend will be available at http://localhost:8000

### Running Tests

```bash
# Backend tests
cd backend
pytest

# Frontend tests
cd frontend
npm test
```

## 📁 Project Structure

```
chatrealm/
├── docker-compose.yml
├── .env.example
├── README.md
├── plan.md                    # Technical design document
│
├── frontend/
│   ├── src/
│   │   ├── components/        # React components
│   │   ├── pages/             # Page components
│   │   ├── game/              # Phaser.js game engine
│   │   ├── services/          # API & Socket services
│   │   ├── store/             # Zustand state management
│   │   └── types/             # TypeScript types
│   ├── Dockerfile
│   └── package.json
│
├── backend/
│   ├── app/
│   │   ├── api/               # REST API routes & WebSocket
│   │   ├── core/              # Database, Redis, Security
│   │   ├── models/            # SQLAlchemy models
│   │   ├── schemas/           # Pydantic schemas
│   │   ├── services/          # Business logic
│   │   └── utils/             # Helper functions
│   ├── Dockerfile
│   └── requirements.txt
│
└── nginx/
    ├── Dockerfile
    └── nginx.conf
```

## 🔑 Key Components

### AI Context Management

The system tracks:
- **User Context**: Sentiment, participation, conversation history
- **Room Context**: Active users, conversation flow, group dynamics
- **AI Triggers**: Direct mentions, confusion detection, silence thresholds

### AI Persona System

Each room type has a unique AI personality:
- **Dr. Chen** (Study Group) - Patient teacher, uses analogies
- **Sam** (Support Circle) - Empathetic counselor, validates emotions
- **Rex** (Casual Lounge) - Charismatic storyteller, social facilitator
- **Atlas** (Tutorial) - Helpful guide, clear instructions

### Real-time Features

- Avatar movement synchronized across clients
- Instant message delivery with typing indicators
- Speech bubbles appear above avatars
- Dynamic user presence tracking

## 🔧 Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `POSTGRES_DB` | PostgreSQL database name | chatrealm |
| `POSTGRES_USER` | PostgreSQL username | chatrealm |
| `POSTGRES_PASSWORD` | PostgreSQL password | chatrealm_password |
| `REDIS_URL` | Redis connection URL | redis://redis:6379/0 |
| `SECRET_KEY` | JWT secret key | (generate with openssl) |
| `JANITOR_AI_API_KEY` | Janitor AI API key | (required) |
| `ANTHROPIC_API_KEY` | Anthropic Claude API key | (required) |
| `CORS_ORIGINS` | Allowed CORS origins | http://localhost:3000,http://localhost:80 |

### API Endpoints

- `GET /health` - Health check
- `POST /api/auth/register` - Register new user
- `POST /api/auth/login` - User login
- `POST /api/auth/guest` - Guest login
- `GET /api/rooms/` - List all rooms
- `POST /api/rooms/` - Create room
- `GET /api/users/me` - Get current user
- `PATCH /api/users/me` - Update user

Full API documentation: http://localhost:8000/docs

## 🐛 Troubleshooting

### Docker Issues

```bash
# Rebuild containers
docker-compose down
docker-compose build --no-cache
docker-compose up -d

# View logs
docker-compose logs -f backend
docker-compose logs -f frontend

# Reset database
docker-compose down -v
docker-compose up -d
```

### Connection Issues

- Ensure all services are running: `docker-compose ps`
- Check backend health: `curl http://localhost:8000/health`
- Verify Redis: `docker-compose exec redis redis-cli ping`
- Check PostgreSQL: `docker-compose exec postgres psql -U chatrealm -d chatrealm -c "SELECT 1"`

### WebSocket Issues

- Check browser console for Socket.io errors
- Verify backend WebSocket endpoint: `ws://localhost:8000/socket.io`
- Ensure CORS is properly configured

## 📝 License

This project is developed for the hackathon.

## 🙏 Acknowledgments

- **Fetch AI** for the AI inference API
- **Anthropic** for Claude 3.5 Sonnet AI capabilities
- **Phaser.js** for the excellent game engine
- **FastAPI** for the modern Python framework

## 📧 Support

For issues and questions:
1. Check the [plan.md](plan.md) for detailed technical documentation
2. Review Docker logs: `docker-compose logs`
3. Open an issue in the reposito

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 81 recognized source files, 465 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Redis (technology) — detected in the code
- SQL (language) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Docker (technology) — claimed on Devpost, not found in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (95 of 95)

```
.gitignore
backend/app/__init__.py
backend/app/api/__init__.py
backend/app/api/routes/__init__.py
backend/app/api/routes/auth.py
backend/app/api/routes/rooms.py
backend/app/api/routes/users.py
backend/app/api/websocket.py
backend/app/config.py
backend/app/core/__init__.py
backend/app/core/database.py
backend/app/core/db_init.py
backend/app/core/init_rooms.py
backend/app/core/migration_001_per_room_usernames.sql
backend/app/core/migration_002_add_persona.sql
backend/app/core/redis_client.py
backend/app/core/security.py
backend/app/main.py
backend/app/models/__init__.py
backend/app/models/message.py
backend/app/models/room.py
backend/app/models/user.py
backend/app/schemas/__init__.py
backend/app/schemas/agent_schemas.py
backend/app/schemas/message_schema.py
backend/app/schemas/room_schema.py
backend/app/schemas/user_schema.py
backend/app/services/__init__.py
backend/app/services/ai_service.py
backend/app/services/context_manager.py
backend/app/services/conversation_memory.py
backend/app/services/enhanced_memory_manager.py
backend/app/services/host_prompt_builder.py
backend/app/services/intelligent_prompt_builder.py
backend/app/services/linkedin_scraper.py
backend/app/services/multiagent_service.py
backend/app/services/room_context_builder.py
backend/app/services/room_service.py
backend/app/services/trigger_ai_service.py
backend/app/services/user_service.py
backend/app/tests.py
backend/app/utils/__init__.py
backend/app/utils/prompt_builder.py
backend/app/utils/sentiment_analyzer.py
backend/app/utils/trigger_detector.py
backend/Dockerfile
backend/fix_imports.py
backend/pyproject.toml
backend/requirements.txt
backend/test_agent_integration.py
backend/test_multiagent.py
docker-compose.override.yml.example
docker-compose.yml
env.example
frontend/Dockerfile
frontend/index.html
frontend/nginx.conf
frontend/package.json
frontend/postcss.config.js
frontend/src/App.tsx
frontend/src/components/ActiveUsersPanel.tsx
frontend/src/components/ChatPanel.tsx
frontend/src/components/EmotionIndicator.tsx
frontend/src/components/GameCanvas.tsx
frontend/src/components/LoadingSpinner.tsx
frontend/src/components/ModerationNotifications.tsx
frontend/src/components/UserList.tsx
frontend/src/game/config.ts
frontend/src/game/GameScene.ts
frontend/src/game/PlayerController.ts
frontend/src/index.css
frontend/src/main.tsx
frontend/src/pages/AvatarCreation.tsx
frontend/src/pages/GameRoom.tsx
frontend/src/pages/Landing.tsx
frontend/src/pages/TutorialHallway.tsx
frontend/src/services/apiService.ts
frontend/src/services/socketService.ts
frontend/src/store/authStore.ts
frontend/src/store/gameStore.ts
frontend/src/store/roomStore.ts
frontend/src/styles/retro-game.css
frontend/src/types/index.ts
frontend/tailwind.config.js
frontend/tsconfig.json
frontend/tsconfig.node.json
frontend/vite.config.ts
nginx/Dockerfile
nginx/nginx.conf
plan.md
README.md
start.sh
stop.sh
target.txt
tests_v2.py
```

### Dependencies

- backend/pyproject.toml: fastapi@^0.104.1, pydantic@^2.5.0, python-socketio@^5.10.0, redis@^5.0.1, sqlalchemy@^2.0.23, uvicorn@^0.24.0
- backend/requirements.txt: aioredis@==2.0.1, alembic@==1.13.1, anthropic@==0.18.1, asyncpg@==0.29.0, celery@==5.3.4, email-validator@==2.1.0, fastapi@==0.109.0, httpx@==0.26.0, passlib[bcrypt]@==1.7.4, psycopg2-binary@==2.9.11, pydantic@==2.9.2, pydantic-settings@==2.1.0, pydantic[email]@==2.9.2, python-dotenv@==1.0.0, python-jose[cryptography]@==3.3.0, python-multipart@==0.0.6, python-socketio@==5.11.0, redis@==5.0.1, sqlalchemy@==2.0.25, uagents@==0.22.10, uagents-core@==0.3.11, uvicorn[standard]@==0.30.1
- frontend/package.json: @types/react@^18.2.43, @types/react-dom@^18.2.17, @typescript-eslint/eslint-plugin@^6.14.0, @typescript-eslint/parser@^6.14.0, @vitejs/plugin-react@^4.2.1, autoprefixer@^10.4.16, axios@^1.6.2, eslint@^8.55.0, eslint-plugin-react-hooks@^4.6.0, eslint-plugin-react-refresh@^0.4.5, framer-motion@^10.16.16, lucide-react@^0.294.0, phaser@^3.60.0, postcss@^8.4.32, react@^18.2.0, react-dom@^18.2.0, react-router-dom@^6.20.1, socket.io-client@^4.5.4, tailwindcss@^3.3.6, typescript@^5.2.2, vite@^5.0.8, zustand@^4.4.7

### Recent commits (newest first)

- Update acknowledgment from Janitor AI to Fetch AI
- final code working
- ALMOST THERE
- WIP:final round
- wip: changes for orchestration
- WIP commit
- feat:multi user chat
- feat:active users
- feat: lgtm :)
- feat: init project

## Key source files (fetched from GitHub, selected and truncated for size)

### plan.md

```markdown
# Technical Design Document: Multiplayer AI Chat Arena

**Project Name:** Talk To Me  


***

## 1. Executive Summary

**ChatRealm** is a gamified, real-time multiplayer chat platform where users enter virtual "rooms" as avatars, interact with an AI character that maintains individual user context, group dynamics, and conversation flow across diverse scenarios (study groups, support groups, casual hangouts).

**Core Innovation:**
- **Spatial chat UI** - Users "walk" into rooms like a 2D game
- **Context-aware AI** - Tracks each user's emotional state, participation level, conversation history
- **Universal adaptability** - AI persona adapts to room type (AA meeting moderator, study TA, casual bartender)

---

## 2. System Architecture

### 2.1 High-Level Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                        FRONTEND LAYER                        │
│  React + Phaser.js (Game Engine) + Socket.io-client        │
│  - 2D Avatar Movement                                       │
│  - Real-time Chat UI                                        │
│  - Emotion Indicators                                       │
└─────────────────┬───────────────────────────────────────────┘
                  │ WebSocket (Socket.io)
                  │ REST API (HTTP)
┌─────────────────▼───────────────────────────────────────────┐
│                       BACKEND LAYER                          │
│  Python (FastAPI) + Socket.io Server + Redis + PostgreSQL  │
│  - WebSocket Manager                                        │
│  - AI Orchestration Service                                 │
│  - User State Manager                                       │
│  - Room Manager                                             │
└─────────────────┬───────────────────────────────────────────┘
                  │ HTTPS
┌─────────────────▼───────────────────────────────────────────┐
│                      AI INFERENCE LAYER                      │
│  Janitor AI API (https://janitorai.com/hackathon/...)      │
│  - Context: 25,000 tokens                                   │
│  - OpenAI-compatible format                                 │
└─────────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────────┐
│                       DATA LAYER                             │
│  Redis (Hot State)          PostgreSQL (Persistent)         │
│  - Active users             - User profiles                  │
│  - Room state               - Chat history                   │
│  - Conversation graph       - Room templates                 │
│  - AI response queue        - Analytics (Do it at the end)   │
└──────────────────────────────────────────────────────────────┘
```

### 2.2 Docker Architecture

```
docker-compose.yml structure:

services:
  - frontend (React + Nginx)
  - backend (FastAPI + Python 3.11)
  - redis (State cache)
  - postgres (Persistent storage)
  - nginx (Reverse proxy)
```

***

## 3. Techn
[truncated — 21955 more characters]
```

### docker-compose.yml

```yaml
version: '3.8'

services:
  # PostgreSQL Database
  postgres:
    image: postgres:15-alpine
    container_name: chatrealm_postgres
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-chatrealm}
      POSTGRES_USER: ${POSTGRES_USER:-chatrealm}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-chatrealm_password}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-chatrealm}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - chatrealm_network

  # Redis Cache
  redis:
    image: redis:7.2-alpine
    container_name: chatrealm_redis
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
    ports:
      - "6379:6379"
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - chatrealm_network

  # Backend API
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: chatrealm_backend
    environment:
      DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-chatrealm}:${POSTGRES_PASSWORD:-chatrealm_password}@postgres:5432/${POSTGRES_DB:-chatrealm}
      REDIS_URL: redis://redis:6379/0
      SECRET_KEY: ${SECRET_KEY:-your-secret-key-change-in-production}
      JANITOR_AI_API_KEY: ${JANITOR_AI_API_KEY:-}
      JANITOR_AI_BASE_URL: ${JANITOR_AI_BASE_URL:-https://janitorai.com/hackathon}
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
      ASI_ONE_API_KEY: ${ASI_ONE_API_KEY:-sk_e804d3f936f8458e852087496c6a3f99518478c238434aa5b3db67957fed4b5e}
      ORCHESTRATOR_ADDRESS: ${ORCHESTRATOR_ADDRESS:-agent1qwyxpqax4rn7p8g0u8h337hcc0lwt0jj8j093jdyfhy8xgcyjuc4jupdart}
      CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:3000,http://localhost:80}
    volumes:
      - ./backend:/app
    ports:
      - "8000:8000"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    networks:
      - chatrealm_network
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

  # Frontend
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
      target: development
    container_name: chatrealm_frontend
    environment:
      VITE_API_URL: ${VITE_API_URL:-http://localhost:8000}
      VITE_WS_URL: ${VITE_WS_URL:-ws://localhost:8000}
    volumes:
      - ./frontend:/app
      - /app/node_modules
    ports:
      - "3000:3000"
    depends_on:
      - backend
    networks:
      - chatrealm_network
    command: npm run dev -- --host

  # Nginx Reverse Proxy
  nginx:
    build:
      context: ./nginx
      dockerfile: Dockerfile
    container_name: chatrealm_nginx
    ports:
      - "80:80"
    depends_on:
      - frontend
      - backend
    networks:
      - chatrealm_network
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro

volumes:
  postgres_data:
  redis_data:

networks:
  chatrealm_network:
    driver: bridge


```

### nginx/Dockerfile

```
FROM nginx:alpine

# Remove default nginx config
RUN rm /etc/nginx/conf.d/default.conf

# Copy custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]


```

### backend/pyproject.toml

```
[tool.poetry]
name = "chatrealm-backend"
version = "0.1.0"
description = "ChatRealm multiplayer AI chat arena backend"
authors = ["ChatRealm Team"]

[tool.poetry.dependencies]
python = "^3.11"
fastapi = "^0.104.1"
uvicorn = {extras = ["standard"], version = "^0.24.0"}
python-socketio = "^5.10.0"
pydantic = "^2.5.0"
sqlalchemy = "^2.0.23"
redis = "^5.0.1"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"


```

### backend/requirements.txt

```
fastapi==0.109.0
uvicorn[standard]==0.30.1
python-socketio==5.11.0
python-multipart==0.0.6
pydantic==2.9.2
pydantic-settings==2.1.0
pydantic[email]==2.9.2
email-validator==2.1.0
sqlalchemy==2.0.25
uagents==0.22.10
uagents-core==0.3.11
asyncpg==0.29.0
alembic==1.13.1
redis==5.0.1
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-dotenv==1.0.0
httpx==0.26.0
anthropic==0.18.1
aioredis==2.0.1
celery==5.3.4
psycopg2-binary==2.9.11

```

### backend/Dockerfile

```
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements first for better caching
COPY requirements.txt .


# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY . .

# Expose port
EXPOSE 8000

# Run the application
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]


```

### frontend/Dockerfile

```
# Multi-stage build for frontend
FROM node:18-alpine AS base

WORKDIR /app

# Copy package files
COPY package.json package-lock.json* ./

# Development stage
FROM base AS development

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "run", "dev", "--", "--host"]

# Build stage
FROM base AS build

RUN npm ci

COPY . .

RUN npm run build

# Production stage
FROM nginx:alpine AS production

COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]


```

### frontend/package.json

```
{
  "name": "chatrealm-frontend",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "phaser": "^3.60.0",
    "socket.io-client": "^4.5.4",
    "zustand": "^4.4.7",
    "axios": "^1.6.2",
    "framer-motion": "^10.16.16",
    "lucide-react": "^0.294.0",
    "react-router-dom": "^6.20.1"
  },
  "devDependencies": {
    "@types/react": "^18.2.43",
    "@types/react-dom": "^18.2.17",
    "@typescript-eslint/eslint-plugin": "^6.14.0",
    "@typescript-eslint/parser": "^6.14.0",
    "@vitejs/plugin-react": "^4.2.1",
    "autoprefixer": "^10.4.16",
    "eslint": "^8.55.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.5",
    "postcss": "^8.4.32",
    "tailwindcss": "^3.3.6",
    "typescript": "^5.2.2",
    "vite": "^5.0.8"
  }
}


```

### frontend/src/main.tsx

```typescript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)


```

### frontend/src/App.tsx

```typescript
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Landing from './pages/Landing'
import AvatarCreation from './pages/AvatarCreation'
import TutorialHallway from './pages/TutorialHallway'
import GameRoom from './pages/GameRoom'
import { useAuthStore } from './store/authStore'

function App() {
  const { isAuthenticated } = useAuthStore()

  return (
    <Router>
      <Routes>
        <Route path="/" element={<Landing />} />
        <Route path="/avatar" element={<AvatarCreation />} />
        <Route 
          path="/tutorial" 
          element={isAuthenticated ? <TutorialHallway /> : <Navigate to="/avatar" />} 
        />
        <Route 
          path="/room/:roomId" 
          element={isAuthenticated ? <GameRoom /> : <Navigate to="/avatar" />} 
        />
        <Route path="*" element={<Navigate to="/" />} />
      </Routes>
    </Router>
  )
}

export default App


```

[76 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]