RuaLafaek AI Chat Implementation
Overview
RuaLafaek is an AI-powered conversational assistant for the LafaekStreet public dashboard, built using Amazon Nova 2 Lite through AWS Bedrock and LangChain. It provides intelligent responses to user queries about infrastructure reports, statistics, and platform information with built-in bot protection through hCaptcha verification.
Architecture
Core Components
- Chat Interface: Floating chat widget with modern UI and hCaptcha verification
- AI Processing: Amazon Nova 2 Lite model via AWS Bedrock
- Database Integration: Real-time queries to PostgreSQL database
- Response Generation: Structured markdown responses with proper formatting
- Bot Protection: hCaptcha verification system to prevent automated abuse
Technology Stack
- AI Model: Amazon Nova 2 Lite (
us.amazon.nova-2-lite-v1:0) - Framework: LangChain with AWS Bedrock integration
- Database: PostgreSQL with Prisma ORM
- Frontend: React with TypeScript, Framer Motion animations
- Markdown: ReactMarkdown with remark-gfm for rich text rendering
- Security: hCaptcha for bot protection and verification
LangChain & AWS Bedrock Flow Diagram
LangChain Integration Details
Implementation Details
1. AI Client Setup (lib/ai/nova-client.ts)
import { ChatBedrockConverse } from '@langchain/aws';
export const novaModel = new ChatBedrockConverse({
model: 'us.amazon.nova-2-lite-v1:0',
region: process.env.AWS_REGION || 'us-east-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
temperature: 0.7,
maxTokens: 1000,
});2. Query Classification System
The AI classifies user questions into three categories:
- DATABASE_QUERY: Infrastructure reports, statistics, location-based queries
- GENERAL_INFO: Platform information, how-to questions
- HELP: Navigation assistance, feature explanations
3. Database Query Handler (lib/ai/database-handler.ts)
- AI-Generated SQL: Nova 2 Lite converts natural language to PostgreSQL queries
- Safety Validation: Only SELECT queries allowed, forbidden operations blocked
- Fallback System: Predefined queries for common requests when AI fails
- Query Examples:
- "Show me potholes in Dili" → Filters by issue_type and municipality
- "How many reports this month" → COUNT aggregation with date filtering
4. Response Generation
- Structured Markdown: Clean formatting with headers, lists, and emphasis
- Conversational Tone: Friendly, professional responses with emojis
- Data Integration: Real database results presented in readable format
- Light/Dark Mode: Proper text colors for both themes
5. Chat Interface Components
Main Chat Widget (components/chat/LafaekAIChat.tsx)
- Floating chat bubble with custom AI logo
- Expandable/minimizable chat window
- Real-time message handling with loading states
- Error handling and retry mechanisms
Message Rendering (components/chat/ChatMessage.tsx)
- ReactMarkdown integration for rich text display
- Custom styling for headers, lists, code blocks
- User/AI message differentiation
- Suggestion buttons for follow-up questions
Input Component (components/chat/ChatInput.tsx)
- Character Limit: 500 characters maximum
- Input Validation: Client and server-side validation
- Visual Feedback: Character counter with warning colors
6. Security & Validation
hCaptcha Bot Protection (lib/hcaptcha.ts)
export async function verifyHCaptcha(token: string): Promise<boolean> {
const secretKey = process.env.HCAPTCHA_SECRET_KEY;
const response = await fetch('https://hcaptcha.com/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
secret: secretKey,
response: token,
}),
});
const data = await response.json();
return data.success;
}Chat Verification Flow
- Initial Access: User opens chat → hCaptcha verification required
- Token Generation: User completes captcha → receives verification token
- API Validation: Each message includes token → server verifies with hCaptcha
- Session Management: Verification persists until chat is closed/refreshed
Input Limits
- Maximum 500 characters per message
- Real-time character counting with visual warnings
- Server-side validation to prevent abuse
SQL Safety
function isQuerySafe(sqlQuery: string): boolean {
const query = sqlQuery.toLowerCase().trim();
// Only allow SELECT queries
if (!query.startsWith('select')) return false;
// Block dangerous operations
const forbiddenKeywords = [
'insert',
'update',
'delete',
'drop',
'create',
'alter',
'truncate',
'grant',
'revoke',
'exec',
'execute',
];
return !forbiddenKeywords.some((keyword) => query.includes(keyword));
}Configuration
Environment Variables
# AWS Credentials
AWS_REGION="us-east-1"
AWS_ACCESS_KEY_ID="your_access_key"
AWS_SECRET_ACCESS_KEY="your_secret_key"
BEDROCK_MODEL_ID="us.amazon.nova-2-lite-v1:0"
# Database
DATABASE_URL="postgresql://user:pass@host:port/db"
# hCaptcha Configuration
NEXT_PUBLIC_HCAPTCHA_SITE_KEY="your_site_key"
HCAPTCHA_SECRET_KEY="your_secret_key"Dependencies
{
"@langchain/aws": "^0.1.0",
"@hcaptcha/react-hcaptcha": "^1.10.1",
"react-markdown": "^9.0.0",
"remark-gfm": "^4.0.0",
"framer-motion": "^11.0.0"
}Features
Current Capabilities
✅ Real Database Queries: Live data from infrastructure reports ✅ Natural Language Processing: Understands context and intent ✅ Markdown Rendering: Rich text responses with proper formatting ✅ Input Validation: Character limits and safety checks ✅ Error Handling: Graceful fallbacks and user-friendly messages ✅ Custom Branding: RuaLafaek name and custom AI logo ✅ Responsive Design: Works on desktop and mobile devices ✅ Light/Dark Mode: Proper text contrast in both themes ✅ Bot Protection: hCaptcha verification prevents automated abuse ✅ Session Security: Token-based verification for each interaction
Query Examples
- "Show me all potholes in Dili"
- "How many reports were submitted this month?"
- "What's the status of street lighting issues?"
- "Which municipality has the most pending reports?"
Response Format
## Query Results
Here's what I found in the database:
### Recent Reports
- **Report 1**: Description (Status: Pending)
- **Report 2**: Description (Status: Fixed)
### Key Insights
Most reports are related to...Performance & Monitoring
Response Times
- Database queries: ~200ms average
- AI processing: ~3-8 seconds
- Total response time: ~4-10 seconds
Error Handling
- AI service failures → Fallback to keyword-based queries
- Database errors → User-friendly error messages
- Network issues → Retry mechanisms with exponential backoff
Troubleshooting
Common Issues
- AI not responding: Check AWS credentials and region
- Database errors: Verify connection string and permissions
- Slow responses: Monitor AWS Bedrock quotas and limits
- Markdown not rendering: Check ReactMarkdown configuration
- hCaptcha not loading: Verify site key and network connectivity
- Verification failing: Check secret key configuration and token expiry
Debug Commands
# Test API endpoint
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Show me reports in Dili", "hcaptchaToken": "test_token"}'
# Check database connection
curl http://localhost:3000/api/health/db
# Test hCaptcha configuration
curl -X POST https://hcaptcha.com/siteverify \
-d "secret=YOUR_SECRET_KEY&response=test_token"hCaptcha Setup Guide
- Register Account: Visit hCaptcha.com and create account
- Create Site: Add your domain to get site key and secret key
- Environment Setup: Add keys to
.env.local - Testing: Use test keys for development:
- Site Key:
10000000-ffff-ffff-ffff-000000000001 - Secret Key:
0x0000000000000000000000000000000000000000
- Site Key:
Conclusion
RuaLafaek represents a sophisticated integration of modern AI technologies with civic engagement platforms. By combining Amazon Nova 2 Lite's natural language capabilities with real-time database access and robust security measures through hCaptcha verification, it provides citizens with a secure and intuitive way to explore infrastructure data and engage with their local government services.
The implementation prioritizes both user experience and security, ensuring that legitimate users can easily access information while preventing automated abuse and maintaining system integrity.
