- Introduced a new session history feature that tracks and manages conversation history across multiple chat sessions. - Implemented REST API endpoints for creating, listing, retrieving, and deleting chat sessions. - Enhanced error handling and logging for session management operations. - Updated README.md to include documentation for the new session history feature and its usage.
6.4 KiB
Session History: Always-On Feature
Final Simplification
Based on user feedback, we've removed the SESSION_HISTORY_ENABLED variable completely. Session history is now always enabled as a core feature of LightRAG Server.
Rationale
Why Remove the Toggle?
- It's Always Useful: Session history is a fundamental feature for chat applications
- No Overhead: If you don't use it, it doesn't impact performance
- Graceful Degradation: If PostgreSQL fails, server still starts (endpoints just unavailable)
- Simpler UX: One less thing for users to configure
- Modern Default: Chat history should be expected, not optional
What Changed
Before (With Toggle)
SESSION_HISTORY_ENABLED=true # Required this line
After (Always On)
# Nothing needed! Session history just works
How It Works Now
Automatic Initialization
When LightRAG Server starts:
- ✅ Reads
POSTGRES_*environment variables - ✅ Connects to PostgreSQL
- ✅ Creates session tables automatically (if they don't exist)
- ✅ Enables
/history/*endpoints - ✅ Ready to use!
Graceful Failure
If PostgreSQL is not available:
WARNING: Session history initialization failed: connection refused
WARNING: Session history endpoints will be unavailable
INFO: Server is ready to accept connections! 🚀
- ✅ Server still starts
- ✅ Other features work normally
- ✅ Session endpoints return 503 (service unavailable)
- ✅ No crash or hard failure
Configuration
Complete Setup
# File: .env
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DATABASE=lightrag_db
# That's it! Session history automatically enabled
No PostgreSQL?
If you don't have PostgreSQL:
- LightRAG Server will start normally
- Session endpoints won't be available
- All other features work as expected
- Check logs for: "Session history endpoints will be unavailable"
Benefits
For Users
- ✅ Zero Configuration: No ENV variable to set
- ✅ Just Works: Automatic if PostgreSQL is available
- ✅ No Surprises: Consistent behavior
- ✅ Less Confusion: No "should I enable this?" questions
For Developers
- ✅ Cleaner Code: No conditional logic for enable/disable
- ✅ Simpler Tests: Always test with feature enabled
- ✅ Better UX: Feature discovery through API docs
- ✅ Modern Architecture: Features are on by default
Migration
From SESSION_HISTORY_ENABLED=true
Simply remove the line from your .env:
# Remove this line
# SESSION_HISTORY_ENABLED=true
# Everything else stays the same
From SESSION_HISTORY_ENABLED=false
If you had it disabled:
# Remove this line
# SESSION_HISTORY_ENABLED=false
# Session history will now be available
# Just don't use the endpoints if you don't need them
API Endpoints
Always available (when PostgreSQL is configured):
POST /history/sessions - Create session
GET /history/sessions - List sessions
GET /history/sessions/{id}/history - Get messages
DELETE /history/sessions/{id} - Delete session
Database Tables
Automatically created in POSTGRES_DATABASE:
lightrag_chat_sessions_historylightrag_chat_messages_historylightrag_message_citations_history
Use Cases
Development
# Just configure PostgreSQL
POSTGRES_HOST=localhost
POSTGRES_DATABASE=dev_lightrag
# Session history automatically available!
Production
# Production database
POSTGRES_HOST=prod-db.example.com
POSTGRES_DATABASE=lightrag_prod
# Session history automatically available!
Testing Without Sessions
# Don't configure PostgreSQL
# Or use SQLite for other storage
# Session endpoints return 503
# Rest of LightRAG works fine
Implementation
Server Initialization
# In lightrag_server.py
app = FastAPI(**app_kwargs)
# Initialize session history - always attempt
try:
session_db_manager = get_session_db_manager()
app.include_router(history_router)
logger.info("Session history initialized")
except Exception as e:
logger.warning(f"Session history unavailable: {e}")
# Server continues normally
Key Points
- ✅ No
if SESSION_HISTORY_ENABLEDchecks - ✅ Try to initialize, log warning if fails
- ✅ Server continues regardless
- ✅ Clean and simple
Philosophy
Modern Software Defaults
Good software should:
- Work out of the box - Session history just works
- Fail gracefully - Server starts even if sessions fail
- Be discoverable - Feature is in API docs by default
- Require minimal config - Use existing PostgreSQL
KISS Principle
- ❌ Before: "Do I need session history? Should I enable it?"
- ✅ After: "It's there if I need it!"
Progressive Enhancement
- Basic: LightRAG without PostgreSQL
- Enhanced: LightRAG with PostgreSQL + Session History
- No configuration needed to progress!
Summary
| Aspect | Before | After |
|---|---|---|
| Configuration | SESSION_HISTORY_ENABLED=true |
Nothing needed |
| If PostgreSQL available | Enabled | Enabled |
| If PostgreSQL unavailable | Disabled | Graceful warning |
| User decision needed | Yes | No |
| Code complexity | Conditional logic | Always attempt |
Quote from User
"Biến này lúc nào cũng = true thì cần gì nữa, xóa luôn"
Exactly right! If it's always true, why have it at all?
Session history is now a first-class citizen of LightRAG Server - always available, no questions asked! 🎉
Technical Notes
Database Connection
Uses the standard SQLAlchemy pattern:
class SessionDatabaseConfig:
def __init__(self):
self.host = os.getenv("POSTGRES_HOST", "localhost")
self.port = os.getenv("POSTGRES_PORT", "5432")
# ... etc
No special handling, no overrides, no complexity.
Graceful Degradation
Exception handling ensures server resilience:
try:
session_db_manager = get_session_db_manager()
app.include_router(history_router)
except Exception as e:
logger.warning(f"Session history unavailable: {e}")
# Server continues
Zero Impact
If session endpoints aren't used:
- ✅ No queries to database
- ✅ No performance overhead
- ✅ No resource consumption
- ✅ Just available when needed
Perfect! 🎯