How samalehzen/emd-chat-ai works
Project Type and Purpose
• This is a full-stack, self-hostable AI chat interface built on Next.js (“app” directory), with API routes for chat and user management, and integrations with multiple AI providers (OpenAI, Claude, Gemini, etc.) plus local Ollama models. It uses Supabase for auth & storage, and includes client-side state stores for chats, agents, settings, and user preferences.
Main Components
a. Frontend (Next.js + React)
• “app” directory: pages (client and server components) for chat UI, agent management, auth flows, and static pages.
• “app2/components” & “components”: reusable UI widgets (shadcn/ui, prompt-kit, motion-primitives).
• Hooks: custom React hooks (e.g., useChatDraft) for local state & UI behaviors.
b. Backend (Next.js API Routes & Lib Layer)
• “app/api” routes: chat, create-agent, user & guest creation, CSRF, rate limits, developer-tools, health checks.
• “lib” folder: core business logic & data access
• Providers for AI models (“lib/openproviders”, “lib/providers”)
• Chat & agent stores: in-memory/session via React contexts (“lib/chat-store”, “lib/agent-store”)
• Supabase integration (“lib/supabase” + “utils/supabase”) for DB reads/writes and auth.
• Tools engine (“lib/tools/exa”) for external utilities (web search, image search).
• Config, utilities (fetch wrappers, sanitization, CSRF helper).
c. External Services
• Supabase: Auth, Database, File Storage
• AI Providers: OpenAI/Mistral/Claude/Gemini via Vercel AI SDK & custom providers
• Ollama (local AI): via Docker or direct CLI, auto-detected by “lib/mcp”
Relationships & Data Flow
1) User interacts with Next.js UI →
2) Frontend calls API route (e.g., POST /api/chat/route.ts) →
3) Route handler uses lib/api.ts + lib/chat-store to:
• Validate session/CSRF →
• Persist messages in Supabase (or session store) →
• Call AI provider via lib/openproviders →
• Stream or return AI response →
4) Frontend receives response and updates UI & local store.
5) File uploads: via API route → Supabase Storage → context-aware prompts.
6) Agent creation/deletion: API → Supabase / local store → UI refresh.
Architectural Patterns & Principles
• Next.js App Router: server/client component separation
• Layered architecture: API routes → lib business logic → provider adapters → external services
• React Context / Provider pattern for state stores (Zustand or Context APIs)
• Routing via filesystem for both UI and API
• Extensibility: plugin-style AI provider map and tool invocation modules