AI Support Agent — Multi-Tenant AI Customer Support SaaS

Featured Project
An AI-powered customer support platform that understands your documentation and handles customer queries autonomously. Features intelligent semantic knowledge search across uploaded documents, a 4-tool AI agent that looks up orders, checks inventory, and creates tickets on its own, multi-tenant data isolation with organization-scoped knowledge bases, flexible Free/Pro subscription tiers with plan-based tool gating, and an embeddable chat widget deployable on any website via a single iframe. Built with 17 Prisma data models across 4 business domains, Stripe billing, and 93 automated tests.
6 weeks
Launched: 2026-01
0
Data Models
Prisma models spanning support, e-commerce, knowledge, and team domains with 7 incremental migrations
0
API Endpoints
REST + streaming endpoints with full CRUD, real-time streaming, and webhook processing
0
Automated Tests
Vitest tests with GitHub Actions CI, covering AI tools, plan limits, security, and RAG pipeline
0
AI Agent Tools
autonomous tools (KB search, order status, inventory check, ticket creation) with plan-based gating

Tech Stack Versions

Precise technology versions used in this project

Next.js16.x
React19.x
Vercel AI SDK6.x
Prisma7.x
NextAuth5.x
Tailwind CSS4.x
pgvector0.8.x

Screenshots

Main feature screens of the project

Landing Page — Feature showcase, pricing tiers, and live AI demo

Dashboard Overview — Real-time metrics, conversation volume, and tool usage stats

Analytics — Multi-dimensional charts, AI response efficiency, and ticket trends

Conversation List — Multi-tenant conversation management with status filtering and search

Conversation Detail — AI tool call traces, message streaming, and Widget preview

Product Management — Inventory tracking, pricing, and AI-queryable product data

Order Management — Order status tracking with AI-automated lookup integration

Ticket System — AI-automated ticket creation, agent tracking, and status management

Knowledge Base — RAG document upload, vector indexing, and search testing

Embeddable Widget — Cross-site deployment, API key authentication, and live AI chat

Capabilities Demonstrated

Technical and business capabilities demonstrated through this project

  • Autonomous AI Agent — 4-tool ToolLoopAgent handles order lookups, inventory checks, knowledge search, and ticket creation without human intervention
  • Semantic Knowledge Retrieval — RAG pipeline with Google Gemini embeddings and pgvector cosine similarity delivers sub-second answers from uploaded documents
  • Multi-Tenant Data Isolation — Organization-scoped queries with TOCTOU-safe mutations ensure complete data separation across tenants
  • Defense-in-Depth Security — SHA-256 API key hashing, 3-layer prompt injection sandwich, sliding window rate limiting, and timing-safe authentication
  • Stripe Subscription Billing — Checkout + webhook integration with plan-based feature gating controlling AI tool access per tier

Challenges Faced

Main technical challenges encountered during development

  • Prisma + Edge Runtime compatibility — static imports crash Turbopack workers in Next.js edge environments
  • Multi-tenant data isolation under TOCTOU race conditions — find-then-mutate patterns create cross-tenant vulnerabilities
  • AI prompt injection prevention — organization-customizable system prompts create attack vectors for security rule bypass
  • Plan-based feature gating without per-request performance penalty — checking plan limits on every AI tool call adds latency
  • Widget API key security in multi-tenant context — storing raw keys means database breach exposes all widget credentials

Solutions

Technical solutions and implementation strategies adopted

  • Singleton factory pattern in db.ts using @prisma/adapter-neon with lazy initialization via globalForPrisma, ensuring edge compatibility without static import crashes
  • Atomic updateMany/deleteMany with orgId in WHERE clause collapses check+mutation into single round-trip; session ownership verified before cross-session writes
  • 3-layer prompt construction: base behavior → org custom (sandwiched) → security rules ALWAYS last; validateAndSanitizeMessages strips role:system from client input
  • Tool gating applied at agent construction time — createSupportAgent reads plan limits once, filters tools via Set, zero per-request overhead
  • SHA-256 hashed API keys at creation; widget auth uses hash lookup with raw key fallback; crypto.randomBytes(32) provides 256-bit entropy

Code Snippets

Key implementation code from the project

// src/lib/ai/agent.ts
export function createSupportAgent(
  orgId: string,
  plan = "free",
  customSystemPrompt?: string | null
) {
  const limits = getPlanLimits(plan);
  const allowed = new Set(limits.enabledTools);

  const allTools = {
    searchKnowledgeBase: createSearchKnowledgeBaseTool(orgId),
    getOrderStatus: createGetOrderStatusTool(orgId),
    checkInventory: createCheckInventoryTool(orgId),
    createTicket: createCreateTicketTool(orgId),
  };

  // Plan-based tool gating — filter tools by plan limits
  const tools = Object.fromEntries(
    Object.entries(allTools).filter(([key]) => allowed.has(key))
  ) as typeof allTools;

  return new ToolLoopAgent({
    model: getModel(),
    instructions: buildSystemPrompt(customSystemPrompt),
    tools,
    stopWhen: stepCountIs(10),
  });
}

Architecture Decisions

Key architectural and technical decisions made during development

Context

AI Support Agent requires multi-round tool calls (KB search → order lookup → ticket creation), choosing between a custom tool loop and an SDK.

Options Compared
自建 Tool Loop
Pros
  • Full flow control with precise customization at each step
Cons
  • Must implement tool call parsing, result injection, multi-round loop, and stop conditions
  • Error handling and edge cases must be handled manually
Vercel AI SDK v6 streamText + tools
Pros
  • ToolLoopAgent has built-in multi-round loop, stopWhen step control, and tool result injection
  • toDataStreamResponse() provides unified stream format shared by Dashboard and Widget
Cons
  • Framework dependency; upgrades may introduce breaking changes
Decision

Chose Vercel AI SDK v6: standardized agent framework reduces 300+ lines of boilerplate; stopWhen makes plan-based step limits one-liner; toDataStreamResponse enables Dashboard/Widget to share one Stream Factory

Outcome

Agent core logic compressed to 30 lines; Dashboard and Widget share createChatStream; plan gating configured in one maxSteps line

Technical Highlights

In-depth technical implementation details and architecture design

ToolLoopAgent + 4 Tools + Plan-Based Gating

AI Agent Architecture
  • Vercel AI SDK v6 streamText — multi-round tool calls until resolution
  • stopWhen(stepCountIs(n)) — Free 3 steps / Pro 10 steps, one-line plan gating
  • Dynamic tool assembly — order / inventory / ticket tools injected only for Pro plan

Gemini Embeddings → pgvector Cosine Search → Org-Scoped

RAG Pipeline
  • text-embedding-004 (768 dims) — Google Generative AI text embeddings
  • pgvector <=> cosine distance operator + raw query (Prisma doesn't natively support)
  • Knowledge base fully isolated per org, search results enforced with orgId filter

Organization Model + API Key + Data Isolation

Multi-Tenant SaaS
  • 17 Prisma models — Organization, User, Product, Order, Ticket, ChatSession, Embedding, and more
  • Every Prisma query enforced with orgId — TOCTOU-safe updateMany / deleteMany
  • Free / Pro plan driven by Prisma model, feature gating without hardcoded logic

Prompt Injection Sandwich + SHA256 + Rate Limiting

Security
  • Prompt Injection Sandwich — three-layer system prompt with Security Rules fixed last
  • SHA256 API key hashing — raw key displayed once, plaintext never stored again
  • Rate limiting (in-memory) + CSP / HSTS / X-Frame-Options HTTP security headers

Key Takeaways

Important lessons and reflections from this project

Technical

Co-locate vector data with relational data — pgvector on Neon PostgreSQL eliminates an entire service dependency while maintaining sub-second search. For knowledge bases under 100K chunks per tenant, a co-located extension outperforms a separate vector DB in both latency and operational simplicity.

Real Impact: Zero additional infrastructure, tenant-scoped embeddings via orgId index, queries join Embedding to Document with status filter — all in one database.

Architecture

Gate features at construction, not execution — filtering tools at agent creation time via Set gives zero per-request overhead. The agent literally cannot call tools it does not have. This pattern applies broadly: restrict capabilities at initialization rather than guarding every invocation.

Real Impact: Clean agent factory in ~30 lines, plan gating adds zero runtime overhead, MockLanguageModelV3 enables full demo without API keys.

Process

Security rules as the final prompt section — allowing org-customizable system prompts creates a prompt injection vector. The 3-layer sandwich (base → custom → security) ensures no custom prompt can bypass safety constraints. This should be standard for any LLM app accepting user-configured instructions.

Real Impact: Multi-layered defense with all security tests failing to breach boundaries; org data protected by dual defense at prompt and database layers.

Interested in this project?

Feel free to reach out to discuss similar technical solutions or how I can help with your project.

Contact Me
Contact Me
AI Support Agent — Multi-Tenant AI Customer Support SaaS | Chih-Cheng Tien - Full Stack Developer