An intelligent customer support system built with Domain-Driven Design (DDD), Hexagonal Architecture, WebSockets, PostgreSQL, and RAG (Retrieval-Augmented Generation) capabilities using LangGraph and OpenAI.
- π€ Intelligent Conversational Agent: Natural language processing with context awareness
- π Real-time WebSocket Communication: Live chat functionality for customer support
- π§ RAG Implementation: Knowledge base integration using LangGraph for intelligent responses
- π Structured Data Extraction: Automatic extraction of order numbers, problem categories, descriptions, and urgency levels
- π Conversation Summarization: Generate summaries and extract key points from conversations
- ποΈ Clean Architecture: DDD, Hexagonal Architecture, and Design Patterns
- π PostgreSQL Integration: Structured data storage with migrations
- π³ Docker Support: Containerized deployment with Docker Compose
- π§ͺ Comprehensive Testing: Full test suite with WebSocket testing
- πΎ Redis Caching: High-performance caching system for improved response times
- π Knowledge Base Management: Automated setup and management of RAG knowledge base
The project follows Domain-Driven Design (DDD) and Hexagonal Architecture principles:
src/
βββ domain/ # Domain layer
β βββ entities/ # Business entities
β β βββ conversation.py
β β βββ message.py
β β βββ extracted_data.py
β β βββ customer_support_ticket.py
β βββ value_objects/ # Value objects
β β βββ conversation_id.py
β β βββ message_id.py
β β βββ order_number.py
β β βββ problem_category.py
β β βββ urgency_level.py
β βββ repositories/ # Repository interfaces (ports)
β β βββ conversation_repository.py
β β βββ extracted_data_repository.py
β β βββ customer_support_ticket_repository.py
β βββ services/ # Domain services
β βββ data_extraction_service.py
β βββ rag_service.py
βββ application/ # Application layer
β βββ use_cases/ # Use cases
β β βββ process_websocket_message.py
β β βββ create_conversation.py
β β βββ get_conversation.py
β β βββ generate_conversation_summary.py
β βββ dtos/ # Data Transfer Objects
β βββ websocket_message.py
β βββ conversation_dto.py
β βββ message_dto.py
β βββ extracted_data_dto.py
βββ infrastructure/ # Infrastructure layer
β βββ cache/ # Caching implementations
β β βββ conversation_cache.py
β β βββ redis_service.py
β βββ database/ # Database implementations
β β βββ models.py
β β βββ config.py
β β βββ repositories/
β βββ external_services/ # External service integrations
β βββ websockets/ # WebSocket handling
β β βββ websocket_handler.py
β βββ services/ # Service implementations
β βββ rag_service_impl.py
β βββ data_extraction_service_impl.py
βββ presentation/ # Presentation layer
β βββ api/ # API endpoints
β β βββ conversation_routes.py
β βββ websockets/ # WebSocket endpoints
β βββ websocket_routes.py
βββ shared/ # Shared utilities
βββ config/ # Configuration
βββ logging/ # Logging setup
βββ exceptions/ # Custom exceptions
scripts/ # Utility scripts
βββ setup_knowledge_base.py
βββ test_chat.py
- Python 3.12+
- Poetry
- Docker and Docker Compose
- PostgreSQL (or use Docker)
- OpenAI API Key
-
Clone and setup
git clone <repository-url> cd vega make setup
-
Configure environment
cp .env.example .env # Edit .env with your OpenAI API key -
Start with Docker (Recommended)
make docker-up
Create a .env file with the following variables:
# Database Configuration
DATABASE_URL=postgresql://vega_user:vega_password@localhost:5432/vega_ai
REDIS_URL=redis://localhost:6379
# OpenAI Configuration
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-4
EMBEDDING_MODEL=text-embedding-ada-002
# Application Configuration
APP_NAME=Vega Customer Support System
APP_VERSION=1.0.0
DEBUG=true
LOG_LEVEL=INFO
SECRET_KEY=vega-secret-key-change-in-production
# WebSocket Configuration
WS_MAX_CONNECTIONS=100
WS_HEARTBEAT_INTERVAL=30
# RAG Configuration
KNOWLEDGE_BASE_PATH=./knowledge_base
VECTOR_STORE_TYPE=chroma
# Redis Configuration
REDIS_MAX_CONNECTIONS=100
REDIS_RETRY_ON_TIMEOUT=true
# Security
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30GET /- Root endpoint with system informationGET /health- Health check with WebSocket connection statsGET /stats- Connection and cache statisticsGET /cache/stats- Detailed cache statisticsPOST /cache/clear- Clear Redis cacheGET /conversations- List conversations with paginationGET /conversations/{id}- Get specific conversationPOST /conversations- Create new conversationPOST /conversations/{id}/summary- Generate conversation summary
ws://localhost:8000/ws/chat/{conversation_id}- Chat with specific conversationws://localhost:8000/ws/chat- General chat (creates new conversation automatically)ws://localhost:8000/ws/test- WebSocket test page
Send a text message:
{
"type": "text",
"data": {
"content": "Hello, I need help with my order ORD123456"
},
"conversation_id": "optional-conversation-id",
"user_id": "optional-user-id"
}Send typing indicator:
{
"type": "typing",
"data": {
"is_typing": true
}
}Request conversation summary:
{
"type": "summary_request",
"conversation_id": "conversation-id"
}Heartbeat:
{
"type": "heartbeat",
"data": {
"timestamp": 1234567890
}
}Text response:
{
"type": "text_response",
"content": "I'd be happy to help you with order ORD123456...",
"extracted_info": {
"order_number": "ORD123456",
"problem_category": "technical",
"problem_description": "Application not working",
"urgency_level": "high",
"confidence_score": 0.85,
"completion_percentage": 100.0
}
}Summary response:
{
"type": "summary_response",
"summary": "Customer reported technical issues with order ORD123456...",
"key_points": [
"Order number: ORD123456",
"Technical problem with application",
"High urgency level",
"Customer needs immediate assistance"
],
"extracted_data": {
"order_number": "ORD123456",
"problem_category": "technical",
"problem_description": "Application not working",
"urgency_level": "high",
"confidence_score": 0.85
}
}The system automatically extracts structured data from conversations:
- Order Number: Patterns like ORD123456, #123456, order-123
- Problem Category: technical, billing, shipping, product, account, general
- Problem Description: Clear description of the issue
- Urgency Level: low, medium, high, critical
- Confidence Score: 0.0 to 1.0 based on extraction quality
- Order numbers must be 3-20 characters, alphanumeric and hyphens only
- Problem categories must be valid enum values
- Urgency levels must be valid enum values
- Confidence scores are calculated based on field completeness
The system uses LangGraph for intelligent response generation:
- Document Retrieval: Searches knowledge base for relevant information
- Context Building: Combines retrieved docs with conversation history
- Response Generation: Uses OpenAI to generate contextual responses
- Summary Generation: Creates conversation summaries and key points
The system includes automated knowledge base setup with sample documents covering:
- Order processing information
- Technical support guidelines
- Billing and payment procedures
- Shipping information
- Product details
- Account management
- General support policies
Use make setup-kb to initialize the knowledge base with these documents.
def _build_graph(self) -> StateGraph:
def retrieve_documents(state):
# Retrieve relevant documents from knowledge base
pass
def generate_response(state):
# Generate response using retrieved documents
pass
# Build the graph
workflow = StateGraph(dict)
workflow.add_node("retrieve", retrieve_documents)
workflow.add_node("generate", generate_response)
workflow.set_entry_point("retrieve")
workflow.add_edge("retrieve", "generate")
workflow.add_edge("generate", END)
return workflow.compile()- conversations: Store conversation metadata
- messages: Store individual messages
- extracted_data: Store structured data extracted from conversations
- customer_support_tickets: Store support tickets created from conversations
# Create new migration
make migrate-create message="Add new table"
# Run migrations
make migrate
# Setup knowledge base
make setup-kb
# Check environment variables
make check-env
# Open API documentation
make docs
# Clean database files
make clean-db# Start all services
make docker-up
# View logs
make docker-logs
# Stop services
make docker-down- app: FastAPI application
- postgres: PostgreSQL database
- redis: Redis cache (for future use)
# Setup knowledge base with sample documents
make setup-kb
# Or run directly
poetry run python scripts/setup_knowledge_base.py# Test WebSocket chat
poetry run python scripts/test_chat.py# Interactive test
make test-client
# Or use the test page
open http://localhost:8000/ws/test# Run tests
make test
# Check health
make status- Application:
GET /health- System status with WebSocket connections - Database: Automatic connection health checks
- WebSocket: Connection count monitoring
- Cache: Redis connection and performance monitoring via
GET /cache/stats
# View application logs
make logs
# View Docker logs
make docker-logs# Format code
make format
# Run linting
make lint
# Pre-commit checks
make pre-commit
# Check environment setup
make check-env# Create migration
make migrate-create message="Description"
# Run migrations
make migrateEnsure all required environment variables are set:
DATABASE_URL=postgresql://user:pass@host:port/db
OPENAI_API_KEY=your_key
SECRET_KEY=your_secret_key
DEBUG=false- Set strong
SECRET_KEY - Configure proper CORS origins
- Use environment-specific database URLs
- Enable HTTPS in production
- Set appropriate rate limits
import asyncio
import websockets
import json
async def chat_example():
uri = "ws://localhost:8000/ws/chat"
async with websockets.connect(uri) as websocket:
# Send message
await websocket.send(json.dumps({
"type": "text",
"data": {"content": "I need help with order ORD123456"}
}))
# Receive response
response = await websocket.recv()
data = json.loads(response)
print(f"AI: {data['content']}")
print(f"Extracted: {data['extracted_info']}")
asyncio.run(chat_example())const ws = new WebSocket('ws://localhost:8000/ws/chat');
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('AI:', data.content);
console.log('Extracted:', data.extracted_info);
};
// Send message
ws.send(JSON.stringify({
type: "text",
data: { content: "I need help with order ORD123456" }
}));This project is licensed under the MIT License.
Vega Customer Support System - Intelligent customer support with DDD, WebSockets, and RAG capabilities.