Production-ready, end-to-end Retrieval-Augmented Generation (RAG) system that delivers Article-cited legal insights from Kuwait Labour Law through a secure, rate-limited webhook API β built on n8n, OpenAI, Pinecone, and PostgreSQL.
Vasudha KnowledgeSphere AI is a fully deployed enterprise AI agent that answers natural language questions about Kuwait Labour Law No. 6 of 2010 with precision, speed, and full auditability.
The system transforms a 136-page scanned PDF into a searchable vector knowledge base, then serves grounded, Article-cited answers through a production-grade REST API β complete with session memory, enhanced logging, and rate limiting.
Built as a flagship product of the Black Elephant AI Learning Ecosystem, this project demonstrates a complete, client-deployable RAG architecture β from raw document to live intelligent API.
| Problem | Solution |
|---|---|
| HR & Legal teams spend hours searching labour law | Instant natural language Q&A with Article-level citations |
| Scanned PDFs are unsearchable | Docling OCR + semantic chunking makes every Article queryable |
| Generic AI hallucinates legal answers | RAG grounds every answer strictly in the law text |
| No visibility into AI system behaviour | Full audit log with retrieval scores, latency, and cited Articles |
| API abuse and runaway costs | Rate limiting (20 req/hour/user) with 429 enforcement |
| Unstructured API responses | Structured JSON with answer + metadata on every response |
Target Users: HR Managers, Legal Advisors, Compliance Officers, and Operations Teams at Kuwait private sector enterprises.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INGESTION PIPELINE β
β (one-time / on update) β
β β
β Kuwait Labour Law PDF (136 pages, Canon-scanned, 2010) β
β β β
β βΌ β
β [Docling OCR] βββΊ kuwait_labour_law.md (167,367 chars) β
β β β
β βΌ β
β [Python Chunker] βββΊ 169 chunks (Article-level + Preamble) β
β β metadata: source, article_number β
β βΌ β
β [OpenAI text-embedding-3-small] βββΊ 1536-dim vectors β
β β β
β βΌ β
β [Pinecone vasudha-knowledge] βββΊ namespace: kuwait-labour-lawβ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β QUERY PIPELINE β
β (n8n webhook workflow) β
β β
β POST /webhook/vasudhachatbotv1 β
β Headers: x-api-key β
β Body: { message, session_id, user_id } β
β β β
β βΌ β
β [Session Manager] ββ API Key Auth + Input Validation β
β β β β
β β (invalid) βββΊ 400/401 β
β βΌ β
β [Rate Limit Check] ββ Query rate_limits table β
β β β
β βΌ β
β [Rate Limit Gate] ββ IF requests < 20/hour β
β β β β
β TRUE FALSE βββΊ 429 Too Many Requests β
β β β
β βΌ β
β [Rate Limit Logger] ββ INSERT into rate_limits β
β β β
β βΌ β
β [Embed Question] ββ OpenAI text-embedding-3-small β
β β β
β βΌ β
β [Query Pinecone] ββ top_k=10, cosine similarity β
β β β
β βΌ β
β [Format Context] ββ Assemble Articles + capture metadata β
β β β
β βΌ β
β [AI Agent / GPT-3.5-turbo] ββ Cite Articles, stay grounded β
β β β β
β β [Postgres Chat Memory] ββ session history β
β βΌ β
β [Upsert Conversation] ββ Full audit log to Postgres β
β β (articles, confidence, latency, times) β
β βΌ β
β [Respond to Webhook] ββ Structured JSON response β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
{
"success": true,
"answer": "According to Article 70 of Kuwait Labour Law No. 6 of 2010, a labourer shall have the right to a paid annual leave of thirty (30) days. However, a labourer is entitled to leave for the first year only after completing at least nine months of service with the employer.",
"metadata": {
"session_id": "hr-session-001",
"user_id": "manager-kuwait",
"articles_retrieved": ["Article 70", "Article 71", "Article 73", "Article 72"],
"top_confidence": 0.6147,
"retrieval_count": 10,
"source": "Kuwait Labour Law No. 6 of 2010",
"timestamp": "2026-04-18T17:57:50.277Z"
}
}| Layer | Technology |
|---|---|
| Orchestration | n8n (self-hosted via Docker) |
| OCR / Document Processing | Docling by IBM |
| Embedding Model | OpenAI text-embedding-3-small (1536 dimensions) |
| Vector Database | Pinecone Serverless (AWS us-east-1, cosine similarity) |
| LLM | OpenAI GPT-3.5-turbo |
| Memory | PostgreSQL (n8n_chat_history) |
| Audit Logging | PostgreSQL (conversation_history) |
| Rate Limiting | PostgreSQL (rate_limits) |
| Authentication | API Key via x-api-key header |
| Runtime | Python 3.11, Docker, macOS Apple Silicon compatible |
vasudha-knowledgesphere-ai/
β
βββ π Kuwait_Labour_Law_English.pdf # Source: 136-page scanned PDF
βββ π kuwait_labour_law.md # Docling OCR output (167,367 chars)
βββ π kuwait_labour_law_chunks.json # 169 Article-level chunks with metadata
β
βββ π ocr_labour_law.py # Phase 1: Docling OCR extraction
βββ π chunk_labour_law.py # Phase 2: Article-level chunking
βββ π embed_and_upsert.py # Phase 3: OpenAI embed + Pinecone upsert
βββ π test_rag.py # RAG pipeline test script
β
βββ π 6_Vasudha-Knowledge-HR-Sphere-AI-Agent.json # Complete n8n workflow (importable)
βββ ποΈ vasudha-db.sql # Full PostgreSQL schema
β
βββ π .env.example # Environment variable template
βββ π .gitignore
βββ π README.md
- Python 3.11+
- Docker Desktop (for n8n)
- PostgreSQL (local or cloud)
- OpenAI API key
- Pinecone account (free tier sufficient)
git clone https://github.com/hrswatirai-debug/vasudha-knowledgesphere-ai.git
cd vasudha-knowledgesphere-aipython3 -m venv vasudha_rag_env
source vasudha_rag_env/bin/activate
pip install docling pinecone openai python-dotenv --timeout 300
β οΈ Docling installs PyTorch (~80MB). Use--timeout 300on slower connections.
cp .env.example .envEdit .env:
PINECONE_API_KEY=your_pinecone_api_key
OPENAI_API_KEY=your_openai_api_keypsql -U postgres -d your_database -f vasudha-db.sqlCreates three tables:
conversation_historyβ full audit log with RAG metadatan8n_chat_historyβ session memory for multi-turn conversationsrate_limitsβ per-user request tracking for rate limiting
In app.pinecone.io, create an index:
| Setting | Value |
|---|---|
| Index name | vasudha-knowledge |
| Dimensions | 1536 |
| Metric | cosine |
| Type | Dense / Serverless |
| Cloud | AWS us-east-1 |
Skip if using the pre-built sample data files included in this repo.
# OCR the PDF (10-15 mins, downloads Docling models on first run)
python3 ocr_labour_law.py
# Chunk by Article
python3 chunk_labour_law.py
# Embed and upsert to Pinecone
python3 embed_and_upsert.pyExpected output:
π¦ Loaded 169 chunks
β
Upserted 20/169 chunks
...
π DONE! 169 chunks stored in Pinecone!
π Total vectors in index: 169
python3 test_rag.pyExpected output:
π Query: What are the rules for annual leave?
Score: 0.6147 | Article 70 β 30 days paid annual leave...
Score: 0.5947 | Article 73 β Cash equivalent for leave...
Score: 0.5566 | Article 71 β Leave carry-forward rules...
- Start n8n:
docker start n8n - Open
http://localhost:5678 - Workflows β Import from file
- Select
6_Vasudha-Knowledge-HR-Sphere-AI-Agent.json - Configure credentials: OpenAI API key + PostgreSQL connection
- Publish the workflow
curl -X POST http://localhost:5678/webhook/vasudhachatbotv1 \
-H "Content-Type: application/json" \
-H "x-api-key: black-elephant-2026" \
-d '{
"message": "What is the annual leave entitlement?",
"session_id": "test-session-001",
"user_id": "demo-user"
}'All requests validated via x-api-key header. Invalid keys return 401 Unauthorized.
- Message field required and non-empty
- Maximum 1000 characters per message
session_idrequired for conversation tracking
- Maximum 20 requests per hour per user
- Tracked in PostgreSQL
rate_limitstable - Exceeding limit returns
429 Too Many Requests - Logged before expensive OpenAI calls to prevent abuse
Every interaction logged to conversation_history with:
| Field | Description |
|---|---|
session_id |
Conversation identifier |
user_id |
Requesting user |
message |
AI response text |
articles_retrieved |
JSON array of cited Articles |
top_confidence |
Pinecone similarity score (0β1) |
retrieval_count |
Number of Articles retrieved |
request_time |
When user sent the message |
response_time |
When AI response was written |
processing_ms |
End-to-end latency in milliseconds |
| Node | Type | Purpose |
|---|---|---|
| Webhook | Trigger | POST endpoint /vasudhachatbotv1 |
| Session Manager | Code | API key auth, input validation, session init |
| Rate Limit Check | Postgres | Count requests in last hour for this user |
| Rate Limit Gate | IF | Branch: allow (< 20) or block (β₯ 20) |
| Rate Limit Logger | Postgres | Log valid request to rate_limits |
| Rate Limit Error | Response | Return 429 with JSON error |
| Embed Question | HTTP Request | OpenAI Embeddings API call |
| Query Pinecone | HTTP Request | Semantic search β top 10 Articles |
| Format Context | Code | Build context + capture RAG metadata |
| AI Agent | LangChain | GPT-3.5-turbo with system prompt |
| OpenAI Chat Model | LangChain | Language model sub-node |
| Postgres Chat Memory | LangChain | Multi-turn session memory |
| Upsert Conversation | Postgres | Full audit log write |
| Respond to Webhook | Response | Structured JSON response |
| Error Response | Response | 400/401 error responses |
| Metric | Value |
|---|---|
| Source document | Kuwait Labour Law No. 6 of 2010 |
| Pages processed | 136 pages |
| OCR engine | Docling (IBM) |
| Extracted text | 167,367 characters |
| Total chunks | 169 (168 Articles + Preamble) |
| Embedding model | text-embedding-3-small (1536 dims) |
| Avg similarity score | 0.51 β 0.61 for relevant queries |
| Avg end-to-end latency | ~7β15 seconds |
| Rate limit | 20 requests / hour / user |
- Multi-document support (HR Manuals, Service Agreements, Oil & Gas regulations)
- RBAC β namespace-level access control per user role
- Telegram bot interface for mobile access
- Arabic language support
- Document update pipeline (automated re-ingestion on change)
- Analytics dashboard for usage and confidence trends
Built by Swati Rai β AI Entrepreneur & Applied AI Consultant, based in Kuwait and India. Technically mentored and supported by Black Elephant AI Learning Ecosystem, India.
Specializing in Generative AI and Agentic AI solutions for enterprise clients across Oil & Gas, HR, Legal, and Government sectors in the GCC.
MIT License β see LICENSE for details.
Disclaimer: This system is a legal reference tool. Always consult a qualified legal professional for binding legal advice.