Skip to content

Repository files navigation

AgentFlow πŸ€–βš‘

The Ultimate AI-Powered Business Automation Platform

License: MIT Node.js Next.js TypeScript PostgreSQL Prisma pnpm

AgentFlow is an enterprise-grade AI automation platform that unifies Large Language Models (LLMs), Retrieval-Augmented Generation (RAG), and Multi-Agent Workflows to streamline customer support, knowledge management, lead handling, and internal business operations.


πŸ“‹ Table of Contents


✨ Key Features

Feature Description
πŸ€– Multi-Agent Workflow Engine Visually design pipelines where specialized agents (Manager, Research, Writer, Reviewer) collaborate
πŸ“š RAG Knowledge Base Upload PDFs, DOCXs, and TXTs to build a vector database for context-aware AI responses
πŸ”§ Dynamic Tool Calling Native integrations for Weather, Email, CRM sync, and internal Databases
🏒 Multi-Tenant RBAC Super Admin, Org Owner, and Team Member roles with strict data isolation
πŸ’³ Stripe Billing & Quotas Built-in subscription management (Free, Pro, Enterprise) with hard plan limits and usage tracking
πŸ”‘ BYOK (Bring Your Own Key) Users can provide their own OpenAI/OpenRouter API keys (stored with AES-256 encryption) for custom billing
πŸ“Š Analytics Dashboard Real-time usage metrics, token consumption, and agent performance tracking
πŸ” Secure Auth JWT-based authentication with email verification and Google OAuth support

πŸ—οΈ System Architecture

AgentFlow utilizes a highly scalable, decoupled monorepo architecture designed for performance and maintainability.

High-Level Architecture

graph TD
    Client["πŸ–₯️ Web Client\nNext.js + TypeScript"] -->|REST API| API["βš™οΈ API Server\nNode.js / Express"]
    API --> DB[("🐘 PostgreSQL\n+ Prisma ORM")]
    API --> Redis[("⚑ Redis\nCache & Sessions")]
    API --> VectorDB[("πŸ” Qdrant\nVector Database")]
    API --> AI["🧠 AI Layer\nOpenAI / OpenRouter\nLangChain / LangGraph"]
    API --> Storage["☁️ Storage\nAWS S3 / Cloudinary"]
    API --> Stripe["πŸ’³ Stripe\nBilling & Payments"]

    style Client fill:#0f172a,stroke:#6366f1,color:#e2e8f0
    style API fill:#0f172a,stroke:#10b981,color:#e2e8f0
    style DB fill:#0f172a,stroke:#3b82f6,color:#e2e8f0
    style Redis fill:#0f172a,stroke:#ef4444,color:#e2e8f0
    style VectorDB fill:#0f172a,stroke:#f59e0b,color:#e2e8f0
    style AI fill:#0f172a,stroke:#8b5cf6,color:#e2e8f0
    style Storage fill:#0f172a,stroke:#06b6d4,color:#e2e8f0
    style Stripe fill:#0f172a,stroke:#ec4899,color:#e2e8f0
Loading

Tech Stack

Layer Technologies
Frontend Next.js 15, TypeScript, Tailwind CSS, ShadCN UI, Redux Toolkit, React Flow
Backend Node.js, Express.js, TypeScript
Database PostgreSQL 15+, Prisma ORM
AI / ML OpenAI API, OpenRouter API, LangChain, LangGraph
Vector Search Qdrant
Cache Redis
Auth JWT, Google OAuth 2.0, Bcrypt
Storage AWS S3, Cloudinary
Payments Stripe
DevOps Docker, Turborepo, pnpm workspaces

πŸ—„οΈ Database ER Diagram

The following diagram represents the complete relational database schema for AgentFlow, showing all entities, their attributes, and relationships.

erDiagram
    User {
        String id PK
        String email UK
        String password
        String name
        String avatar
        UserRole role
        Boolean emailVerified
        String googleId UK
        String refreshToken
        String verificationToken UK
        DateTime verificationExpiry
        String resetToken UK
        DateTime resetTokenExpiry
        DateTime createdAt
        DateTime updatedAt
    }

    Organization {
        String id PK
        String name
        String slug UK
        String logo
        OrgPlan plan
        Json settings
        String ownerId FK
        DateTime createdAt
        DateTime updatedAt
    }

    Team {
        String id PK
        String name
        String orgId FK
        DateTime createdAt
        DateTime updatedAt
    }

    TeamMember {
        String id PK
        TeamMemberRole role
        String teamId FK
        String userId FK
        String invitedEmail
        String inviteToken UK
        Boolean inviteAccepted
        DateTime createdAt
        DateTime updatedAt
    }

    Agent {
        String id PK
        String name
        String description
        String persona
        String modelId
        Json tools
        Boolean isActive
        String orgId FK
        String createdById FK
        DateTime createdAt
        DateTime updatedAt
    }

    Conversation {
        String id PK
        String title
        String agentType
        Json metadata
        String orgId FK
        String userId FK
        DateTime createdAt
        DateTime updatedAt
    }

    Message {
        String id PK
        MessageRole role
        String content
        Int tokens
        Json toolCalls
        Json toolResults
        Json metadata
        String conversationId FK
        DateTime createdAt
    }

    Document {
        String id PK
        String name
        DocumentType type
        String url
        Int size
        DocumentStatus status
        Json metadata
        String error
        String orgId FK
        DateTime createdAt
        DateTime updatedAt
    }

    Embedding {
        String id PK
        String content
        String vectorId UK
        Int chunkIndex
        Json metadata
        String documentId FK
        DateTime createdAt
    }

    Lead {
        String id PK
        String name
        String email
        String phone
        String company
        LeadStatus status
        String source
        String notes
        Json metadata
        String orgId FK
        String createdById FK
        DateTime createdAt
        DateTime updatedAt
    }

    Subscription {
        String id PK
        OrgPlan plan
        SubscriptionStatus status
        String stripeCustomerId UK
        String stripeSubscriptionId UK
        String stripePriceId
        DateTime currentPeriodStart
        DateTime currentPeriodEnd
        String orgId FK
        DateTime createdAt
        DateTime updatedAt
    }

    Payment {
        String id PK
        Int amount
        String currency
        PaymentStatus status
        String stripePaymentId UK
        String invoiceUrl
        Json metadata
        String subscriptionId FK
        DateTime createdAt
    }

    UsageRecord {
        String id PK
        UsageType type
        Int count
        String month
        String orgId FK
        DateTime createdAt
        DateTime updatedAt
    }

    Workflow {
        String id PK
        String name
        String description
        Boolean isActive
        Json viewport
        String orgId FK
        String createdById FK
        DateTime createdAt
        DateTime updatedAt
    }

    WorkflowNode {
        String id PK
        String type
        Float positionX
        Float positionY
        Json data
        String workflowId FK
        DateTime createdAt
    }

    WorkflowEdge {
        String id PK
        String sourceId
        String targetId
        String sourceHandle
        String targetHandle
        String workflowId FK
        DateTime createdAt
    }

    %% Relationships
    User ||--o{ Organization : "owns"
    User ||--o{ TeamMember : "belongs to"
    User ||--o{ Conversation : "has"
    User ||--o{ Lead : "creates"
    User ||--o{ Agent : "creates"
    User ||--o{ Workflow : "creates"

    Organization ||--o{ Team : "has"
    Organization ||--o{ Document : "has"
    Organization ||--o{ Conversation : "has"
    Organization ||--o{ Lead : "has"
    Organization ||--o{ Agent : "has"
    Organization ||--o{ Workflow : "has"
    Organization ||--|| Subscription : "has"
    Organization ||--o{ UsageRecord : "tracks"

    Team ||--o{ TeamMember : "has"

    Document ||--o{ Embedding : "generates"

    Conversation ||--o{ Message : "contains"

    Subscription ||--o{ Payment : "records"

    Workflow ||--o{ WorkflowNode : "contains"
    Workflow ||--o{ WorkflowEdge : "contains"
Loading

πŸ“ Project Structure

This project is organized as a pnpm monorepo managed by Turborepo.

agent-flow/
β”œβ”€β”€ apps/
β”‚   β”œβ”€β”€ api/                    # Express.js Backend API
β”‚   β”‚   └── src/
β”‚   β”‚       β”œβ”€β”€ modules/        # Feature modules (auth, org, agent, ...)
β”‚   β”‚       β”œβ”€β”€ middleware/     # Auth, rate-limiting, error handling
β”‚   β”‚       └── index.ts        # Entry point
β”‚   └── web/                    # Next.js Frontend Application
β”‚       └── src/
β”‚           β”œβ”€β”€ app/            # App Router pages & layouts
β”‚           β”œβ”€β”€ components/     # Reusable UI components
β”‚           └── store/          # Redux state management
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ database/               # Prisma schema & migrations
β”‚   β”‚   └── prisma/
β”‚   β”‚       └── schema.prisma
β”‚   └── shared/                 # Shared TypeScript types & utilities
β”œβ”€β”€ docker-compose.yml          # Local dev infrastructure
β”œβ”€β”€ turbo.json                  # Turborepo pipeline config
└── pnpm-workspace.yaml         # Workspace definition

πŸš€ Getting Started

Prerequisites

Ensure you have the following installed:

1. Clone the repository

git clone https://github.com/your-org/agent-flow.git
cd agent-flow

2. Install dependencies

pnpm install

3. Configure environment variables

cp apps/api/.env.example apps/api/.env
cp apps/web/.env.example apps/web/.env.local

Fill in the required values. See Environment Variables section for details.

4. Start infrastructure with Docker

docker-compose up -d

This starts PostgreSQL, Redis, and Qdrant locally.

5. Setup the database

# Generate Prisma client
pnpm --filter @agentflow/database prisma generate

# Push schema to database
pnpm --filter @agentflow/database prisma db push

# (Optional) Seed the database
pnpm --filter @agentflow/database prisma db seed

6. Run in development mode

pnpm dev
Service URL
πŸ–₯️ Web App http://localhost:3000
βš™οΈ API Server http://localhost:5000
πŸ” Prisma Studio pnpm --filter @agentflow/database prisma studio

7. Production build

pnpm build
pnpm start

βš™οΈ Environment Variables

API (apps/api/.env)

# Database
DATABASE_URL="postgresql://user:password@localhost:5432/agentflow"

# Redis
REDIS_URL="redis://localhost:6379"

# JWT
JWT_SECRET="your-super-secret-jwt-key"
JWT_REFRESH_SECRET="your-refresh-secret"

# AI Providers
OPENAI_API_KEY="sk-..."
OPENROUTER_API_KEY="sk-or-..."

# Vector Database
QDRANT_URL="http://localhost:6333"
QDRANT_API_KEY="your-qdrant-api-key"

# Storage
AWS_ACCESS_KEY_ID="..."
AWS_SECRET_ACCESS_KEY="..."
AWS_S3_BUCKET="agentflow-uploads"
CLOUDINARY_URL="cloudinary://..."

# Stripe
STRIPE_SECRET_KEY="sk_live_..."
STRIPE_WEBHOOK_SECRET="whsec_..."

# Email
SMTP_HOST="smtp.resend.com"
SMTP_PORT=465
SMTP_USER="resend"
SMTP_PASS="re_..."
EMAIL_FROM="[email protected]"

# App
NODE_ENV="development"
PORT=5000
CLIENT_URL="http://localhost:3000"

Web (apps/web/.env.local)

NEXT_PUBLIC_API_URL="http://localhost:5000/api"
NEXT_PUBLIC_APP_URL="http://localhost:3000"
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY="pk_live_..."

🐳 Docker Setup

For a fully containerized local development environment:

# Start all services (PostgreSQL, Redis, Qdrant)
docker-compose up -d

# Check running containers
docker-compose ps

# View logs
docker-compose logs -f

# Stop all services
docker-compose down

The docker-compose.yml exposes:

  • PostgreSQL β†’ localhost:5432
  • Redis β†’ localhost:6379
  • Qdrant β†’ localhost:6333

πŸ“‘ API Overview

The REST API is structured around feature modules:

Module Base Path Description
Auth /api/auth Login, register, OAuth, token refresh
Users /api/users User profile management
Organizations /api/org Org CRUD, settings, members
Teams /api/teams Team management & invitations
Agents /api/agents AI agent creation & configuration
Conversations /api/conversations Chat sessions & message history
Documents /api/documents Knowledge base upload & management
Leads /api/leads CRM lead tracking
Workflows /api/workflows Visual workflow builder
Billing /api/billing Stripe subscriptions & payments
Admin /api/admin Super admin controls

πŸ›‘οΈ Security

  • Authentication: Stateless JWT with short-lived access tokens and rotating refresh tokens.
  • Authorization: Role-Based Access Control (RBAC) β€” SUPER_ADMIN, ORG_OWNER, TEAM_MEMBER.
  • Data Isolation: All queries are scoped by orgId ensuring strict multi-tenant separation.
  • Data at Rest: Organization API keys (BYOK) are stored securely using AES-256-CBC encryption.
  • Rate & Plan Limiting: AI endpoints are protected against abuse. Hard quotas (Agent/Document limits) are enforced by subscription tier.
  • Password Hashing: Bcrypt with configurable salt rounds.
  • Input Validation: Zod schemas validate all incoming request payloads.
  • CORS: Strict origin whitelisting in production.

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch: git checkout -b feat/amazing-feature
  3. Commit your changes: git commit -m 'feat: add amazing feature'
  4. Push to the branch: git push origin feat/amazing-feature
  5. Open a Pull Request

Please follow Conventional Commits for your commit messages.


πŸ“œ License

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


Made with ❀️ by the AgentFlow Team

About

A powerful AI Automation Platform to build, manage, and execute autonomous AI agents with custom tools and RAG-based knowledge integration.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages