omnispindle 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ """
2
+ AI-powered Todo Assistant for FastMCP Todo Server
3
+
4
+ This module provides AI-powered features for the todo application, including:
5
+ - Pattern analysis of completed todos
6
+ - Automated suggestions for routine tasks
7
+ - Priority recommendations based on past behavior
8
+ - Task grouping and organization suggestions
9
+ """
10
+
11
+ import json
12
+ import logging
13
+ import os
14
+ from datetime import datetime, timedelta, UTC
15
+ from typing import Dict, List, Any
16
+
17
+ from pymongo import MongoClient
18
+ from sklearn.feature_extraction.text import TfidfVectorizer
19
+ from sklearn.cluster import DBSCAN
20
+ from collections import Counter
21
+
22
+ # Configure logger
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Load MongoDB connection from environment
26
+ MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://localhost:27017")
27
+ MONGODB_DB = os.getenv("MONGODB_DB", "swarmonomicon")
28
+ MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION", "todos")
29
+
30
+ # Create MongoDB connection
31
+ mongo_client = MongoClient(MONGODB_URI)
32
+ db = mongo_client[MONGODB_DB]
33
+ collection = db[MONGODB_COLLECTION]
34
+
35
+
36
+ class TodoAssistant:
37
+ """AI-powered Todo Assistant that learns from past todos and suggests improvements"""
38
+
39
+ def __init__(self):
40
+ """Initialize the Todo Assistant"""
41
+ self.completed_todos = []
42
+ self.pending_todos = []
43
+ self.patterns = {}
44
+ self.last_refresh = None
45
+ logger.info("Todo Assistant initialized")
46
+
47
+ def refresh_data(self) -> None:
48
+ """Fetch fresh todo data from the database"""
49
+ logger.debug("Refreshing todo data from database")
50
+ try:
51
+ # Get completed todos
52
+ self.completed_todos = list(collection.find({"status": "completed"}))
53
+
54
+ # Get pending todos
55
+ self.pending_todos = list(collection.find({"status": "pending"}))
56
+
57
+ self.last_refresh = datetime.now(UTC)
58
+ logger.info(f"Refreshed data: {len(self.completed_todos)} completed todos, {len(self.pending_todos)} pending todos")
59
+ except Exception as e:
60
+ logger.error(f"Error refreshing todo data: {e}")
61
+
62
+ def analyze_patterns(self) -> Dict[str, Any]:
63
+ """
64
+ Analyze patterns in completed todos to identify routine tasks
65
+
66
+ Returns:
67
+ Dict containing analysis results and patterns found
68
+ """
69
+ if not self.completed_todos or (self.last_refresh and (datetime.now(UTC) - self.last_refresh) > timedelta(minutes=30)):
70
+ self.refresh_data()
71
+
72
+ if len(self.completed_todos) < 5:
73
+ logger.warning("Not enough completed todos for meaningful pattern analysis")
74
+ return {"status": "insufficient_data", "message": "Need at least 5 completed todos for analysis"}
75
+
76
+ try:
77
+ logger.info("Starting pattern analysis on completed todos")
78
+
79
+ # Extract descriptions
80
+ descriptions = [todo.get("description", "") for todo in self.completed_todos]
81
+
82
+ # Create TF-IDF vectors for text similarity
83
+ vectorizer = TfidfVectorizer(max_features=100, stop_words='english')
84
+ tfidf_matrix = vectorizer.fit_transform(descriptions)
85
+
86
+ # Cluster similar todos
87
+ dbscan = DBSCAN(eps=0.5, min_samples=2)
88
+ clusters = dbscan.fit_predict(tfidf_matrix)
89
+
90
+ # Find patterns
91
+ patterns = {}
92
+ for i, cluster_id in enumerate(clusters):
93
+ if cluster_id != -1: # -1 means no cluster assigned
94
+ if cluster_id not in patterns:
95
+ patterns[cluster_id] = []
96
+
97
+ patterns[cluster_id].append({
98
+ "id": self.completed_todos[i].get("id", "unknown"),
99
+ "description": descriptions[i],
100
+ "created_at": self.completed_todos[i].get("created_at"),
101
+ "completed_at": self.completed_todos[i].get("completed_at"),
102
+ "priority": self.completed_todos[i].get("priority", "medium"),
103
+ "target_agent": self.completed_todos[i].get("target_agent", "user")
104
+ })
105
+
106
+ # Store patterns
107
+ self.patterns = patterns
108
+
109
+ # Calculate statistics
110
+ total_patterns = sum(len(items) for items in patterns.values())
111
+ num_clusters = len(patterns)
112
+
113
+ logger.info(f"Pattern analysis complete: found {num_clusters} patterns across {total_patterns} todos")
114
+
115
+ return {
116
+ "status": "success",
117
+ "patterns": patterns,
118
+ "pattern_count": num_clusters,
119
+ "clustered_todos": total_patterns,
120
+ "total_completed": len(self.completed_todos)
121
+ }
122
+
123
+ except Exception as e:
124
+ logger.error(f"Error in pattern analysis: {e}")
125
+ return {"status": "error", "message": str(e)}
126
+
127
+ def suggest_automation(self) -> List[Dict[str, Any]]:
128
+ """
129
+ Suggest routine tasks that could be automated based on patterns
130
+
131
+ Returns:
132
+ List of dictionaries with automation suggestions
133
+ """
134
+ if not self.patterns:
135
+ self.analyze_patterns()
136
+
137
+ suggestions = []
138
+
139
+ # Find patterns with consistent properties worth automating
140
+ for cluster_id, todos in self.patterns.items():
141
+ if len(todos) >= 3: # Need at least 3 examples to suggest automation
142
+ # Check if target agent is consistent
143
+ target_agents = [todo["target_agent"] for todo in todos]
144
+ agent_counter = Counter(target_agents)
145
+ primary_agent = agent_counter.most_common(1)[0][0]
146
+ agent_consistency = agent_counter[primary_agent] / len(todos)
147
+
148
+ # Check if priority is consistent
149
+ priorities = [todo["priority"] for todo in todos]
150
+ priority_counter = Counter(priorities)
151
+ primary_priority = priority_counter.most_common(1)[0][0]
152
+ priority_consistency = priority_counter[primary_priority] / len(todos)
153
+
154
+ # Calculate average time to completion (if available)
155
+ completion_times = []
156
+ for todo in todos:
157
+ if todo.get("created_at") and todo.get("completed_at"):
158
+ completion_time = todo["completed_at"] - todo["created_at"]
159
+ if completion_time > 0:
160
+ completion_times.append(completion_time)
161
+
162
+ avg_completion_time = sum(completion_times) / len(completion_times) if completion_times else None
163
+
164
+ # Create a template based on common words
165
+ descriptions = [todo["description"] for todo in todos]
166
+ common_words = self._extract_common_words(descriptions)
167
+ template = " ".join(common_words) if common_words else descriptions[0]
168
+
169
+ # Determine if this cluster is worth automating
170
+ automation_score = (agent_consistency + priority_consistency) / 2
171
+ should_automate = automation_score > 0.7 and len(todos) >= 3
172
+
173
+ if should_automate:
174
+ suggestion = {
175
+ "pattern_id": str(cluster_id),
176
+ "similar_tasks": len(todos),
177
+ "template": template,
178
+ "suggested_agent": primary_agent,
179
+ "suggested_priority": primary_priority,
180
+ "automation_confidence": round(automation_score * 100, 2),
181
+ "avg_completion_time": avg_completion_time,
182
+ "examples": [todo["description"] for todo in todos[:3]]
183
+ }
184
+ suggestions.append(suggestion)
185
+
186
+ logger.info(f"Generated {len(suggestions)} automation suggestions")
187
+ return suggestions
188
+
189
+ def recommend_priorities(self) -> List[Dict[str, Any]]:
190
+ """
191
+ Recommend priority changes for pending todos based on similar completed todos
192
+
193
+ Returns:
194
+ List of dictionaries with priority recommendations
195
+ """
196
+ if not self.completed_todos or not self.pending_todos:
197
+ self.refresh_data()
198
+
199
+ recommendations = []
200
+
201
+ # Create vectorizer from completed todos
202
+ completed_descriptions = [todo.get("description", "") for todo in self.completed_todos]
203
+ if not completed_descriptions:
204
+ return recommendations
205
+
206
+ vectorizer = TfidfVectorizer(max_features=100, stop_words='english')
207
+ completed_vectors = vectorizer.fit_transform(completed_descriptions)
208
+
209
+ # For each pending todo, find similar completed todos
210
+ for pending in self.pending_todos:
211
+ try:
212
+ pending_desc = pending.get("description", "")
213
+ if not pending_desc:
214
+ continue
215
+
216
+ # Transform pending todo using same vectorizer
217
+ pending_vector = vectorizer.transform([pending_desc])
218
+
219
+ # Calculate similarity with all completed todos
220
+ from sklearn.metrics.pairwise import cosine_similarity
221
+ similarities = cosine_similarity(pending_vector, completed_vectors).flatten()
222
+
223
+ # Get the indices of the top 3 most similar todos
224
+ top_indices = similarities.argsort()[-3:][::-1]
225
+
226
+ # Only consider valid similarities
227
+ valid_matches = [(i, s) for i, s in zip(top_indices, similarities[top_indices]) if s > 0.3]
228
+
229
+ if valid_matches:
230
+ # Get the priorities of the similar todos
231
+ similar_priorities = [self.completed_todos[i].get("priority", "medium") for i, _ in valid_matches]
232
+ priority_counter = Counter(similar_priorities)
233
+ recommended_priority = priority_counter.most_common(1)[0][0]
234
+
235
+ # Only recommend if it's different from current priority
236
+ current_priority = pending.get("priority", "medium")
237
+ if recommended_priority != current_priority:
238
+ recommendation = {
239
+ "todo_id": pending.get("id"),
240
+ "description": pending_desc,
241
+ "current_priority": current_priority,
242
+ "recommended_priority": recommended_priority,
243
+ "confidence": round((sum(s for _, s in valid_matches) / len(valid_matches)) * 100, 2),
244
+ "similar_tasks": len(valid_matches)
245
+ }
246
+ recommendations.append(recommendation)
247
+ except Exception as e:
248
+ logger.error(f"Error processing recommendation for todo {pending.get('id')}: {e}")
249
+
250
+ logger.info(f"Generated {len(recommendations)} priority recommendations")
251
+ return recommendations
252
+
253
+ def _extract_common_words(self, texts: List[str], min_word_length: int = 4) -> List[str]:
254
+ """
255
+ Extract words that appear in multiple text descriptions
256
+
257
+ Args:
258
+ texts: List of text descriptions
259
+ min_word_length: Minimum length of words to consider
260
+
261
+ Returns:
262
+ List of common words
263
+ """
264
+ # Tokenize and count word occurrences
265
+ all_words = []
266
+ for text in texts:
267
+ words = [w.lower() for w in text.split() if len(w) >= min_word_length]
268
+ all_words.extend(words)
269
+
270
+ word_counter = Counter(all_words)
271
+
272
+ # Words that appear in at least 50% of descriptions
273
+ min_occurrences = max(2, len(texts) // 2)
274
+ common_words = [word for word, count in word_counter.items() if count >= min_occurrences]
275
+
276
+ return common_words
277
+
278
+
279
+ # Create singleton instance
280
+ assistant = TodoAssistant()
281
+
282
+
283
+ async def get_todo_suggestions() -> str:
284
+ """
285
+ Get AI-powered suggestions for todos based on pattern analysis
286
+
287
+ Returns:
288
+ JSON string with todo suggestions
289
+ """
290
+ try:
291
+ assistant.refresh_data()
292
+
293
+ # Get automation suggestions
294
+ automation_suggestions = assistant.suggest_automation()
295
+
296
+ # Get priority recommendations
297
+ priority_recommendations = assistant.recommend_priorities()
298
+
299
+ # Get pattern analysis
300
+ patterns = assistant.analyze_patterns()
301
+
302
+ result = {
303
+ "status": "success",
304
+ "automation_suggestions": automation_suggestions,
305
+ "priority_recommendations": priority_recommendations,
306
+ "pattern_analysis": {
307
+ "total_patterns": patterns.get("pattern_count", 0),
308
+ "analyzed_todos": patterns.get("total_completed", 0)
309
+ }
310
+ }
311
+
312
+ return json.dumps(result, default=str)
313
+ except Exception as e:
314
+ logger.error(f"Error generating todo suggestions: {e}")
315
+ return json.dumps({"status": "error", "message": str(e)})
316
+
317
+
318
+ async def get_specific_suggestions(todo_id: str) -> str:
319
+ """
320
+ Get AI-powered suggestions for a specific todo
321
+
322
+ Args:
323
+ todo_id: ID of the todo to get suggestions for
324
+
325
+ Returns:
326
+ JSON string with suggestions specific to the todo
327
+ """
328
+ try:
329
+ # Get the specific todo
330
+ todo = collection.find_one({"id": todo_id})
331
+ if not todo:
332
+ return json.dumps({"status": "error", "message": "Todo not found"})
333
+
334
+ # Refresh data to ensure we have the latest information
335
+ assistant.refresh_data()
336
+
337
+ # For pending todos, find similar completed todos
338
+ if todo.get("status") == "pending":
339
+ completed_descriptions = [t.get("description", "") for t in assistant.completed_todos]
340
+ if not completed_descriptions:
341
+ return json.dumps({
342
+ "status": "success",
343
+ "message": "No completed todos available for comparison",
344
+ "suggestions": []
345
+ })
346
+
347
+ vectorizer = TfidfVectorizer(max_features=100, stop_words='english')
348
+ completed_vectors = vectorizer.fit_transform(completed_descriptions)
349
+
350
+ # Transform pending todo using same vectorizer
351
+ pending_desc = todo.get("description", "")
352
+ pending_vector = vectorizer.transform([pending_desc])
353
+
354
+ # Calculate similarity with all completed todos
355
+ from sklearn.metrics.pairwise import cosine_similarity
356
+ similarities = cosine_similarity(pending_vector, completed_vectors).flatten()
357
+
358
+ # Get the indices of the top 5 most similar todos
359
+ top_indices = similarities.argsort()[-5:][::-1]
360
+
361
+ # Only consider valid similarities
362
+ similar_todos = []
363
+ for i, similarity in zip(top_indices, similarities[top_indices]):
364
+ if similarity > 0.2:
365
+ completed_todo = assistant.completed_todos[i]
366
+ similar_todos.append({
367
+ "id": completed_todo.get("id"),
368
+ "description": completed_todo.get("description"),
369
+ "priority": completed_todo.get("priority"),
370
+ "similarity": round(similarity * 100, 2)
371
+ })
372
+
373
+ # Calculate suggested priority based on similar todos
374
+ priorities = [t.get("priority") for t in similar_todos]
375
+ priority_counter = Counter(priorities)
376
+ suggested_priority = priority_counter.most_common(1)[0][0] if priorities else todo.get("priority")
377
+
378
+ # Calculate estimated completion time based on similar todos
379
+ completion_times = []
380
+ for t in assistant.completed_todos:
381
+ if t.get("created_at") and t.get("completed_at"):
382
+ completion_time = t.get("completed_at") - t.get("created_at")
383
+ if completion_time > 0:
384
+ completion_times.append(completion_time)
385
+
386
+ avg_completion = sum(completion_times) / len(completion_times) if completion_times else None
387
+
388
+ result = {
389
+ "status": "success",
390
+ "todo": {
391
+ "id": todo.get("id"),
392
+ "description": todo.get("description"),
393
+ "current_priority": todo.get("priority"),
394
+ "status": todo.get("status")
395
+ },
396
+ "suggestions": {
397
+ "suggested_priority": suggested_priority,
398
+ "estimated_completion_time": avg_completion,
399
+ "similar_completed_count": len(similar_todos)
400
+ },
401
+ "similar_todos": similar_todos
402
+ }
403
+
404
+ return json.dumps(result, default=str)
405
+
406
+ # For completed todos, there's not much to suggest
407
+ else:
408
+ return json.dumps({
409
+ "status": "success",
410
+ "message": "Todo is already completed",
411
+ "todo": {
412
+ "id": todo.get("id"),
413
+ "description": todo.get("description"),
414
+ "priority": todo.get("priority"),
415
+ "created_at": todo.get("created_at"),
416
+ "completed_at": todo.get("completed_at")
417
+ }
418
+ })
419
+
420
+ except Exception as e:
421
+ logger.error(f"Error generating suggestions for todo {todo_id}: {e}")
422
+ return json.dumps({"status": "error", "message": str(e)})