Integrating Large Language Models into Enterprise Web Applications with RAG & Pgvector
By Abu Bakr
•
August 10, 2026
Integrating Large Language Models (LLMs) into enterprise production applications requires moving beyond basic prompt engineering. To prevent hallucinations and enforce strict data privacy, modern software architectures employ **Retrieval-Augmented Generation (RAG)**—a pattern that injects verified company data directly into the model's context window prior to response synthesis.
In this article, we detail the production-tested RAG pipeline we implement at MTAI Software Labs using PostgreSQL (`pgvector`), OpenAI embeddings, and Node.js/TypeScript.
---
## 1. High-Level Architecture of an Enterprise RAG Pipeline
```
[ User Query ]
│
▼
┌───────────────────────────┐
│ Generate Vector Embedding│ <-- OpenAI text-embedding-3-small
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Vector Similarity Search │ <-- PostgreSQL (pgvector cosine similarity)
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Inject Relevant Context │ <-- Top-K Document Snippets
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Stream Response via LLM │ <-- Claude 3.5 Sonnet / GPT-4o
└───────────────────────────┘
```
---
## 2. Setting Up Vector Search in PostgreSQL
Instead of managing a separate vector database (such as Pinecone or Milvus), enterprise teams often prefer utilizing existing PostgreSQL infrastructure via the `pgvector` extension. This simplifies transaction safety, backup procedures, and role-based access control (RBAC).
```sql
-- Enable the vector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create document chunk storage with 1536-dimensional vector column
CREATE TABLE document_chunks (
id BIGSERIAL PRIMARY KEY,
document_id UUID NOT NULL,
content TEXT NOT NULL,
metadata JSONB DEFAULT '{}'::jsonb,
embedding vector(1536),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Create HNSW index for high-speed cosine similarity lookup
CREATE INDEX ON document_chunks
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
```
---
## 3. Node.js Implementation of Vector Querying
Below is the TypeScript handler for performing context retrieval with Drizzle ORM and `pgvector`:
```typescript
import { db } from "./db";
import { sql } from "drizzle-orm";
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function retrieveRelevantContext(userQuery: string, limit = 4) {
// 1. Generate query embedding
const embeddingResponse = await openai.embeddings.create({
model: "text-embedding-3-small",
input: userQuery,
});
const queryVector = JSON.stringify(embeddingResponse.data[0].embedding);
// 2. Perform Cosine Similarity Search using pgvector <=> operator
const results = await db.execute(sql`
SELECT id, content, metadata,
1 - (embedding <=> ${queryVector}::vector) AS similarity
FROM document_chunks
WHERE 1 - (embedding <=> ${queryVector}::vector) > 0.72
ORDER BY embedding <=> ${queryVector}::vector ASC
LIMIT ${limit};
`);
return results.rows;
}
```
---
## 4. Key Lessons from Enterprise Deployments
> - **Chunking Strategy Matters:** Chunking documents by semantic paragraphs (approx. 400-600 tokens with 50-token overlap) yields significantly better accuracy than rigid character splitting.
> - **Enforce Metadata Filtering:** Always filter vector queries by tenant/organization ID before computing distance metrics to avoid cross-tenant data leaks.
> - **Stream Responses:** Use Server-Sent Events (SSE) or WebSockets to stream LLM outputs to users instantly, reducing perceived latency from 4.5s down to <300ms (Time-to-First-Token).
---
## Summary
RAG provides an enterprise-ready mechanism to leverage AI intelligence while retaining 100% authority over proprietary data. By implementing `pgvector` alongside existing relational databases, organizations can roll out AI capabilities quickly without adding complex infrastructure dependencies.
In this article, we detail the production-tested RAG pipeline we implement at MTAI Software Labs using PostgreSQL (`pgvector`), OpenAI embeddings, and Node.js/TypeScript.
---
## 1. High-Level Architecture of an Enterprise RAG Pipeline
```
[ User Query ]
│
▼
┌───────────────────────────┐
│ Generate Vector Embedding│ <-- OpenAI text-embedding-3-small
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Vector Similarity Search │ <-- PostgreSQL (pgvector cosine similarity)
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Inject Relevant Context │ <-- Top-K Document Snippets
└─────────────┬─────────────┘
│
▼
┌───────────────────────────┐
│ Stream Response via LLM │ <-- Claude 3.5 Sonnet / GPT-4o
└───────────────────────────┘
```
---
## 2. Setting Up Vector Search in PostgreSQL
Instead of managing a separate vector database (such as Pinecone or Milvus), enterprise teams often prefer utilizing existing PostgreSQL infrastructure via the `pgvector` extension. This simplifies transaction safety, backup procedures, and role-based access control (RBAC).
```sql
-- Enable the vector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Create document chunk storage with 1536-dimensional vector column
CREATE TABLE document_chunks (
id BIGSERIAL PRIMARY KEY,
document_id UUID NOT NULL,
content TEXT NOT NULL,
metadata JSONB DEFAULT '{}'::jsonb,
embedding vector(1536),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Create HNSW index for high-speed cosine similarity lookup
CREATE INDEX ON document_chunks
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
```
---
## 3. Node.js Implementation of Vector Querying
Below is the TypeScript handler for performing context retrieval with Drizzle ORM and `pgvector`:
```typescript
import { db } from "./db";
import { sql } from "drizzle-orm";
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function retrieveRelevantContext(userQuery: string, limit = 4) {
// 1. Generate query embedding
const embeddingResponse = await openai.embeddings.create({
model: "text-embedding-3-small",
input: userQuery,
});
const queryVector = JSON.stringify(embeddingResponse.data[0].embedding);
// 2. Perform Cosine Similarity Search using pgvector <=> operator
const results = await db.execute(sql`
SELECT id, content, metadata,
1 - (embedding <=> ${queryVector}::vector) AS similarity
FROM document_chunks
WHERE 1 - (embedding <=> ${queryVector}::vector) > 0.72
ORDER BY embedding <=> ${queryVector}::vector ASC
LIMIT ${limit};
`);
return results.rows;
}
```
---
## 4. Key Lessons from Enterprise Deployments
> - **Chunking Strategy Matters:** Chunking documents by semantic paragraphs (approx. 400-600 tokens with 50-token overlap) yields significantly better accuracy than rigid character splitting.
> - **Enforce Metadata Filtering:** Always filter vector queries by tenant/organization ID before computing distance metrics to avoid cross-tenant data leaks.
> - **Stream Responses:** Use Server-Sent Events (SSE) or WebSockets to stream LLM outputs to users instantly, reducing perceived latency from 4.5s down to <300ms (Time-to-First-Token).
---
## Summary
RAG provides an enterprise-ready mechanism to leverage AI intelligence while retaining 100% authority over proprietary data. By implementing `pgvector` alongside existing relational databases, organizations can roll out AI capabilities quickly without adding complex infrastructure dependencies.
#ai
#llm
#rag
#postgresql
#pgvector
#typescript
Need expert engineering assistance?
Discuss your software, mobile app, or AI project with our team.