# Agentic Structure
<!-- Source: agents/, services/, index.js, utils/modelHelper.js -->
<!-- last updated: 2026-03-25 -->

## 7-Layer Overview

| Layer | Name | Directory | Purpose |
|-------|------|-----------|---------|
| 7 | Frontend / UI | `frontend/` | Next.js dashboard, 60+ React components |
| 6 | API Gateway | `index.js` | 120+ REST endpoints, auth, middleware |
| 5 | Orchestration | `agents/*Orchestrator.js` | Multi-agent coordinators |
| 4 | Agents | `agents/` | 20+ specialized AI agents ← **main agent list** |
| 3 | Services | `services/` | LLM clients, schedulers, enrichment |
| 2 | Knowledge | `knowledge/` | RAG, vector store, connectors |
| 1 | Data | `db.js` | PostgreSQL + pgvector, 55+ tables |

> When building a new feature, identify which layers it touches and update each accordingly.

---

## Model Routing Strategy

| Model | Use Case | Input / Output Cost |
|-------|----------|-------------------|
| **DeepSeek Reasoner** | Primary — most agent tasks, reasoning, strategy | $0.14 / $0.28 per 1M tokens |
| **Claude Haiku** | Fallback — classification, extraction, simple tasks | $0.25 / $1.25 per 1M tokens |
| **Perplexity Sonar** | Research — web search, live information | $3.00 / $15.00 per 1M tokens |
| **Claude Sonnet** | Vision / complex only — image analysis, heavy reasoning | $3.00 / $15.00 per 1M tokens |

Model selection logic: `utils/modelHelper.js`

---

## Agent Inventory

### Strategic & Analysis Agents (`agents/`)

| Agent File | Class/Export | Purpose | Primary Model |
|-----------|-------------|---------|--------------|
| `brandStrategyAgent.js` | BrandStrategyAgent | Brand strategy development | DeepSeek Reasoner |
| `creativeAgent.js` | CreativeAgent | Creative content generation | DeepSeek Reasoner |
| `seoAgent.js` | SeoAgent | SEO strategy & keyword optimization | DeepSeek Reasoner |
| `socialAgent.js` | SocialAgent | Social media strategy | DeepSeek Reasoner |
| `researchAgent.js` | ResearchAgent | Market research & competitive intelligence | Perplexity Sonar |
| `customerInsightAgent.js` | CustomerInsightAgent | Customer behavior & persona analysis | DeepSeek Reasoner |
| `competitorAgent.js` | CompetitorAgent | Competitor analysis | Perplexity Sonar |

### Sales & Growth Agents

| Agent File | Class/Export | Purpose | Primary Model |
|-----------|-------------|---------|--------------|
| `leadScoringAgent.js` | LeadScoringAgent | Score inbound leads | Claude Haiku |
| `leadIntelligenceAgent.js` | LeadIntelligenceAgent | Enrich lead data | Perplexity Sonar |
| `demoCloserAgent.js` | DemoCloserAgent | Sales demo assistant | DeepSeek Reasoner |
| `emailNurtureAgent.js` | EmailNurtureAgent | Email nurture sequences | DeepSeek Reasoner |
| `conversionOptimizerAgent.js` | ConversionOptimizerAgent | CRO optimization | DeepSeek Reasoner |
| `retargetingAgent.js` | RetargetingAgent | Retargeting campaign builder | DeepSeek Reasoner |

### Monitoring & Analytics Agents

| Agent File | Class/Export | Purpose | Primary Model |
|-----------|-------------|---------|--------------|
| `marketSentinelAgent.js` | MarketSentinelAgent | Market trend monitoring | Perplexity Sonar |
| `campaignAnalyticsAgent.js` | CampaignAnalyticsAgent | Campaign performance analysis | DeepSeek Reasoner |

### Orchestrators (Multi-Agent Coordinators)

| Agent File | Class/Export | Purpose | Coordinates |
|-----------|-------------|---------|------------|
| `csoOrchestrator.js` | CSOOrchestrator | Customer Success Orchestration | customerInsight, email, social, competitor |
| `smeGrowthOrchestrator.js` | SMEGrowthOrchestrator | SME end-to-end growth pipeline | leadScoring, leadIntel, emailNurture, demoCloser, analytics |

### Ziwei Astrology Agents (`agents/` — TypeScript)

| Agent File | Class/Export | Purpose | Primary Model |
|-----------|-------------|---------|--------------|
| `ziweiChartAgent.ts` | ZiweiChartAgent | Chart generation & palace assignment | DeepSeek Reasoner |
| `ziweiInterpretationAgent.ts` | ZiweiInterpretationAgent | Chart interpretation & insights | DeepSeek Reasoner |
| `ziweiEvaluationAgent.ts` | ZiweiEvaluationAgent | Rule evaluation & scoring | Claude Haiku |

---

## Services Inventory (`services/`)

### Core LLM Services

| Service File | Export | Purpose |
|-------------|--------|---------|
| `deepseekService.js` | deepseekService | DeepSeek API client (primary LLM) |
| `perplexityService.js` | perplexityService | Perplexity web search API client |
| `minimaxService.js` | minimaxService | MiniMax API client (image/video gen) |
| `lib/llm.js` | llm | Generic LLM utility (model switching) |
| `utils/modelHelper.js` | modelHelper | Model selection routing logic |

### Data & RAG Services

| Service File | Export | Purpose |
|-------------|--------|---------|
| `rag-service.js` | ragService | Retrieval-Augmented Generation |
| `services/encryption.js` | encrypt/decrypt | PII field encryption/decryption |
| `complianceChecker.js` | complianceChecker | Regulatory compliance analysis |

### Scheduling Services

| Service File | Export | Purpose |
|-------------|--------|---------|
| `services/scheduler.js` | scheduler | Background job runner (node-cron) |
| `services/schedule-registry.js` | scheduleRegistry | Cron job definitions & registry |

**Scheduled Jobs** (from `schedule-registry.js`):
- Marketing strategy: 1 run/day (NOT 5 — see Known Mistakes in CLAUDE.md)
- Market sentinel: configurable
- Tender digest: daily

### Research & Enrichment Services

| Service File | Export | Purpose |
|-------------|--------|---------|
| `contactResearchService.js` | contactResearchService | Contact data enrichment |
| `linkedinProfileFetcher.js` | linkedinProfileFetcher | LinkedIn profile scraping |
| `brandVoiceAnalyzer.js` | brandVoiceAnalyzer | Brand voice & tone analysis |
| `tender-intel-service.js` | tenderIntelService | Tender opportunity processing |

### Real-time Services

| Service File | Export | Purpose |
|-------------|--------|---------|
| `websocket-server.js` | wsServer | WebSocket for real-time updates |

### Ziwei Calculation Services

| Service File | Purpose | Language |
|-------------|---------|---------|
| `ziwei-chart-engine.js` | Main chart calculation & palace assignment | JS |
| `ziwei-chart-calculator.py` | Precise astronomical calculations | Python |
| `ziwei-interpretation-engine.js` | Interprets chart patterns into insights | JS |
| `ziwei-rule-evaluator.js` | Applies interpretation rules to charts | JS |
| `ziwei-compatibility-analyzer.js` | Relationship compatibility scoring | JS |
| `ziwei-conversation-manager.js` | Maintains chart discussion context | JS |
| `ziwei-llm-enhancer.js` | LLM-augmented interpretation enhancement | JS |

---

## Knowledge Management Layer (`knowledge/`)

```
KnowledgeManager (knowledge/index.ts)
├── Connectors (knowledge/connectors/)
│   ├── NotionConnector    → Notion workspace sync
│   ├── WebCrawler         → Web content crawling
│   ├── PDFParser          → PDF document extraction
│   └── EmailParser        → Gmail integration
├── Embeddings (knowledge/embeddings/)
│   ├── EmbeddingService   → Text → vector (OpenAI/Anthropic/local)
│   ├── VectorStore        → pgvector read/write
│   └── SemanticSearch     → High-level search API
└── Schema (knowledge/schema/)
    ├── knowledge-types.ts → Core interfaces
    ├── ziwei-types.ts     → Ziwei type definitions
    └── ziwei-rules.ts     → Rule type definitions
```

---

## Agent API Endpoints (in `index.js`)

```
POST /agents/creative      → creativeAgent
POST /agents/seo           → seoAgent
POST /agents/social        → socialAgent
POST /agents/research      → researchAgent
POST /agents/customer      → customerInsightAgent
POST /agents/competitor    → competitorAgent
POST /agents/strategy      → brandStrategyAgent
POST /agents/cso           → csoOrchestrator
POST /agents/sentinel      → marketSentinelAgent
GET  /agents               → list all available agents
```

---

## Agentic Workflow Patterns

### Standard Agent Call Pattern
```js
// 1. Validate input
// 2. Fetch brand context from DB
// 3. Build system prompt with brand context
// 4. Call LLM via deepseekService or lib/llm
// 5. Parse structured JSON response
// 6. Save result to DB
// 7. Return to client
```

### Orchestrator Pattern (multi-agent)
```js
// 1. Receive high-level goal
// 2. Break into sub-tasks
// 3. Run sub-agents in sequence or parallel
// 4. Merge and synthesize results
// 5. Return unified report
```

### RAG-Augmented Pattern
```js
// 1. Receive query
// 2. Embed query via EmbeddingService
// 3. Semantic search in VectorStore (pgvector)
// 4. Inject retrieved docs into LLM context
// 5. Generate grounded response
```

### Workflow Chat Pattern (streaming)
```
POST /api/workflow-chat
POST /api/agent-chat
→ Uses SSE / streaming response
→ Maintains conversation state in DB
```

---

## Use-Case Verticals (23 solutions)

| Use Case | Key Backend | Key Frontend | Agent Used |
|----------|------------|-------------|-----------|
| `recruitai` | `/api/recruitai/*` | `frontend/app/use-cases/` | leadScoringAgent |
| `tedx-xinyi` | `/api/tedx-xinyi/*` | `frontend/public/tedx-xinyi/` | creativeAgent, minimaxService |
| `hk-sg-tender-intelligence` | `/api/tender-intel/*` | Dashboard tab | tenderIntelService |
| `print-finance` | `/api/print-finance/*` | `frontend/app/use-cases/print-finance/` | — (data only) |
| `ziwei` | `/api/ziwei/*` | `frontend/app/use-cases/ziwei/` | ZiweiChartAgent |
| `client-crm-kb` | `/api/crm/*`, `/api/brands/*` | `frontend/app/use-cases/crm/` | researchAgent |
| `ai-media-generation` | `/api/admin/media-library/*` | `frontend/components/MediaGenerationWorkflow.tsx` | minimaxService |
| `adaptive-learning` | Embedded in index.js | `frontend/app/adaptive-learning/` | — |
| `ads-performance-multitenant` | Embedded in index.js | `frontend/app/ads-dashboard/` | campaignAnalyticsAgent |
| `eventflow` | Embedded in index.js | `frontend/app/eventflow/` | — |
