Delivered remotely for a business based in London, United Kingdom. Names withheld by agreement.
Project Overview
High-growth software teams face a chronic support imbalance: routine configuration questions and changelog lookups flood human queues, yet deflecting users with brittle decision-tree bots damages customer trust. Standard LLM wrappers introduce a different hazard—confident fabrication of nonexistent settings, outdated SLA clauses, or invalid troubleshooting commands when documentation is ambiguous.
In collaboration with product stakeholders in London, United Kingdom, we designed and shipped an omnichannel AI customer support platform using Python, LangChain, Next.js, PostgreSQL, pgvector, and Redis. The platform delivers cited, documentation-grounded answers inside an embeddable web widget while giving support supervisors live visibility and instant, context-rich human takeover whenever automated resolution reaches its boundary.
Escalation & Knowledge Drift
Replacing scripted decision trees with a production support assistant uncovered several hard engineering constraints:
- Exact-match blind spots in pure vector search: Customers paste verbatim stack traces, webhook error codes, and plan SKUs that semantic embeddings frequently dilute unless paired with lexical matching.
- Unbounded multi-turn drift: Long troubleshooting chats accumulate conflicting guesses if the system fails to anchor each turn against verified knowledge-base passages.
- Abrupt agent handoffs: Transferring a conversation to a human specialist without a structured summary forces customers to repeat diagnostics they already provided.
- Stale knowledge indices: Product documentation shifts weekly; full-corpus re-indexing wastes compute while manual syncing leaves deprecated steps live.
Architectural Strategy
We built the conversational core as a deterministic retrieval-and-routing pipeline orchestrated with Python and LangChain Expression Language (LCEL), decoupled cleanly from the Next.js presentation and agent-triage layer. Every incoming message passes first through a lightweight policy and intent router that detects sensitive categories—account cancellations, security incidents, or explicit human requests—before invoking generative retrieval.
For eligible queries, LangChain executes hybrid retrieval over tenant-isolated PostgreSQL and pgvector tables, applies cross-encoder reranking, and requires inline source references mapped to live knowledge URLs. When confidence scores fall short or a user rejects a suggested fix, Redis Streams transition the thread atomically into human-owned status so bot generation never collides with a live agent typing in the Next.js console.
Core Capabilities
- Cited Hybrid RAG Answers: Responses render clickable documentation footnotes alongside step-by-step troubleshooting instructions grounded exclusively in verified tenant content.
- Deterministic Escalation Routing: Keyword policies, confidence floors, and repeat-clarification counters route complex or sensitive issues straight to specialist queues.
- Structured Agent Handoff Briefs: Escalated tickets arrive in the Next.js triage inbox pre-populated with detected product area, attempted steps, and user account context.
- Incremental Knowledge Sync: Hash-based ingestion workers monitor documentation feeds and re-embed only changed sections without interrupting active chat traffic.
- Supervisor Analytics & Transcript Audits: Support leads inspect unanswered query clusters and low-confidence gaps to prioritize documentation improvements.
Technical Architecture
Customer widgets communicate with Next.js API routes that authenticate ephemeral visitor sessions and proxy streaming turns to the Python LangChain service, while Redis coordinates live state transitions between automated and human responders.
Flow: Next.js Chat Widget → Session Gateway (Auth & Tenant Context) → Python Policy Router (Escalation Check) → LangChain Hybrid Retriever (PostgreSQL FTS + pgvector) → Citation-Constrained Generator → Redis Live Takeover Bus / Next.js Agent Console
Separating the Next.js web application from the Python retrieval cluster allowed independent scaling of CPU/network-heavy embedding and reranking workloads without slowing down agent dashboard interactions. PostgreSQL serves as the single source of truth for conversation ledgers, citation mappings, and vector storage, avoiding synchronization lag between separate relational and vector databases.
Technology Stack
| Category | Technology detail |
|---|---|
| Retrieval & Chain Engine | Python with LangChain LCEL pipelines and custom citation verifiers |
| Web Console & Widget | Next.js (App Router) and TypeScript for embeddable chat and triage UI |
| Vector & Relational Store | PostgreSQL with pgvector for tenant-scoped document chunks and transcripts |
| Hybrid Search Layer | PostgreSQL full-text search combined with dense vector similarity and reranking |
| Session & Escalation Bus | Redis Streams and pub/sub for live agent takeover and typing indicators |
| Ingestion Workers | Asynchronous Python workers syncing help centers, markdown docs, and changelogs |
| Guardrail & Routing | Deterministic intent classifier for billing, outage, and sentiment triggers |
| Telemetry & QA | Structured feedback logs tracking groundedness checks and handoff reasons |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Choosing pgvector inside PostgreSQL over a standalone vector database | Consolidated relational permissions, transcripts, and embeddings in PostgreSQL; simplifies transactional consistency and tenant isolation at the cost of careful HNSW index tuning as collections scale. |
| Preventing race conditions when a human agent claims an active bot thread | Enforced atomic conversation-ownership locks in Redis checked before streaming begins, adding a small state lookup per turn while guaranteeing bot and human replies never interleave. |
| Balancing citation strictness against conversational fluency | Forced structured intermediate output separating answer prose from chunk IDs before rendering; introduces slight post-processing latency in exchange for verifiable links and fewer unsupported claims. |
| Supporting rich documentation embeds without bloating the widget script | Built a decoupled loader script rendering inside an isolated shadow container, trading one extra iframe/asset handshake for zero CSS interference on host SaaS dashboards. |
Security & Multi-Tenant Isolation
Hosting support corpora and end-user transcripts for multiple SaaS organizations demands rigorous tenant boundaries. All database access passes through scoped session contexts enforcing PostgreSQL row-level security by tenant identifier, ensuring vector similarity scans never cross organizational partitions.
End-user identity attributes—such as subscription tier or workspace ID—are passed via signed JWT handshakes from the host application rather than trusted from client query parameters. Prompt wrappers separate user messages cleanly from system instructions, strip markup injections, and scrub sensitive payment or credential patterns prior to persistent transcript logging.
Operational Outcomes
Replacing rigid support trees with a grounded Python, LangChain, and Next.js platform gave engineering and support teams measurable operational clarity:
- Trustworthy self-service: Customers verify recommendations directly via inline source citations instead of encountering ungrounded guesses.
- Frictionless escalations: Tier-2 specialists pick up escalated threads with complete diagnostic summaries rather than starting investigations from scratch.
- Actionable documentation feedback: Unresolved query clustering reveals exactly which help articles or API examples lack clarity, turning chat logs into a continuous documentation roadmap.
- Unified operational footprint: Consolidating hybrid retrieval, transcripts, and tenant permissions inside PostgreSQL keeps deployment and backup workflows straightforward for operations teams.