---
name: supabase-rag-knowledge
description: Customer knowledge base ingestion and RAG-powered query system using Supabase pgvector for Vapi voice agents
status: backlog
created: 2025-10-22T15:04:27Z
---

# PRD: Supabase RAG Knowledge Base System

## Executive Summary

Build a Retrieval-Augmented Generation (RAG) knowledge base system that enables BuzzTrail voice agents (starting with Vapi) to answer customer-specific questions by querying ingested website content. The system uses Supabase's native pgvector for semantic search, Firecrawl for web scraping, and provides a simple admin-managed workflow for ingesting customer documentation.

**Key Value Proposition**: Voice agents can provide accurate, customer-specific answers by retrieving relevant information from the customer's own documentation, improving conversation quality and reducing hallucinations.

**Initial Scope**: Launch with 3 pilot customers, admin-managed ingestion only, Vapi integration first.

---

## Problem Statement

### Current State
BuzzTrail's voice agents (Vapi, LiveKit, Tavus) can only answer questions based on their training data and system prompts. When customers ask product-specific questions ("How do I reset my password on your platform?"), agents either:
- Hallucinate answers based on general knowledge
- Give generic responses that don't match the customer's actual product
- Fail to answer entirely

### Impact
- **Customer Frustration**: Inaccurate or unhelpful responses during demos/support calls
- **Reduced Trust**: Customers lose confidence in AI agents
- **Missed Sales Opportunities**: Demos fail to showcase customer-specific value
- **Support Escalations**: Questions that could be answered must be escalated to humans

### Why Now?
1. **Vapi Customers Requesting**: Voice-only customers need knowledge base integration
2. **Competitive Necessity**: Modern AI platforms expect RAG capabilities
3. **Infrastructure Ready**: We already use Supabase, have voice agents deployed
4. **Proven Use Case**: Vapi provides custom knowledge base API integration

---

## User Stories

### Primary Persona: BuzzTrail Admin (Implementation Engineer)

**User Story 1: Ingest Customer Documentation**
```
As a BuzzTrail admin
I want to ingest a customer's documentation website
So that their voice agent can answer product-specific questions

Acceptance Criteria:
- Can run CLI command from laptop with customer URL
- System scrapes website using Firecrawl (handles JS rendering)
- Raw content stored in Supabase Storage (per customer/website)
- Content chunked and embedded using OpenAI
- Vectors stored in Supabase pgvector with customer isolation
- Process completes in < 5 minutes for typical doc site (50 pages)
- Can verify ingestion success via Supabase dashboard
```

**User Story 2: Re-ingest Updated Documentation**
```
As a BuzzTrail admin
I want to re-ingest a customer's docs when they've updated their site
So that the knowledge base stays current

Acceptance Criteria:
- Can run same CLI command to refresh existing knowledge base
- Old vectors are replaced with new ones
- Raw content in storage is updated
- Process preserves customer_id and kb_id for continuity
```

**User Story 3: Monitor Query Performance**
```
As a BuzzTrail admin
I want to see how often customers query the knowledge base
So that I can validate it's being used and working

Acceptance Criteria:
- Can view query logs in Supabase Edge Function logs
- See customer_id, query text, results returned
- Identify failed queries or empty results
```

### Secondary Persona: End Customer (Via Vapi Voice Call)

**User Story 4: Get Product-Specific Answers**
```
As an end customer calling a Vapi voice agent
I want to ask questions about the product
And receive accurate answers from the company's actual documentation

Acceptance Criteria:
- Ask question like "How do I reset my password?"
- Voice agent searches customer's knowledge base
- Returns relevant answer from actual docs
- Cites source URL when possible
- Response time < 3 seconds total (including search + LLM)
```

**User Story 5: Fallback to General Knowledge**
```
As an end customer
When I ask a question not in the knowledge base
I want the agent to gracefully handle it
Instead of giving a wrong answer

Acceptance Criteria:
- If no relevant results found (similarity < 0.7)
- Agent acknowledges "I don't have specific documentation on that"
- Agent can still try to answer generally or offer to escalate
```

---

## Requirements

### Functional Requirements

#### FR1: Web Scraping & Ingestion
- **FR1.1**: CLI tool runs on admin's laptop (no deployment required for ingestion)
- **FR1.2**: Use Firecrawl API to scrape customer websites
  - Support up to 100 pages per site (configurable)
  - Handle JavaScript-rendered content
  - Extract clean markdown from HTML
  - Respect robots.txt and crawl delays
- **FR1.3**: Store raw scraped content in Supabase Storage
  - Structure: `customer-docs/{customer_id}/{kb_id}/`
  - Files: `raw_pages.json`, `page_*.md`, `metadata.json`
- **FR1.4**: Support public websites only (no authentication in v1)

#### FR2: Content Processing
- **FR2.1**: Chunk scraped content using RecursiveCharacterTextSplitter
  - Chunk size: 1000 characters
  - Overlap: 200 characters
  - Preserve metadata: source URL, page title
- **FR2.2**: Generate embeddings using OpenAI `text-embedding-3-small`
  - Batch requests (100 chunks at a time) for efficiency
  - Store 1536-dimension vectors
- **FR2.3**: Store vectors in Supabase `knowledge_chunks` table
  - Include: customer_id, chunk_text, embedding, metadata

#### FR3: Query API
- **FR3.1**: Supabase Edge Function exposes `/knowledge-query` endpoint
- **FR3.2**: Accept input: `{ messages: [...], customer_id: "..." }`
  - Messages in Vapi format (array of {role, content} objects)
  - Extract user's query from last user message
- **FR3.3**: Hybrid search combining semantic and keyword search
  - **Semantic search**: pgvector cosine similarity on embeddings
  - **Keyword search**: PostgreSQL full-text search (tsvector)
  - **Fusion**: Reciprocal Rank Fusion (RRF) to combine results
  - Return top 5 most relevant chunks
  - Minimum similarity threshold: 0.7 for semantic results
- **FR3.4**: Return results in Vapi-compatible format
  - `{ results: [{ content, score, metadata }] }`
- **FR3.5**: API key authentication (x-api-key header)

#### FR4: Vapi Integration
- **FR4.1**: Configure Vapi assistant with custom knowledge base
  - Point to Edge Function URL
  - Pass API key in headers
  - Map customer_id from call metadata
- **FR4.2**: Results automatically included in LLM context
- **FR4.3**: LLM uses retrieved content to answer questions

#### FR5: Customer Data Isolation
- **FR5.1**: All data segregated by `customer_id`
- **FR5.2**: Storage organized: `customer-docs/{customer_id}/{kb_id}/`
- **FR5.3**: Database queries filtered by customer_id
- **FR5.4**: One customer cannot access another's data

### Non-Functional Requirements

#### NFR1: Performance
- **NFR1.1**: Query latency < 500ms (embedding generation + vector search)
- **NFR1.2**: Ingestion completes in < 5 minutes for 50-page site
- **NFR1.3**: Support 5 concurrent queries without degradation
- **NFR1.4**: Edge Function cold start < 2 seconds

#### NFR2: Reliability
- **NFR2.1**: 99% query success rate
- **NFR2.2**: Graceful degradation if OpenAI API is down
- **NFR2.3**: Retry logic for transient failures
- **NFR2.4**: Error messages are actionable

#### NFR3: Scalability
- **NFR3.1**: Support 3 customers initially (launch target)
- **NFR3.2**: Architecture supports scaling to 50+ customers
- **NFR3.3**: Supabase free tier sufficient for 3 customers
  - ~150,000 vectors total (3 customers × 50 pages × 1000 chunks)
  - pgvector free tier supports up to 1M vectors

#### NFR4: Security
- **NFR4.1**: Edge Function protected by API key
- **NFR4.2**: Only service role can access Supabase Storage
- **NFR4.3**: Customer data isolated (no cross-customer access)
- **NFR4.4**: API keys stored securely (Supabase secrets)
- **NFR4.5**: No sensitive customer data logged

#### NFR5: Maintainability
- **NFR5.1**: Use standard Supabase features only (no third-party extensions)
- **NFR5.2**: CLI tool is simple Node.js script (easy to debug)
- **NFR5.3**: Edge Function code is < 200 lines
- **NFR5.4**: Clear error messages and logging

#### NFR6: Cost
- **NFR6.1**: Target: < $100/month for 3 customers
  - Supabase: $0 (free tier)
  - Firecrawl: ~$15 (3 sites × $5/site, on-demand)
  - OpenAI Embeddings: ~$5/month (ingestion + queries)
  - Total: ~$20/month
- **NFR6.2**: No ongoing costs beyond OpenAI API usage

---

## Success Criteria

### Launch Success (3 Customers)
1. **✅ 3 customer websites ingested successfully**
   - All pages scraped without errors
   - Vectors stored in Supabase
   - Queryable via Edge Function

2. **✅ Vapi voice agents can query knowledge base**
   - Configured in Vapi dashboard
   - Returns relevant results for customer questions
   - Results appear in LLM context

3. **✅ Query performance meets targets**
   - 95% of queries complete in < 500ms
   - No failed queries due to system errors
   - Relevance: 80% of queries return useful results (manual validation)

4. **✅ Admin can ingest new sites in < 30 minutes**
   - From receiving customer URL to queryable in Vapi
   - Including setup, running CLI, verifying results

### Quality Metrics
- **Accuracy**: LLM answers match documentation (manual review of 20 queries)
- **Coverage**: System can answer 70% of product-specific questions
- **Latency**: Average query time < 300ms (P95 < 500ms)
- **Reliability**: 99% uptime for Edge Function

### User Satisfaction
- Customers report improved demo quality (qualitative feedback)
- Reduced "I don't know" responses from voice agents
- Sales team confidence in AI agent demos increases

---

## Constraints & Assumptions

### Technical Constraints
- Must use Supabase's standard features (no ParadeDB, no custom extensions)
- Laptop-based ingestion only (no Railway deployment for CLI)
- Public websites only (no authentication support in v1)
- English-language content only (no multi-language support)

### Resource Constraints
- Single admin managing all ingestions
- Budget: < $100/month operational costs
- Timeline: 1-2 weeks for MVP implementation

### Assumptions
- **AS1**: Customers have publicly accessible documentation websites
- **AS2**: 50 pages per customer is sufficient coverage
- **AS3**: Semantic search alone (no keyword search) is adequate
- **AS4**: Supabase free tier capacity is sufficient for 3 customers
- **AS5**: Vapi's custom knowledge base integration works as documented
- **AS6**: Customers trust us to scrape and store their public documentation
- **AS7**: On-demand ingestion is acceptable (no auto-refresh needed)

### External Dependencies
- **Firecrawl API** availability and pricing stability
- **OpenAI API** uptime and embedding model availability
- **Supabase** infrastructure reliability
- **Vapi** custom knowledge base feature support

---

## Out of Scope (v1)

### Explicitly Not Building
1. **Customer Self-Service Ingestion**
   - No UI for customers to add their own websites
   - Admin-managed only

2. **Scheduled Re-Crawling**
   - No automatic refresh of stale content
   - Manual re-ingestion on-demand only

3. **Authentication Support**
   - No password-protected sites
   - No login flows or credential management

4. **Multi-Language Support**
   - English-only content processing
   - No translation or language detection

5. **Advanced Search Features**
   - No filtering by date, category, etc. (in v1)
   - No advanced reranking models (in v1)
   - No query expansion (in v1)

6. **Customer-Facing Analytics**
   - No dashboard showing what's been queried
   - Admin-only monitoring

7. **Data Residency/Compliance**
   - No EU-specific data residency
   - No GDPR compliance features beyond basic data isolation

8. **LiveKit/Tavus Integration (v1)**
   - Focus on Vapi first
   - Other platforms in future iterations

9. **Content Moderation**
   - No filtering of inappropriate content
   - Assumes customer sites are safe

10. **Version Control**
    - No tracking of document changes over time
    - Latest scrape overwrites previous

### Future Considerations (Post-v1)
- Customer self-service UI
- Scheduled re-crawls
- LiveKit and Tavus integrations
- Authentication support for private docs
- Multi-language content
- Advanced analytics and usage dashboards
- Content versioning and change detection

---

## Dependencies

### External Service Dependencies
1. **Firecrawl API** (Critical Path)
   - Used for web scraping
   - Fallback: Could use Playwright directly (more complex)
   - Risk: Service outage blocks new ingestions

2. **OpenAI Embeddings API** (Critical Path)
   - Used for generating embeddings
   - Fallback: None for v1 (could switch to other embedding models later)
   - Risk: Outage blocks ingestion and queries

3. **Supabase** (Critical Path)
   - pgvector for vector storage
   - Storage for raw content
   - Edge Functions for query API
   - Fallback: None (core infrastructure)
   - Risk: Outage blocks all functionality

4. **Vapi Platform** (Integration Dependency)
   - Custom knowledge base feature
   - Risk: Feature changes could break integration

### Internal Dependencies
1. **Existing Supabase Setup**
   - Database already configured
   - Service role key available
   - Storage bucket creation access

2. **Admin Laptop Environment**
   - Node.js v22+ installed
   - pnpm available
   - Environment variables configured

3. **Vapi Customer Accounts**
   - Admin access to configure assistants
   - Ability to set metadata on calls

### Development Dependencies
- Nx monorepo tooling (for CLI app)
- TypeScript compilation
- Supabase CLI (for Edge Function deployment)

---

## Technical Architecture

### System Components

```
┌─────────────────────────────────────────────────────────┐
│                  Admin Laptop (One-Time)                │
│                                                         │
│  ┌───────────────────────────────────────────────┐    │
│  │  Ingestion CLI (knowledge-cli)                │    │
│  │  - Firecrawl API call                         │    │
│  │  - Chunk content                              │    │
│  │  - Generate embeddings (OpenAI)               │    │
│  │  - Upload to Supabase (Storage + pgvector)    │    │
│  └───────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                    Supabase (Cloud)                     │
│                                                         │
│  ┌─────────────────┐      ┌──────────────────────┐    │
│  │   PostgreSQL    │      │    Storage Bucket    │    │
│  │   + pgvector    │      │   (customer-docs/)   │    │
│  │                 │      │                      │    │
│  │  Tables:        │      │  Files:              │    │
│  │  - knowledge_   │      │  - raw_pages.json    │    │
│  │    chunks       │      │  - page_*.md         │    │
│  │  - customer_    │      │  - metadata.json     │    │
│  │    knowledge_   │      │                      │    │
│  │    base         │      │  Per customer/KB     │    │
│  └─────────────────┘      └──────────────────────┘    │
│           ↑                                            │
│  ┌────────┴────────────────────────────────────┐      │
│  │   Edge Function: /knowledge-query           │      │
│  │   - Validate API key                        │      │
│  │   - Generate query embedding (OpenAI)       │      │
│  │   - Hybrid search (RPC):                    │      │
│  │     * Semantic: pgvector cosine similarity  │      │
│  │     * Keyword: full-text search (tsvector)  │      │
│  │     * Fusion: Reciprocal Rank Fusion (RRF) │      │
│  │   - Return combined results                 │      │
│  │  └─────────────────────────────────────────────┘      │
└─────────────────────────────────────────────────────────┘
                            ↑
┌─────────────────────────────────────────────────────────┐
│                    Vapi Platform                        │
│                                                         │
│  Assistant Configuration:                              │
│  - knowledgeBase.provider: "custom"                    │
│  - knowledgeBase.url: Edge Function URL                │
│  - Pass customer_id from call metadata                 │
│                                                         │
│  LLM receives retrieved content in context             │
└─────────────────────────────────────────────────────────┘
```

### Data Model

**PostgreSQL Tables:**

```sql
customer_knowledge_base (
  id UUID PRIMARY KEY,
  customer_id TEXT NOT NULL,        -- Isolation key
  name TEXT NOT NULL,                -- e.g., "Acme Corp Docs"
  source_url TEXT NOT NULL,          -- Original website
  status TEXT,                       -- 'ready' | 'processing'
  pages_count INT,
  chunks_count INT,
  created_at TIMESTAMPTZ
)

knowledge_chunks (
  id UUID PRIMARY KEY,
  kb_id UUID REFERENCES customer_knowledge_base(id),
  customer_id TEXT NOT NULL,        -- Denormalized for fast filtering
  chunk_text TEXT NOT NULL,
  chunk_index INT,
  embedding VECTOR(1536) NOT NULL,  -- pgvector for semantic search
  text_search TSVECTOR,              -- Full-text search for keyword matching
  metadata JSONB,                   -- {source_url, title}
  created_at TIMESTAMPTZ
)
```

**Supabase Storage Structure:**
```
customer-docs/
├── cust_acme/
│   ├── kb_550e8400/
│   │   ├── raw_pages.json      (Full Firecrawl response)
│   │   ├── page_000.md         (Individual pages)
│   │   ├── page_001.md
│   │   └── metadata.json       (Scrape metadata)
│   └── kb_6ba7b810/
│       └── ...
└── cust_widgets/
    └── kb_xyz/
        └── ...
```

### API Specification

**Edge Function Endpoint:**
```
POST /functions/v1/knowledge-query
Headers:
  x-api-key: <secret>
  Content-Type: application/json

Body:
{
  "messages": [
    {"role": "user", "content": "How do I reset my password?"}
  ],
  "customer_id": "cust_acme"
}

Response:
{
  "results": [
    {
      "content": "To reset your password, go to...",
      "score": 0.89,
      "metadata": {
        "source_url": "https://docs.acme.com/auth/reset",
        "title": "Password Reset"
      }
    }
  ]
}
```

---

## Implementation Phases

### Phase 1: Infrastructure Setup (Day 1)
**Duration**: 4 hours

**Tasks:**
1. Run Supabase migration (create tables, indexes, RPC function)
2. Create `customer-docs` storage bucket
3. Generate and set API key secret
4. Verify pgvector extension enabled

**Deliverables:**
- Database schema ready
- Storage bucket created
- Secrets configured

**Success Criteria:**
- Can manually insert/query test vectors
- Storage bucket accessible via service role

---

### Phase 2: Ingestion CLI (Days 2-3)
**Duration**: 12 hours

**Tasks:**
1. Create `knowledge-cli` Nx app
2. Install dependencies (Firecrawl, OpenAI, Langchain, Supabase)
3. Implement scraping logic
4. Implement chunking and embedding
5. Implement Supabase upload (Storage + pgvector)
6. Add error handling and logging
7. Test with sample website

**Deliverables:**
- Working CLI tool: `pnpm nx run knowledge-cli:ingest`
- Successfully ingest test website
- Vectors visible in Supabase dashboard

**Success Criteria:**
- Can ingest 50-page site in < 5 minutes
- Raw content stored in Storage
- Vectors queryable in database

---

### Phase 3: Query API (Days 3-4)
**Duration**: 8 hours

**Tasks:**
1. Initialize Supabase Edge Function
2. Implement API key validation
3. Implement embedding generation
4. Implement pgvector search
5. Format results for Vapi
6. Deploy to Supabase
7. Test with curl/Postman

**Deliverables:**
- Deployed Edge Function
- API endpoint URL
- Test queries return results

**Success Criteria:**
- API key authentication works
- Returns relevant results for test queries
- Response time < 500ms

---

### Phase 4: Vapi Integration (Day 5)
**Duration**: 4 hours

**Tasks:**
1. Configure Vapi assistant with custom knowledge base
2. Set Edge Function URL and API key
3. Configure customer_id metadata passing
4. Test voice call with ingested content
5. Verify LLM uses retrieved context

**Deliverables:**
- Vapi assistant configured
- Test call demonstrates RAG working

**Success Criteria:**
- Voice agent answers questions using ingested docs
- Responses are accurate to source material

---

### Phase 5: Launch with 3 Customers (Days 6-7)
**Duration**: 8 hours

**Tasks:**
1. Ingest customer #1 website
2. Configure Vapi for customer #1
3. Test and validate
4. Repeat for customers #2 and #3
5. Document ingestion process
6. Create runbook for troubleshooting

**Deliverables:**
- 3 customer knowledge bases live
- 3 Vapi assistants using RAG
- Admin documentation

**Success Criteria:**
- All 3 customers can query their docs
- Voice calls demonstrate improved accuracy
- Admin can re-ingest independently

---

## Risk Assessment

### High Risk

**R1: Firecrawl API Instability**
- **Impact**: Cannot ingest new customers
- **Likelihood**: Low
- **Mitigation**: Have Playwright fallback code ready (not implemented in v1)
- **Contingency**: Manual scraping or customer provides markdown files

**R2: OpenAI API Outage**
- **Impact**: Cannot ingest or query
- **Likelihood**: Low
- **Mitigation**: Retry logic, fallback to cached embeddings
- **Contingency**: Wait for service restoration (acceptable for v1)

**R3: Poor Search Relevance**
- **Impact**: Users get wrong answers or no results
- **Likelihood**: Medium
- **Mitigation**: Tune similarity threshold, chunk size, add keyword search in v2
- **Contingency**: Manual content curation, prompt engineering

### Medium Risk

**R4: Vapi Custom KB Feature Changes**
- **Impact**: Integration breaks
- **Likelihood**: Low
- **Mitigation**: Monitor Vapi changelog, maintain good relationship with Vapi team
- **Contingency**: Implement direct LLM context injection

**R5: Supabase Free Tier Limits Exceeded**
- **Impact**: Cannot scale beyond 3 customers
- **Likelihood**: Low (well within limits)
- **Mitigation**: Monitor usage, plan upgrade path
- **Contingency**: Upgrade to Supabase Pro ($25/month)

**R6: Chunk Size/Overlap Not Optimal**
- **Impact**: Relevant info split across chunks, poor results
- **Likelihood**: Medium
- **Mitigation**: Test with different settings, allow CLI parameter override
- **Contingency**: Re-ingest with new settings

### Low Risk

**R7: Admin Laptop Environment Issues**
- **Impact**: Cannot run ingestion
- **Likelihood**: Low
- **Mitigation**: Document setup clearly, test on multiple machines
- **Contingency**: Use different laptop or VM

---

## Open Questions

1. **Q1**: Should we cache query embeddings to reduce OpenAI costs?
   - **Decision Needed By**: Phase 3
   - **Impact**: Cost optimization

2. **Q2**: What's the policy for re-ingesting when customer updates docs?
   - **Decision Needed By**: Phase 5
   - **Impact**: Operational process

3. **Q3**: Should we expose similarity scores to LLM or hide them?
   - **Decision Needed By**: Phase 4
   - **Impact**: LLM prompt engineering

4. **Q4**: Do we need a way to delete/archive old knowledge bases?
   - **Decision Needed By**: Post-launch
   - **Impact**: Data cleanup

---

## Appendix

### Glossary
- **RAG**: Retrieval-Augmented Generation - LLM technique that retrieves relevant context before generating responses
- **pgvector**: PostgreSQL extension for storing and querying vector embeddings
- **Embedding**: Numerical representation of text in high-dimensional space (1536 dimensions for OpenAI)
- **Chunk**: Segment of text (typically 1000 characters) for processing
- **Cosine Similarity**: Metric for measuring vector similarity (0-1 scale)

### References
- [Supabase pgvector Documentation](https://supabase.com/docs/guides/ai/vector-columns)
- [Vapi Custom Knowledge Base](https://docs.vapi.ai/knowledge-base/custom-knowledge-base)
- [Firecrawl API Documentation](https://docs.firecrawl.dev)
- [OpenAI Embeddings API](https://platform.openai.com/docs/guides/embeddings)

### Example Customer Use Cases

**Customer 1: SaaS Product Documentation**
- 80 pages of product docs
- Common queries: "How do I...", "What is...", "Where can I find..."
- Expected accuracy: 85%+

**Customer 2: E-commerce Store Policies**
- 30 pages (returns, shipping, FAQ)
- Common queries: "What's your return policy?", "Do you ship to..."
- Expected accuracy: 90%+

**Customer 3: Financial Services Compliance**
- 120 pages (regulations, procedures)
- Common queries: "What's the compliance process for...", "Are there restrictions on..."
- Expected accuracy: 80%+ (complex domain)

---

## Revision History

| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2025-10-22 | PM System | Initial PRD creation |

