Building Multi-AI-Feature SaaS Products: AI Feature Routers, Domain-Driven AI, Deterministic Business Truth, Structured Outputs & Unit Economics.
Throughout previous lessons, we mastered the core technical building blocks: LLMs, prompt registries, RAG pipelines, autonomous agents, AI Gateways, and developer runtimes. Now, our architectural perspective shifts from infrastructure to business product architecture: How do we combine these technologies into a real-world, multi-feature enterprise SaaS?
Simply bolting a generic floating chatbot onto an existing web application does not create an AI product. In a modern SaaS (such as an ERP, CRM, or commerce suite), AI must be woven seamlessly into everyday business workflows:
The Architectural Imperative: If each product team constructs an isolated AI stack for their specific module, the platform collapses under redundant API bills, inconsistent security postures, and divergent audit trails. We must build one shared AI platform that exposes dozens of domain-specific features through a centralized control plane.
Writing response = openai.chat.completions.create(...) produces a raw inference response; it does not produce a product feature. A production-ready AI feature encompasses a 16-layer operational stack:
In enterprise software, the foundation model represents less than 15% of the total engineering complexity. The remaining 85% is software architecture, data isolation, user experience, and financial governance.
Software companies approach artificial intelligence across three evolutionary tiers:
A conventional CRUD SaaS that adds auxiliary AI utilities. The core product functions normally if the AI subsystem is disabled:
The core value proposition revolves around machine intelligence, though wrapped in standard web controls:
The fundamental architecture is designed around autonomous goals, natural language interaction, and dynamic execution loops:
A comprehensive SaaS platform groups AI capabilities into eight distinct operational categories:
Contextual chat assistants, support copilots, and interactive user onboarding.
Hybrid vector + BM25 search across internal policies, invoices, tickets, and documentation.
E-commerce titles, SEO metadata, localized emails, social campaigns, and invoices.
Transforming unstructured PDFs, receipts, and emails into strictly typed JSON schemas.
Ticket urgency tagging, spam filtering, sentiment analysis, and churn risk scoring.
Hybrid rule-based + embedding nearest-neighbor product & workflow suggestions.
Natural language queries translated to read-only ClickHouse SQL with synthesized business insights.
Event-triggered background workflows performing multi-step tasks with human-in-the-loop gates.
In modern architectures, client applications never query LLM providers or specific models directly. Instead, all traffic passes through an AI Feature Router:
{
"feature_key": "ai.commerce.product_description",
"name": "E-Commerce Product Description Generator",
"execution_mode": "SYNCHRONOUS_STREAM",
"target_workflow": "workflows/catalog_enrichment:v2",
"required_permissions": ["products.read", "products.write"],
"quota_tier": "STANDARD_CONTENT",
"monthly_limit": 500,
"requires_approval": false,
"cost_limit_usd": 0.015
}
When a user clicks "Generate Description", the frontend submits a generic request to POST /v1/ai/features/product_description/run. The Feature Router verifies permissions, validates the tenant's monthly quota balance, loads the versioned workflow, and routes inference through the AI Gateway.
Selecting the correct execution mode is critical for application reliability:
| Feature Type | Execution Mode | Target Latency | Client UX Pattern |
|---|---|---|---|
| Chat & Support Copilot | Synchronous Streaming | < 3.0 seconds | SSE / Token-by-token stream |
| Product Description Generation | Synchronous JSON | < 2.5 seconds | Inline spinner → Populated textarea |
| 500-Invoice Batch OCR | Asynchronous Job (202) | Minutes / Hours | Progress bar → Push notification |
| Order Churn Follow-up Agent | Event-Driven Workflow | Decoupled Queue | Manager approval modal / Email alert |
A superior AI feature feels like an empowering tool, not an impenetrable black box. Enterprise AI UX must adhere to core interaction design standards:
Display token streams immediately. Never force users to stare at a static spinner for 10 seconds.
Every claim derived from RAG must render a clickable citation pill linking directly to the source document.
Always provide [Copy], [Regenerate], [Edit Inline], and [Thumbs Up/Down] feedback buttons.
The most dangerous architectural defect in modern AI engineering is treating a probabilistic language model as the authoritative source of business truth.
The Cardinal Rule: Never ask an LLM "How much inventory is left?". Instead, query the deterministic Inventory Service (returning {"stock": 142}) and instruct the model: "Explain to the warehouse manager that 142 units remain in stock."
Downstream business logic cannot parse unstructured conversational text. AI features producing operational payloads must adhere to strict JSON Schema contracts:
import { z } from "zod";
export const InvoiceSchema = z.object({
invoiceNumber: z.string().min(3),
supplierName: z.string(),
totalAmount: z.number().positive(),
currency: z.enum(["USD", "BDT", "EUR"]),
lineItemsCount: z.number().int()
});
export type Invoice = z.infer<typeof InvoiceSchema>;
from pydantic import BaseModel, Field
class InvoiceExtraction(BaseModel):
invoice_number: str = Field(..., min_length=3)
supplier_name: str
total_amount: float = Field(..., gt=0)
currency: str
line_items_count: int
# Validated on completion
invoice = InvoiceExtraction.model_validate_json(raw)
In a B2B SaaS, tenant isolation is a non-negotiable security boundary. Merely prompting an LLM "Do not reveal Tenant B's data" is catastrophically vulnerable to jailbreaking.
qdrant_client.search(collection="kb", query_vector=vec, query_filter=Filter(must=[FieldCondition(key="tenant_id", match=MatchValue(value=42))]))
Enabling natural language analytics (e.g. "Why did gross revenue decline in Q3?") requires strict query isolation:
When deploying autonomous agents within specific modules (e.g., an Inventory Optimization Agent), the agent's capabilities must be rigorously bounded by granular role-based permissions:
inventory.get_stock_levelssuppliers.query_lead_timespurchase_orders.draft_orderinventory.adjust_counts (Requires Supervisor)suppliers.delete_contract (Blocked)payments.execute_transfer (Requires Dual-Key)Pricing AI features requires understanding Unit Economics. An enterprise SaaS cannot bill purely on raw input/output tokens because business customers think in feature outcomes:
| Subscription Tier | Monthly AI Entitlement | Feature Quotas | Margin Target |
|---|---|---|---|
| Starter ($29/mo) | 50,000 Tokens | 100 Product Descriptions / 0 Agents | > 85% Gross Margin |
| Professional ($99/mo) | 300,000 Tokens | 1,000 Descriptions / 50 AI Reports | > 80% Gross Margin |
| Enterprise ($499/mo) | 2,000,000 Tokens | Unlimited Summaries / Full Agent Suite | > 75% Gross Margin |
Measuring HTTP 200 uptime is insufficient. An AI feature's real-world efficacy is measured through behavioral telemetry:
Below is the practical implementation of the central AI Feature Router and its corresponding frontend hook:
namespace App\Services\AI;
class AiFeatureRouter
{
public function dispatch(string $featureKey, array $payload, User $user)
{
$feature = AiFeature::where('key', $featureKey)->where('enabled', true)->firstOrFail();
// 1. Authorize Tenant Permissions
abort_unless($user->can($feature->required_permission), 403, 'Unauthorized AI capability');
// 2. Enforce Monthly Quotas
$quota = app(QuotaManager::class)->checkTenant($user->tenant_id, $feature->quota_tier);
abort_unless($quota->hasBalance(), 429, 'Monthly AI feature quota exhausted');
// 3. Dispatch to Unified Workflow Runner
return app(WorkflowRunner::class)->execute($feature->workflow, $payload, $user->tenant_id);
}
}
Test feature routing, deterministic domain truth verification, schema validation, and unit economics calculations in the interactive suite below:
Select an incoming feature request to test permission enforcement, quota deduction, and workflow routing:
Your progress is automatically saved to browser storage. Complete all platform criteria for production-ready AI product engineering.
Context: A product manager proposes asking an LLM to calculate customized discount pricing based on customer loyalty tiers.
Verdict: Strictly reject LLM arithmetic. Mathematical calculations in e-commerce are deterministic business logic. Execute the loyalty formula in the Pricing Service and pass the resulting dollar amount to the LLM solely for conversational rendering.
Context: The Marketing team attempts to integrate a separate OpenAI SDK directly into their controller without using the company's AI Gateway.
Verdict: Enforce architectural convergence. Direct provider integrations bypass tenant quota limits, PII redaction, and centralized OpenTelemetry logging. Mandate that all features register in the central Feature Registry and route through the AI Feature Router.
Context: An engineering team saves raw unstructured LLM text directly to the customer invoice notes field.
Verdict: Mandate structured output enforcement. Require all transactional completions to pass strict Zod/Pydantic validation. If the model generates malformed JSON, automatically trigger an internal repair pass before saving to the database.
Context: A SaaS considers charging customers per 1,000 raw input tokens for all AI capabilities.
Verdict: Adopt outcome-based feature quotas. B2B software customers cannot predict token counts. Package AI capabilities into tiered feature entitlements (e.g. 500 Product Descriptions/mo on Pro) with clear unit economics ensuring healthy > 80% gross margins.