mirror of
https://github.com/Significant-Gravitas/AutoGPT.git
synced 2026-02-09 22:35:54 -05:00
## Summary Enable LaunchDarkly feature flags to use rich user context and metadata for advanced targeting, including user segments, account age, email domains, and custom attributes. This unlocks LaunchDarkly's powerful targeting capabilities beyond simple user ID checks. ## Problem LaunchDarkly feature flags were only receiving basic user IDs, preventing the use of: - **Segment-based targeting** (e.g., "employees", "beta users", "new accounts") - **Contextual rules** (e.g., account age, email domain, custom metadata) - **Advanced LaunchDarkly features** like percentage rollouts by user attributes This limited feature flag flexibility and required manual user ID management for targeting. ## Solution ### 🎯 **LaunchDarkly Context Enhancement** - **Rich user context**: Send user metadata, segments, account age, email domain to LaunchDarkly - **Automatic segmentation**: Users automatically categorized as "employee", "new_user", "established_user" etc. - **Custom metadata support**: Any user metadata becomes available for LaunchDarkly targeting - **24-hour caching**: Efficient user context retrieval with TTL cache to reduce database calls ### 📊 **User Context Data** ```python # Before: Only user ID context = Context.builder("user-123").build() # After: Full context with targeting data context = { "email": "user@agpt.co", "created_at": "2023-01-15T10:00:00Z", "segments": ["employee", "established_user"], "email_domain": "agpt.co", "account_age_days": 365, "custom_role": "admin" } ``` ### 🏗️ **Required Infrastructure Changes** To support proper LaunchDarkly serialization, we needed to implement clean application models: #### **Application-Layer User Model** - Created snake_case User model (`created_at`, `email_verified`) for proper JSON serialization - LaunchDarkly expects consistent field naming - camelCase Prisma objects caused validation errors - Added `User.from_db()` converter to safely transform database objects #### **HTTP Client Reliability** - Fixed HTTP 4xx retry issue that was causing unnecessary load - Added layer validation to prevent database objects leaking to external services #### **Type Safety** - Eliminated `Any` types and defensive coding patterns - Proper typing enables better IDE support and catches errors early ## Technical Implementation ### **Core LaunchDarkly Enhancement** ```python # autogpt_libs/feature_flag/client.py @async_ttl_cache(maxsize=1000, ttl_seconds=86400) # 24h cache async def _fetch_user_context_data(user_id: str) -> dict[str, Any]: user = await get_user_by_id(user_id) return _build_launchdarkly_context(user) def _build_launchdarkly_context(user: User) -> dict[str, Any]: return { "email": user.email, "created_at": user.created_at.isoformat(), # snake_case for serialization "segments": determine_user_segments(user), "account_age_days": calculate_account_age(user), # ... more context data } ``` ### **User Segmentation Logic** - **Role-based**: `admin`, `user`, `system` segments - **Domain-based**: `employee` for @agpt.co emails - **Account age**: `new_user` (<7 days), `recent_user` (7-30 days), `established_user` (>30 days) - **Custom metadata**: Any user metadata becomes available for targeting ### **Infrastructure Updates** - `backend/data/model.py`: Application User model with proper serialization - `backend/util/service.py`: HTTP client improvements and layer validation - Multiple files: Migration to use application models for consistency ## LaunchDarkly Usage Examples With this enhancement, you can now create LaunchDarkly rules like: ```yaml # Target employees only - variation: true targets: - values: ["employee"] contextKind: "user" attribute: "segments" # Target new users for gradual rollout - variation: true rollout: variations: - variation: true weight: 25000 # 25% of new users contextKind: "user" bucketBy: "segments" filters: - attribute: "segments" op: "contains" values: ["new_user"] ``` ## Performance & Caching - **24-hour TTL cache**: Dramatically reduces database calls for user context - **Graceful fallbacks**: Simple user ID context if database unavailable - **Efficient caching**: 1000 entry LRU cache with automatic TTL expiration ## Testing - [x] LaunchDarkly context includes all expected user attributes - [x] Segmentation logic correctly categorizes users - [x] 24-hour cache reduces database load - [x] Fallback to simple context works when database unavailable - [x] All existing feature flag functionality preserved - [x] HTTP retry improvements work correctly ## Breaking Changes ✅ **No external API changes** - all existing feature flag usage continues to work ⚠️ **Internal changes only**: - `get_user_by_id()` returns application User model instead of Prisma model - Test utilities need to import User from `backend.data.model` ## Impact 🎯 **Product Impact**: - **Advanced targeting**: Product teams can now use sophisticated LaunchDarkly rules - **Better user experience**: Gradual rollouts, A/B testing, and segment-based features - **Operational efficiency**: Reduced need for manual user ID management 🚀 **Performance Impact**: - **Reduced database load**: 24-hour caching minimizes repeated user context queries - **Improved reliability**: Fixed HTTP retry inefficiencies - **Better monitoring**: Cleaner logs without 4xx retry noise --- **Primary goal**: Enable rich LaunchDarkly targeting with user context and segments **Infrastructure changes**: Required for proper serialization and reliability 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>