SulmanK commited on
Commit
436126f
·
1 Parent(s): d5eabda

Remove TODO file and associated design plan for production refinement - Deleted `TODO/todo.md` to streamline the codebase and eliminate outdated design documentation. This cleanup supports ongoing refactoring efforts and enhances overall project maintainability by removing unnecessary files that no longer align with the current development direction.

Browse files
Files changed (1) hide show
  1. TODO/todo.md +0 -594
TODO/todo.md CHANGED
@@ -1,594 +0,0 @@
1
- Okay, this is a substantial codebase with a good foundation, but there's definitely room for refinement to make it more production-ready, focusing on DRY principles and overall cleanliness.
2
-
3
- Here's a design plan for refactoring:
4
-
5
- ## Design Plan: Production Refinement for BeatDebate
6
-
7
- **Guiding Principles:**
8
-
9
- 1. **DRY (Don't Repeat Yourself):** Consolidate common logic into base classes, utility functions, or shared components.
10
- 2. **Single Responsibility Principle (SRP):** Ensure classes and modules have one primary reason to change.
11
- 3. **Dependency Inversion Principle (DIP):** Depend on abstractions, not concretions. The use of `APIService` and DI in agents is a good start.
12
- 4. **Clear Abstractions:** Make interfaces between components well-defined and intuitive.
13
- 5. **Configuration Management:** Centralize and simplify how configurations are handled and passed.
14
- 6. **Readability & Maintainability:** Improve code clarity through better organization and naming.
15
- 7. **Preserve Functionality:** All existing features should work as before.
16
-
17
- ---
18
-
19
- **Key Refactoring Areas & Action Plan:**
20
-
21
- ### 1. Agents (`src/agents/`)
22
-
23
- The agent structure has a good base with shared components. The main goal here is to ensure maximum leverage of these components and the `BaseAgent`.
24
-
25
- * **`BaseAgent` Enhancement:**
26
- * **Action:** Ensure `BaseAgent` handles common initialization patterns (e.g., logging setup, component instantiation if always the same type), standard error handling for `process`, and perhaps a standard way to access shared services like `APIService`, `MetadataService`.
27
- * **Rationale:** Reduces boilerplate in concrete agent classes.
28
-
29
- * **Advocate Agents (`GenreMoodAgent`, `DiscoveryAgent`):**
30
- * **Action (Candidate Generation):** Verify that *all* candidate generation logic is exclusively within `UnifiedCandidateGenerator`. Remove any local API calls or direct list building for candidates within these agents. They should only configure and call the generator.
31
- * **Action (Scoring):** Ensure that all scoring uses `ComprehensiveQualityScorer`. Agent-specific scoring logic should be encapsulated as strategies *within* the `QualityScorer` or passed as parameters, rather than being implemented directly in the agent.
32
- * **Action (Intent Adaptation):** The `_adapt_to_intent` methods are good. Consider if the `intent_parameters` dictionaries could be loaded from a configuration file or a shared constants module for easier management if they grow very large.
33
- * **Rationale:** Maximizes reuse of shared components, makes agents leaner and focused on their specific advocacy role (configuring shared tools).
34
-
35
- * **Centralized Intent Logic for Agents:**
36
- * **Action:** Reduce complex conditional intent handling within individual agents (`DiscoveryAgent`, `GenreMoodAgent`, `JudgeAgent`, `PlannerAgent`). Agents should receive a clear, pre-processed "effective intent" from a centralized service (see `IntentOrchestrationService` below).
37
- * **Rationale:** Simplifies agent logic, reduces bugs, and centralizes intent-related decision-making, making the system easier to maintain and extend.
38
-
39
- * **`PlannerAgent`:**
40
- * **Action (Query Understanding):** `QueryUnderstandingEngine` seems to be the core. Ensure it fully utilizes `LLMUtils`, `EntityExtractionUtils`, and `QueryAnalysisUtils`. The existing structure is good.
41
- * **Action (Context Handling Logic):** Methods like `_is_followup_with_preserved_context`, `_create_understanding_from_context`, `_create_entities_from_context`, `_extract_entity_names` are specific to interpreting and transforming conversation context. These could potentially be moved to `ConversationContextService` or a new `ContextTransformationUtils` if they are general enough, or kept if tightly coupled with planner's decision-making. For now, let's assume they are planner-specific but review if they are used elsewhere.
42
- * **Rationale:** Keeps planner focused on strategic planning, delegating detailed context interpretation.
43
-
44
- * **`JudgeAgent`:**
45
- * **Action (Ranking & Explanation):** Relies on `RankingLogic` and `ConversationalExplainer`. This is good. Ensure `ConversationalExplainer` uses `LLMUtils`.
46
- * **Action (Hybrid Subtype Detection):** The `_detect_hybrid_subtype` logic might be better placed within `QueryAnalysisUtils` or as part of the output from `QueryUnderstandingEngine`, as it's a core part of understanding the query's nuances.
47
- * **Action (Filtering Shown Tracks):** The `_filter_out_recently_shown` logic should ideally be a utility provided by `ConversationContextService` (e.g., `get_recommendations_excluding_seen(candidates, session_id)`).
48
- * **Rationale:** Centralizes query analysis and session-specific filtering.
49
-
50
- * **`src/agents/components/`:**
51
- * **Action (General):** These are crucial. Review all agents to ensure they are *maximally* leveraging these utilities. Any local regex, list manipulation for entities, or direct LLM call patterns outside `LLMUtils` should be questioned and likely refactored to use these components.
52
- * **`QualityScorer`:** The structure with sub-scorers and a `ComprehensiveQualityScorer` is good. Ensure it's the single point of entry for quality scoring.
53
- * **`UnifiedCandidateGenerator`:** Ensure it's flexible enough to handle all generation strategies required by advocate agents. The intent-aware generation logic is a good pattern.
54
- * **Rationale:** These components are the backbone of DRY for agent logic.
55
-
56
- ### 2. Services (`src/services/`)
57
-
58
- * **`EnhancedRecommendationService`:**
59
- * **Action:** This is the main orchestrator. Its primary role should be to manage the LangGraph workflow and interact with other services. Keep business logic minimal here; it should delegate.
60
- * **Action (Context Handling):** The `ContextAwareIntentAnalyzer` inside this service. This is a good place for the high-level decision of *how* to use context (e.g., is this a follow-up that needs special handling?). It should use `ConversationContextService` to fetch and update history.
61
- * **Action (Agent Initialization):** Ensure `initialize_agents` correctly passes shared instances of `APIService`, `MetadataService`, `CacheManager`, and `rate_limiter` to all agents.
62
- * **Rationale:** Clear separation of orchestration from core business logic.
63
- * **Action (Slimming Down):** Ensure complex context analysis (especially original intent tracking for follow-ups) is fully delegated to the enhanced `ConversationContextService` and the new `IntentOrchestrationService`.
64
- * **Rationale:** Keeps the orchestrator focused and delegates specialized tasks.
65
-
66
- * **`ConversationContextService` & `SmartContextManager`:**
67
- * There's an overlap. `ConversationContextService` in `conversation_context_service.py` seems to be the intended manager for session data. `SmartContextManager` in `smart_context_manager.py` contains logic for *deciding* context use.
68
- * **Action:**
69
- 1. Rename `ConversationContextService` to something more encompassing like `SessionManagerService` or `UserContextService`.
70
- 2. Merge the "smart" decision-making logic from `SmartContextManager` into this service or make `SmartContextManager` a sub-component that `EnhancedRecommendationService` consults. The goal is one primary service for all things related to user session and conversation context.
71
- 3. Ensure methods like `_extract_recently_shown_tracks` (currently in `EnhancedRecommendationService`) are part of this unified context service.
72
- * **Rationale:** Consolidates all context-related logic into a single, authoritative service.
73
- * **Action (Enhanced Context for Follow-ups):** This service (potentially renamed `SessionManagerService`) must store not just previous queries/recommendations, but also the *parsed original intent and entities* of earlier queries in the session. This is crucial for correct follow-up interpretation.
74
- * **Action (Candidate Pool Persistence for Follow-ups):** This service should manage (potentially with `CacheManager`) the persistence of a larger initial candidate pool generated by advocate agents. "More tracks" follow-ups would then instruct the `JudgeAgent` to draw from this existing pool.
75
- * **Rationale:** Enables accurate intent resolution for follow-ups and efficient "load more" style interactions.
76
-
77
- * **NEW: `IntentOrchestrationService` (Conceptual - could be merged or remain distinct):**
78
- * **Action:** Create a new service dedicated to advanced intent management, or significantly enhance `ContextAwareIntentAnalyzer` and `ConversationContextService` to cover these responsibilities.
79
- * **Responsibilities:**
80
- * Managing the full lifecycle of intent: initial detection via `QueryUnderstandingEngine`.
81
- * Storing the original query's intent and entities (working with `SessionManagerService`).
82
- * Accurately interpreting follow-up queries by considering the original intent (e.g., "more tracks" after "songs *by* X" vs. "songs *like* X").
83
- * Providing a clear, unambiguous "effective intent" to the `PlannerAgent` and subsequently to other agents for the current turn.
84
- * Centralizing the logic that handles variations in follow-up phrasing and ensures they map to the correct underlying original intent.
85
- * **Rationale:** Addresses the "hacky code" concern by creating a single source of truth for intent resolution, especially for complex follow-up scenarios. Drastically simplifies intent handling within individual agents.
86
-
87
- * **`APIService` & `MetadataService` & `CacheManager`:**
88
- * **Action:** These seem well-defined. Ensure `APIService` is the *only* way agents/services interact with external APIs (Last.fm, Spotify). `MetadataService` should be the sole provider of `UnifiedTrackMetadata`, potentially using `APIService` and `CacheManager`.
89
- * **Rationale:** Enforces a clean abstraction layer for external data and caching.
90
-
91
- * **`LLMFallbackService`:**
92
- * **Action:** This is a distinct concern and is fine as a separate service. Ensure it uses `LLMUtils` for its Gemini calls.
93
- * **Rationale:** Keeps fallback logic isolated.
94
-
95
- ### 3. API Layer (`src/api/`)
96
-
97
- * **`backend.py`:**
98
- * **Action:** The `transform_unified_to_ui_format` function is UI-specific. Move it to `src/ui/response_formatter.py` or a new `src/ui/ui_utils.py`. The backend should ideally return data in a consistent internal format, and the UI layer transforms it.
99
- * **Action:** Ensure all endpoints only call the `EnhancedRecommendationService` and do not contain business logic themselves.
100
- * **Rationale:** Keeps backend clean and focused on API contracts, decouples it from UI presentation details.
101
-
102
- * **Other API Files (`base_client.py`, `client_factory.py`, `lastfm_client.py`, `spotify_client.py`, `rate_limiter.py`, `logging_middleware.py`):**
103
- * **Action:** This structure is generally good. Ensure `LastFmClient` and `SpotifyClient` strictly adhere to `BaseAPIClient` and are always created via `APIClientFactory`. `UnifiedRateLimiter` is a good abstraction.
104
- * **Rationale:** Maintains consistency and reusability for external API interactions.
105
-
106
- ### 4. Models (`src/models/`)
107
-
108
- * **Action:** Review `agent_models.py`, `metadata_models.py`, `recommendation_models.py`.
109
- * Ensure `UnifiedTrackMetadata` and `UnifiedArtistMetadata` are the standard for passing track/artist data internally after fetching from external APIs.
110
- * `MusicRecommenderState` is the central state object for LangGraph, which is good.
111
- * Clarify if `TrackRecommendation` in `recommendation_models.py` is still needed or if `UnifiedTrackMetadata` (with its recommendation-specific fields) can serve that purpose. If `TrackRecommendation` is a UI-focused or Judge-output-focused model, ensure its distinction from `UnifiedTrackMetadata` is clear. It seems `TrackRecommendation` is used by `JudgeAgent`. This might be okay, but if it largely duplicates `UnifiedTrackMetadata`, consider merging or having it inherit. Given the current use, keeping it separate for the Judge's output and final UI presentation seems reasonable but ensure it's constructed from `UnifiedTrackMetadata`.
112
- * **Rationale:** Consistent data representation reduces errors and improves understanding.
113
-
114
- ### 5. UI Layer (`src/ui/`)
115
-
116
- * **Action:**
117
- * `BeatDebateChatInterface` should interact cleanly with the `/recommendations` and `/planning` endpoints.
118
- * The fallback logic in `BeatDebateChatInterface` using `LLMFallbackService` is good. Ensure the conditions for fallback (`_should_use_fallback`) are robust.
119
- * Move `transform_unified_to_ui_format` here from `backend.py` (as mentioned above).
120
- * **Rationale:** Separates UI concerns.
121
-
122
- ### 6. Tests (`tests/`)
123
-
124
-
125
- * **Action:** Consolidate `tests/agents/test_enhanced_judge.py` and `tests/agents/test_judge_agent.py` if they test the same current `JudgeAgent`. If `test_enhanced_judge.py` was for an older version, it could be archived or removed if its tests are covered.
126
- * **Rationale:** Better test organization.
127
-
128
- ### 6.5. Follow-up Query Enhancements & Candidate Caching
129
-
130
- * **Problem:** Follow-up queries like "more tracks" need to:
131
- 1. Correctly interpret intent based on the *original* query (e.g., "more tracks BY artist X" vs. "more tracks LIKE artist X").
132
- 2. Efficiently provide more results without expensive regeneration if possible.
133
- * **Action (Intent Tracking):** The `SessionManagerService` (enhanced `ConversationContextService`) will store the original parsed intent and entities of queries. The `IntentOrchestrationService` (or equivalent) will use this stored original intent to correctly interpret follow-up queries.
134
- * **Action (Candidate Pool Persistence & Reuse):**
135
- * Advocate agents (`DiscoveryAgent`, `GenreMoodAgent`), via `UnifiedCandidateGenerator`, will be capable of generating a larger initial pool of candidates (e.g., 50-100) if the `PlannerAgent` deems it appropriate (e.g., for intents likely to have "more like this" follow-ups).
136
- * This initial, unranked pool will be stored by the `SessionManagerService` (possibly using `CacheManager`) for the session's duration.
137
- * When a "more tracks" or similar follow-up occurs, and the `IntentOrchestrationService` confirms it's a continuation of the previous request:
138
- * The `JudgeAgent` will be instructed to pull additional candidates from this *persisted pool* rather than advocate agents re-generating.
139
- * The `JudgeAgent` will then apply its scoring, ranking, and diversity logic to the newly requested subset from the larger pool.
140
- * **Rationale:** Significantly improves user experience for follow-ups by providing contextually correct and efficiently loaded subsequent results. Reduces redundant API calls and processing.
141
-
142
- ### 7. Root Directory & Miscellaneous
143
-
144
- * **`TODO/todo.md`:**
145
- * **Action:** Review and integrate these TODOs into this refactoring plan or a subsequent one. The items "Enhanced Planner Agent", "Agent Improvements", "Enhanced Judge Agent" are covered by this plan.
146
- * **Logging:**
147
- * **Action:** `logging_config.py` and `logging.conf` provide good structured logging. Ensure all modules use `get_logger(__name__)` from `logging_config.py` for consistency.
148
- * **Rationale:** Centralized and consistent logging.
149
-
150
- ---
151
-
152
- **Code that is getting too large / needs most refactoring attention:**
153
-
154
- 1. **`src/agents/components/quality_scorer.py` (and its sub-components):** While modular with sub-scorers, the main file `comprehensive_quality_scorer.py` can be the orchestrator.
155
- * **Action (Reiteration):** Ensure individual scorer classes (e.g., `AudioQualityScorer`, `PopularityBalancer`, `EngagementScorer`, `GenreMoodFitScorer`, `IntentAwareScorer`) are in their own files within the `src/agents/components/scoring/` subdirectory. `ComprehensiveQualityScorer` acts as the composer.
156
- * **Rationale:** Improves readability and maintainability of individual scoring components.
157
-
158
- 2. **Advocate Agents (`src/agents/discovery/agent.py`, `src/agents/genre_mood/agent.py`):** These still contain significant internal logic for intent adaptation, filtering, and some aspects of scoring.
159
- * **Action:** With the new `IntentOrchestrationService`, the intent adaptation logic within these agents should be drastically simplified. They should receive a clear "effective intent".
160
- * **Action:** Push more of their specialized filtering or candidate manipulation logic into configurable strategies or utilities that `UnifiedCandidateGenerator` or the agents themselves can use, rather than large conditional blocks within the agent's `process` method.
161
- * **Rationale:** Makes agents thinner, more focused on configuring common tools based on a clear intent, and reduces duplicated or "hacky" conditional logic.
162
-
163
- 3. **`src/services/enhanced_recommendation_service.py`:** While it orchestrates the LangGraph flow, its direct business logic and context-handling should be minimal.
164
- * **Action:** Ensure it primarily delegates to `PlannerAgent` for planning, advocate agents for candidate generation, `JudgeAgent` for selection, and the new `IntentOrchestrationService` (or enhanced `ContextAwareIntentAnalyzer` + `SessionManagerService`) for all complex intent and context decisions.
165
- * **Rationale:** Keeps orchestration logic clean and focused on managing the workflow.
166
-
167
- 4. **`src/agents/planner/agent.py`:**
168
- * **Action:** If the context handling methods mentioned earlier (`_is_followup_with_preserved_context`, etc.) are deemed general enough, moving them to the unified `SessionManagerService` or `IntentOrchestrationService` would reduce this agent's size. Its role should be to take the "effective intent" and plan the agent sequence and high-level parameters.
169
- * **Rationale:** Centralizes context transformation and intent resolution logic.
170
-
171
- 5. **`src/agents/judge/agent.py`:**
172
- * **Action:** Its logic for handling "more tracks" follow-ups will need to be adapted to request candidates from the persisted pool managed by `SessionManagerService` when appropriate.
173
- * **Rationale:** Enables efficient "load more" functionality.
174
-
175
- 6. **`src/services/api_service.py`:**
176
- * **Action:** While generally well-structured, ensure it remains focused solely on external API interactions and does not creep into business logic related to candidate generation or scoring nuances that belong in agents or components. Review for any overly complex methods that could be simplified or broken down if they handle too many concerns.
177
- * **Rationale:** Maintains a clean separation of concerns for external API interactions.
178
-
179
- ---
180
-
181
- **Proposed Final Directory Structure (Illustrative Changes):**
182
-
183
- ```
184
- BeatDebate/
185
- ├── Design/
186
- ├── scripts/
187
- │ └── validate_lastfm.py
188
- ├── src/
189
- │ ├── agents/
190
- │ │ ├── base_agent.py
191
- │ │ ├── components/
192
- │ │ │ ├── __init__.py
193
- │ │ │ ├── entity_extraction_utils.py
194
- │ │ │ ├── llm_utils.py
195
- │ │ │ ├── query_analysis_utils.py
196
- │ │ │ ├── unified_candidate_generator.py
197
- │ │ │ ├── candidate_processor.py
198
- │ │ │ ├── scoring/
199
- │ │ │ │ ├── __init__.py
200
- │ │ │ │ ├── audio_quality_scorer.py
201
- │ │ │ │ ├── popularity_balancer.py
202
- │ │ │ │ ├── engagement_scorer.py
203
- │ │ │ │ ├── genre_mood_fit_scorer.py
204
- │ │ │ │ ├── intent_aware_scorer.py
205
- │ │ │ │ └── comprehensive_quality_scorer.py
206
- │ │ │ └── generation_strategies/
207
- │ │ │ ├── __init__.py
208
- │ │ │ ├── base_strategy.py
209
- │ │ │ ├── artist_strategies.py
210
- │ │ │ ├── genre_strategies.py
211
- │ │ │ ├── discovery_strategies.py
212
- │ │ │ ├── mood_strategies.py
213
- │ │ │ └── factory.py
214
- │ │ ├── planner/
215
- │ │ │ ├── __init__.py
216
- │ │ │ ├── agent.py
217
- │ │ │ ├── entity_recognizer.py
218
- │ │ │ └── query_understanding_engine.py
219
- │ │ ├── genre_mood/
220
- │ │ │ ├── __init__.py
221
- │ │ │ ├── agent.py
222
- │ │ │ ├── mood_logic.py
223
- │ │ │ └── tag_generator.py
224
- │ │ ├── discovery/
225
- │ │ │ ├── __init__.py
226
- │ │ │ ├── agent.py
227
- │ │ │ ├── similarity_explorer.py
228
- │ │ │ └── underground_detector.py
229
- │ │ └── judge/
230
- │ │ ├── __init__.py
231
- │ │ ├── agent.py
232
- │ │ ├── explainer.py
233
- │ │ └── ranking_logic.py
234
- │ ├── api/
235
- │ │ ├── __init__.py
236
- │ │ ├── backend.py
237
- │ │ ├── base_client.py
238
- │ │ ├── client_factory.py
239
- │ │ ├── lastfm_client.py
240
- │ │ ├── logging_middleware.py
241
- │ │ ├── rate_limiter.py
242
- │ │ └── spotify_client.py
243
- │ ├── models/
244
- │ │ ├── __init__.py
245
- │ │ ├── agent_models.py
246
- │ │ ├── metadata_models.py
247
- │ │ └── recommendation_models.py
248
- │ ├── services/
249
- │ │ ├── __init__.py
250
- │ │ ├── api_service.py # ✅ REFACTORED (1,554 → 350 lines, 77% reduction)
251
- │ │ ├── cache_manager.py
252
- │ │ ├── recommendation_service.py # ✅ REFACTORED (enhanced_recommendation_service)
253
- │ │ ├── session_manager_service.py # ✅ RENAMED from conversation_context_service
254
- │ │ ├── intent_orchestration_service.py # ✅ NEW service for intent management
255
- │ │ ├── metadata_service.py
256
- │ │ ├── components/ # ✅ NEW modular service components
257
- │ │ │ ├── __init__.py
258
- │ │ │ ├── client_manager.py # API client management
259
- │ │ │ ├── track_operations.py # Track search and metadata
260
- │ │ │ ├── artist_operations.py # Artist info and operations
261
- │ │ │ ├── genre_analyzer.py # Genre matching and analysis
262
- │ │ │ ├── context_handler.py # Context analysis (from recommendation service)
263
- │ │ │ ├── agent_coordinator.py # Agent initialization (from recommendation service)
264
- │ │ │ ├── workflow_orchestrator.py # LangGraph workflow (from recommendation service)
265
- │ │ │ └── state_manager.py # State management (from recommendation service)
266
- │ │ # Removed smart_context_manager.py (logic merged into session_manager_service)
267
- │ ├── ui/
268
- │ │ ├── __init__.py
269
- │ │ ├── chat_interface.py
270
- │ │ ├── planning_display.py
271
- │ │ ├── response_formatter.py
272
- │ │ └── ui_utils.py # New for UI-specific transformations
273
- │ ├── utils/
274
- │ │ ├── __init__.py
275
- │ │ └── logging_config.py
276
- │ ├── __init__.py
277
- │ └── main.py
278
- ├── tests/
279
- │ ├── agents/
280
- │ │ ├── test_advocate_agents.py # Could be split into test_genre_mood.py, test_discovery.py
281
- │ │ ├── test_enhanced_planner.py
282
- │ │ ├── test_judge_agent.py # Consolidated judge tests
283
- │ │ └── test_planner_agent.py
284
- │ ├── services/
285
- │ │ ├── __init__.py
286
- │ │ ├── test_enhanced_recommendation_service.py
287
- │ │ ├── test_llm_fallback_service.py
288
- │ │ ├── test_recommendation_engine_integration.py
289
- │ │ └── test_recommendation_engine.py
290
- │ ├── ui/
291
- │ │ └── test_chat_interface_fallback.py
292
- │ ├── integration/ # New for broader integration tests
293
- │ │ ├── test_intent_aware_backend_integration.py
294
- │ │ └── test_phase3_demo.py
295
- │ └── scenarios/ # New for specific scenario tests
296
- │ ├── test_followup_behavior.py
297
- │ ├── test_followup_detection_fix.py
298
- │ ├── test_history_filtering.py
299
- │ ├── test_hybrid_context.py
300
- │ ├── test_kendrick_followup.py
301
- │ ├── test_simple_extraction.py
302
- │ └── test_state_fix.py
303
- ├── TODO/
304
- │ └── todo.md # To be updated or removed after refactoring
305
- ├── .flake8
306
- ├── .gitignore
307
- ├── app.py
308
- ├── env.example
309
- ├── logging.conf
310
- ├── pyproject.toml
311
- ├── README.md
312
- └── requirements.txt
313
- ```
314
-
315
- ---
316
-
317
- **Proposed Refactoring Progression**
318
-
319
- Here's a suggested way to progress through this refactoring plan, focusing on building foundational pieces first:
320
-
321
- **Phase 1: Strengthen the Core - Context and Intent Services**
322
-
323
- * **Goal:** Establish robust services for managing conversation context and resolving user intent, especially for follow-ups.
324
- * **Key Actions from `TODO.md`:**
325
- 1. **Refactor `ConversationContextService` into `SessionManagerService`**:
326
- * Implement storage for the *original parsed intent and entities* of previous queries.
327
- * Add capabilities to store and retrieve a larger, unranked candidate pool generated by advocate agents (for "more tracks" scenarios).
328
- 2. **Develop `IntentOrchestrationService`** (or significantly enhance `ContextAwareIntentAnalyzer` within `EnhancedRecommendationService` and integrate its logic with `SessionManagerService`):
329
- * Focus on accurately identifying follow-up queries.
330
- * Implement logic to retrieve the stored original intent/entities from `SessionManagerService`.
331
- * Develop the core mechanism to determine the "effective intent" for the current turn, especially differentiating "more tracks *by* X" from "more tracks *like* X" based on the original query's intent.
332
-
333
- **Phase 2: Adapt Agents to the New Intent Paradigm**
334
-
335
- * **Goal:** Simplify agents by having them consume the "effective intent" from the centralized service.
336
- * **Key Actions from `TODO.md`:**
337
- 1. **Modify `PlannerAgent`**:
338
- * Update it to receive and use the "effective intent" from `IntentOrchestrationService`.
339
- * Delegate more of its specific context-handling logic to `SessionManagerService` and `IntentOrchestrationService`.
340
- 2. **Modify Advocate Agents (`DiscoveryAgent`, `GenreMoodAgent`)**:
341
- * Simplify their internal intent adaptation logic (e.g., `_adapt_to_intent` methods) to rely on the clear "effective intent".
342
- * Modify `UnifiedCandidateGenerator` to support generating a larger initial candidate pool when directed by the `PlannerAgent` (useful for intents prone to "load more" type follow-ups).
343
- 3. **Modify `JudgeAgent`**:
344
- * Adapt its logic to request additional candidates from the persisted pool (managed by `SessionManagerService`) for relevant follow-up queries, instead of always triggering full regeneration.
345
-
346
- **Phase 3: Implement Efficient Follow-up Candidate Handling**
347
-
348
- * **Goal:** Enable the "load more" functionality by using persisted candidate pools.
349
- * **Key Actions from `TODO.md`:**
350
- 1. **Integrate Candidate Pool Persistence**:
351
- * Ensure `UnifiedCandidateGenerator` (via advocate agents) can store its larger initial candidate pool in `SessionManagerService` (potentially using `CacheManager`).
352
- 2. **Refine Follow-up Workflow**:
353
- * Solidify the interaction between `IntentOrchestrationService`, `PlannerAgent` (to decide if a large pool is needed), advocate agents (to generate it), `SessionManagerService` (to store/retrieve it), and `JudgeAgent` (to use it for "more tracks" style follow-ups).
354
-
355
- **Phase 4: Deep Dive into Modularization and Code Health** ⚡ **IN PROGRESS**
356
-
357
- * **Goal:** Address the large code files and ensure adherence to DRY and SRP.
358
-
359
- ### ✅ **Phase 4.1: DiscoveryAgent Refactoring - COMPLETE**
360
- **Status**: Successfully refactored from 86,725 bytes (1,680 lines) to 15,072 bytes (~400 lines) - **82.6% reduction**
361
-
362
- **Components Created**:
363
- - ✅ `DiscoveryConfig` (14,117 bytes) - Intent parameter management
364
- - ✅ `DiscoveryScorer` (13,788 bytes) - Discovery-specific scoring logic
365
- - ✅ `DiscoveryFilter` (16,026 bytes) - Discovery-specific filtering
366
- - ✅ `DiscoveryDiversity` (14,133 bytes) - Diversity management
367
- - ✅ `agent_refactored.py` (15,072 bytes) - Modular main agent
368
-
369
- **Benefits Achieved**:
370
- - Single responsibility principle applied
371
- - Better testability and maintainability
372
- - Reusable components for other agents
373
- - Validated through comprehensive testing
374
-
375
- ### ✅ **Phase 4.2: EnhancedRecommendationService Refactoring - COMPLETE**
376
- **Status**: Successfully refactored from 72KB (1,792 lines) to 21KB (527 lines) - **70.6% reduction**
377
-
378
- **Components Created**:
379
- - ✅ `ContextHandler` (26KB, 600 lines) - Context analysis and processing
380
- - ✅ `AgentCoordinator` (9KB, 240 lines) - Agent initialization and coordination
381
- - ✅ `WorkflowOrchestrator` (12KB, 311 lines) - LangGraph workflow management
382
- - ✅ `StateManager` (16KB, 382 lines) - MusicRecommenderState management
383
- - ✅ `enhanced_recommendation_service_refactored.py` (21KB, 527 lines) - Lean main service
384
-
385
- **Benefits Achieved**:
386
- - Single responsibility principle applied across all components
387
- - Clear separation of concerns (context vs agents vs workflow vs state)
388
- - Improved testability with isolated components
389
- - Better maintainability through modular architecture
390
- - Validated through successful component import and creation tests
391
-
392
- ### ✅ **Phase 4.3: PlannerAgent Refactoring - COMPLETE**
393
- **Status**: Successfully refactored from 50KB (1,276 lines) to 16KB (374 lines) - **68.2% reduction**
394
-
395
- **Components Created**:
396
- - ✅ `QueryAnalyzer` (11KB, 323 lines) - Query understanding and parsing
397
- - ✅ `ContextAnalyzer` (20KB, 465 lines) - Context interpretation and transformation
398
- - ✅ `StrategyPlanner` (19KB, 520 lines) - Agent strategy and parameter planning
399
- - ✅ `EntityProcessor` (16KB, 389 lines) - Entity extraction and processing
400
- - ✅ `planner_agent_refactored.py` (16KB, 374 lines) - Lean main planner
401
-
402
- **Benefits Achieved**:
403
- - Single responsibility principle applied across all components
404
- - Clear separation of concerns (query vs context vs strategy vs entities)
405
- - Improved testability with isolated components
406
- - Better maintainability through modular architecture
407
- - Comprehensive backward compatibility for existing code
408
-
409
- ### ✅ **Phase 4.4: JudgeAgent & RankingLogic Refactoring - COMPLETE**
410
- **Status**: Successfully refactored from 115KB (2,586 lines) to 17KB (374 lines) - **85.2% reduction**
411
-
412
- **Components Created**:
413
- - ✅ `RankingEngine` (20KB, 475 lines) - Core ranking algorithms and scoring
414
- - ✅ `ExplanationGenerator` (19KB, 464 lines) - Enhanced explanation and reasoning logic
415
- - ✅ `CandidateSelector` (19KB, 455 lines) - Candidate selection and filtering logic
416
- - ✅ `DiversityOptimizer` (16KB, 407 lines) - Final diversity optimization
417
- - ✅ `judge_agent_refactored.py` (17KB, 374 lines) - Lean main judge
418
-
419
- **Benefits Achieved**:
420
- - Single responsibility principle applied across all components
421
- - Clear separation of concerns (ranking vs explanation vs selection vs diversity)
422
- - Improved testability with isolated components
423
- - Better maintainability through modular architecture
424
- - Excellent size reduction (85.2%) in main agent file
425
-
426
- ### ✅ **Phase 4.5: GenreMoodAgent Refactoring - COMPLETE**
427
- **Status**: Successfully refactored from 42KB (895 lines) to 23KB (509 lines) - **45.9% reduction**
428
-
429
- **Components Created**:
430
- - ✅ `GenreMoodConfig` (9KB, 210 lines) - Intent parameter management and configuration
431
- - ✅ `MoodAnalyzer` (11KB, 275 lines) - Mood detection, analysis, and mapping logic
432
- - ✅ `GenreProcessor` (14KB, 339 lines) - Genre matching, filtering, and processing
433
- - ✅ `TagGenerator` (10KB, 290 lines) - Tag generation, extraction, and enhancement
434
- - ✅ `genre_mood_agent_refactored.py` (23KB, 509 lines) - Lean main agent
435
-
436
- **Benefits Achieved**:
437
- - Single responsibility principle applied across all components
438
- - Clear separation of concerns (config vs mood vs genre vs tags)
439
- - Improved testability with isolated components
440
- - Better maintainability through modular architecture
441
- - Comprehensive component validation and successful testing
442
-
443
- ### ✅ **Phase 4.6: APIService Refactoring - COMPLETE**
444
- **Status**: Successfully refactored from 59KB (1,554 lines) to 11KB (350 lines) - **77.4% reduction**
445
-
446
- **Components Created**:
447
- - ✅ `ClientManager` (5.7KB, 175 lines) - API client instantiation and session management
448
- - ✅ `TrackOperations` (14KB, 374 lines) - Track search, metadata retrieval, similar tracks
449
- - ✅ `ArtistOperations` (9.9KB, 282 lines) - Artist info, top tracks, similar artists
450
- - ✅ `GenreAnalyzer` (31KB, 770 lines) - Genre matching, relationship checking, LLM analysis
451
- - ✅ `api_service_refactored.py` (11KB, 350 lines) - Lean orchestrator service
452
-
453
- **Benefits Achieved**:
454
- - Single responsibility principle applied across all components
455
- - Clear separation of concerns (client vs track vs artist vs genre operations)
456
- - Improved testability with isolated components
457
- - Better maintainability through modular architecture
458
- - Comprehensive testing and validation completed
459
-
460
- ### ✅ **Phase 4.7: Scoring Component Modularization - ALREADY COMPLETE**
461
- **Status**: Already properly modularized in `src/agents/components/scoring/`
462
- - ✅ Individual scorer classes in separate files
463
- - ✅ `ComprehensiveQualityScorer` as main orchestrator
464
- - ✅ Clean imports and exports in `__init__.py`
465
-
466
- **Current Phase 4 Impact** (All Phases Complete):
467
- - **Before**: DiscoveryAgent (86KB) + EnhancedRecommendationService (72KB) + PlannerAgent (50KB) + JudgeAgent (115KB) + GenreMoodAgent (42KB) + APIService (59KB) = 424KB
468
- - **After**: Modularized components totaling 92KB for main services/agents
469
- - **Achieved Reduction**: 78.3% across all completed components
470
-
471
- **Final Phase 4 Impact**:
472
- - **Before Phase 4**: 424KB in large monolithic files
473
- - **After Phase 4**: 92KB in modular components + 61KB in specialized components = 153KB total
474
- - **Overall Reduction**: 63.9% across all major components
475
- - **Maintainability**: Massive improvement through modularization
476
- - **Component Count**: 20+ specialized, focused components created
477
-
478
- **Phase 5: Testing, UI Adaptation, and Iteration**
479
-
480
- * **Goal:** Ensure all changes are robust, user-facing aspects are consistent, and gather feedback for further refinement.
481
- * **Key Actions from `TODO.md`:**
482
- 1. **Comprehensive Testing**:
483
- * Write new unit and integration tests for the new services (`SessionManagerService`, `IntentOrchestrationService`) and modified agent interactions.
484
- * Create specific scenario tests (in `tests/scenarios/`) for various follow-up queries (e.g., "more by X", "more like X", "more like these but upbeat") to validate correct intent handling and candidate pool reuse.
485
- 2. **UI Review**: Check if `BeatDebateChatInterface` needs any adjustments to how it displays or handles sequences of recommendations, especially with the "load more" style follow-ups.
486
- 3. **Review and Iterate**: Based on testing and usage, identify any remaining areas for improvement in clarity, efficiency, or intent handling.
487
-
488
- ---
489
-
490
- ## 📊 **CURRENT STATUS - Updated After Phase 4.4**
491
-
492
- ### **Phases Completed** ✅
493
- - ✅ **Phase 1**: Enhanced SessionManagerService and IntentOrchestrationService
494
- - ✅ **Phase 2**: Simplified agents to use "effective intent"
495
- - ✅ **Phase 3**: Implemented efficient follow-up candidate handling
496
- - ✅ **Phase 4.1**: DiscoveryAgent refactoring (82.6% size reduction)
497
- - ✅ **Phase 4.2**: EnhancedRecommendationService refactoring (70.6% size reduction)
498
- - ✅ **Phase 4.3**: PlannerAgent refactoring (68.2% size reduction)
499
- - ✅ **Phase 4.4**: JudgeAgent refactoring (85.2% size reduction)
500
- - ✅ **Phase 4.5**: GenreMoodAgent refactoring (45.9% size reduction)
501
- - ✅ **Phase 4.6**: APIService refactoring (77.4% size reduction)
502
-
503
- ### **Phase 4 Status** ✅ **COMPLETE**
504
- All major agent and service refactoring completed successfully!
505
-
506
- ### **Ready for Phase 5** 🚀
507
- After Phase 4 completion:
508
- - Comprehensive testing of all refactored components
509
- - UI adaptations for modular architecture
510
- - Performance validation and benchmarking
511
- - Integration testing across all phases
512
-
513
- ### **Key Achievements - Phase 4 Complete** 🎉
514
- - **Phase 4.1**: DiscoveryAgent refactored (82.6% reduction - 86KB → 15KB)
515
- - **Phase 4.2**: EnhancedRecommendationService refactored (70.6% reduction - 72KB → 21KB)
516
- - **Phase 4.3**: PlannerAgent refactored (68.2% reduction - 50KB → 16KB)
517
- - **Phase 4.4**: JudgeAgent refactored (85.2% reduction - 115KB → 17KB)
518
- - **Phase 4.5**: GenreMoodAgent refactored (45.9% reduction - 42KB → 23KB)
519
- - **Phase 4.6**: APIService refactored (77.4% reduction - 59KB → 11KB)
520
- - **Overall Impact**: 424KB → 103KB across all major components (75.7% total reduction)
521
- - **Code Health**: Dramatic size reductions while maintaining functionality
522
- - **Modularity**: Proven template for component extraction working excellently
523
- - **Maintainability**: Single responsibility principle applied consistently
524
- - **Testability**: Independent component validation and successful integration
525
- - **Performance**: Retained all functionality with superior architecture
526
-
527
- ### ✅ **Phase 4.8: UnifiedCandidateGenerator Refactoring - FULLY COMPLETED** ✅
528
-
529
- * **Status**: ✅ **FULLY COMPLETED** - All bugs eliminated, system working perfectly
530
- * **Problem Fixed**: `src/agents/components/unified_candidate_generator.py` was a monolithic "god class" of over 1400 lines with multiple critical issues:
531
- * ✅ **Critical Bug ELIMINATED**: `AttributeError: 'str' object has no attribute 'value'` - **COMPLETELY RESOLVED**
532
- * ✅ **Missing Enum FIXED**: `HYBRID_ARTIST_GENRE` intent causing initialization failures - **RESOLVED**
533
- * ✅ **Entity Format Mismatch FIXED**: Strategy now correctly handles `musical_entities.artists.primary` format - **RESOLVED**
534
- * ✅ **Metadata Model FIXED**: Fixed `.value` attribute errors in `to_dict()` methods - **RESOLVED**
535
- * ✅ **Judge Agent IMPROVED**: Better track validation for underground/new tracks - **RESOLVED**
536
- * **Goal Achieved**: Successfully refactored into a lean orchestrator (~400 lines, 71% reduction) with specialized, type-safe components.
537
-
538
- **✅ FINAL SUCCESS METRICS:**
539
- - ✅ **Zero Runtime Errors**: Error logs completely empty
540
- - ✅ **Working Recommendations**: System successfully generates Mk.gee recommendations
541
- - ✅ **Type Safety**: Complete elimination of string/enum confusion
542
- - ✅ **Modular Architecture**: 9 specialized strategy classes + factory + processor
543
- - ✅ **Backward Compatibility**: All existing code paths preserved
544
- - ✅ **Code Quality**: 71% size reduction while fixing critical bugs
545
-
546
- **Proposed Components & Architecture:**
547
-
548
- The refactoring will be based on the **Strategy Pattern**. Each distinct candidate generation logic will be encapsulated in its own "strategy" class.
549
-
550
- 1. **New Directory**: `src/agents/components/generation_strategies/`
551
- * This will house all the new strategy components.
552
-
553
- 2. **Base Strategy Class**: `src/agents/components/generation_strategies/base_strategy.py`
554
- * **Action**: Create an abstract base class `BaseGenerationStrategy` with a common interface, e.g., `async def generate(self, entities, intent_analysis, **kwargs) -> List[Dict[str, Any]]:`.
555
- * **Rationale**: Enforces a consistent contract for all generation strategies.
556
-
557
- 3. **Concrete Strategy Classes**: `src/agents/components/generation_strategies/`
558
- * **Action**: Create separate classes for each generation method, inheriting from `BaseGenerationStrategy`. Logic from the large `if/elif` block in `_generate_intent_aware_candidates` and other generation methods will be moved into these classes.
559
- * `artist_strategies.py`: `TargetArtistStrategy`, `SimilarArtistStrategy`
560
- * `genre_strategies.py`: `GenreExplorationStrategy`, `GenreFocusedStrategy`, `RandomGenreStrategy`
561
- * `discovery_strategies.py`: `UndergroundGemsStrategy`, `SerendipitousDiscoveryStrategy`
562
- * `mood_strategies.py`: `MoodBasedSerendipityStrategy`, `MoodFilteredTracksStrategy`
563
- * ... and so on for all other strategies.
564
- * **Rationale**: Isolates each strategy, making them independently testable and easier to manage. Adheres to SRP.
565
-
566
- 4. **Strategy Factory**: `src/agents/components/generation_strategies/factory.py`
567
- * **Action**: Create a `StrategyFactory` that takes an intent (as a `QueryIntent` enum, not a string) and returns the corresponding strategy instance(s). This factory will contain the mapping between intents and strategies.
568
- * **Rationale**: Decouples the `UnifiedCandidateGenerator` from the concrete strategy implementations. Centralizes the selection logic. **This is key to fixing the bug**, as the factory will enforce the use of the `QueryIntent` enum, ensuring type safety.
569
-
570
- 5. **Candidate Processor**: `src/agents/components/candidate_processor.py` (or similar name)
571
- * **Action**: Move utility functions like `_finalize_candidates`, `_filter_recently_shown_tracks`, `_deduplicate_candidates`, and `_convert_metadata_to_dict` into a dedicated processor class or module.
572
- * **Rationale**: Separates the concern of post-processing candidates from generating them.
573
-
574
- 6. **Entity Extraction Utils**:
575
- * **Action**: The various `_extract_*` methods (`_extract_seed_artists`, `_extract_target_genres`) are utility functions. They should be moved to a relevant utility module like `src/agents/components/entity_extraction_utils.py` if they are not already there.
576
- * **Rationale**: Consolidates entity extraction logic.
577
-
578
- 7. **Refactored `UnifiedCandidateGenerator`**: `src/agents/components/unified_candidate_generator.py`
579
- * **Action**: The `UnifiedCandidateGenerator` class will be significantly slimmed down. Its primary role will be to:
580
- 1. Use the `StrategyFactory` to get the correct strategy for the given intent.
581
- 2. Execute the strategy to get a raw list of candidates.
582
- 3. Use the `CandidateProcessor` to clean, deduplicate, and finalize the candidates.
583
- * **Rationale**: Transforms the "god class" into a clean orchestrator, adhering to SRP.
584
-
585
- **Benefits of this Refactoring**:
586
- * **Bug Fix**: Enforces the use of `QueryIntent` enum via the factory, eliminating the `str` vs. `enum` ambiguity and fixing the `'str' object has no attribute 'value'` error.
587
- * **Maintainability**: Small, focused components are easier to understand and modify than a single, massive file.
588
- * **Testability**: Each strategy can be unit-tested in isolation.
589
- * **Extensibility**: Adding a new candidate generation strategy becomes as simple as creating a new strategy class and registering it in the factory, without touching the existing logic.
590
- * **Readability**: The orchestrator's logic will become straightforward and easy to follow.
591
-
592
- ---
593
-
594
- This plan provides a structured approach. The successful Phase 4.1 refactoring proves the modular approach works excellently. Each subsequent phase will follow the same pattern of extracting specialized components while maintaining functionality and improving code quality.