sametgirgin commited on
Commit
365fa23
·
verified ·
1 Parent(s): ab6f9fb

Create to_do.py

Browse files
Files changed (1) hide show
  1. to_do.py +166 -0
to_do.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import json
3
+ import uuid
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Dict, List
7
+
8
+ import pytz
9
+ from smolagents import tool
10
+
11
+
12
+ @dataclass
13
+ class Task:
14
+ id: str = None
15
+ completed: bool = False
16
+ description: str = ""
17
+ last_updated: str = ""
18
+
19
+ def __post_init__(self):
20
+ if self.id is None:
21
+ self.id = str(uuid.uuid4())
22
+
23
+ def to_dict(self) -> Dict:
24
+ return {
25
+ "id": self.id,
26
+ "completed": self.completed,
27
+ "description": self.description,
28
+ "last_updated": self.last_updated,
29
+ }
30
+
31
+
32
+ class TodoManager:
33
+ def __init__(self, filepath: str = "todo.jsonl"):
34
+ self.filepath = Path(filepath)
35
+ if not self.filepath.exists():
36
+ self.filepath.write_text("")
37
+
38
+ def _read_tasks(self) -> List[Task]:
39
+ if not self.filepath.exists():
40
+ return []
41
+
42
+ try:
43
+ with self.filepath.open("r", encoding="utf-8") as file:
44
+ data = [json.loads(line) for line in file if line.strip()]
45
+
46
+ return [
47
+ Task(
48
+ description=item.get("description", item.get("task", "")),
49
+ completed=item.get("completed", item.get("status") == "✅"),
50
+ last_updated=item["last_updated"],
51
+ id=item.get("id"),
52
+ )
53
+ for item in data
54
+ ]
55
+ except json.JSONDecodeError:
56
+ return []
57
+
58
+ def _save_tasks(self, tasks: List[Task]):
59
+ with self.filepath.open("w") as file:
60
+ for task in tasks:
61
+ file.write(json.dumps(task.to_dict()) + "\n")
62
+
63
+
64
+ @tool
65
+ def get_current_time_in_timezone(timezone: str) -> str:
66
+ """A tool that fetches the current local time in a specified timezone.
67
+ Args:
68
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
69
+ """
70
+ try:
71
+ tz = pytz.timezone(timezone)
72
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
73
+ return f"The current local time in {timezone} is: {local_time}"
74
+ except Exception as e:
75
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
76
+
77
+
78
+ @tool
79
+ def get_todays_tasks() -> str:
80
+ """List all tasks with their status and details.
81
+ Args:
82
+ None
83
+ Returns:
84
+ A formatted string containing all tasks with their status and IDs.
85
+ """
86
+ manager = TodoManager("./todo.jsonl")
87
+ tasks = manager._read_tasks()
88
+
89
+ if not tasks:
90
+ return "No tasks found"
91
+
92
+ pending = [t for t in tasks if not t.completed]
93
+ completed = [t for t in tasks if t.completed] # Uncomment this to show all tasks
94
+
95
+ output = [f"📅 Tasks Report for {datetime.date.today()}"]
96
+ output.append("\n🔴 Pending Tasks:")
97
+ output.extend(f"[{t.id[:8]}] {t.description}" for t in pending)
98
+ output.append("\n✅ Completed Tasks:") # Show both pending and completed tasks
99
+ output.extend(f"[{t.id[:8]}] {t.description}" for t in completed)
100
+ output.append(f"\nTotal: {len(pending)} pending, {len(completed)} completed")
101
+
102
+ return "\n".join(output)
103
+
104
+
105
+ @tool
106
+ def update_task_status(task_id: str) -> str:
107
+ """Toggle a task's completion status between complete and pending.
108
+ Args:
109
+ task_id: First 8 characters of the task's UUID (e.g., '65118069' from '65118069-b2a4-4ea3-b8e9-d7921381cbfc').
110
+ You can find task IDs in square brackets when listing tasks.
111
+ Returns:
112
+ Success message with task details if found and updated.
113
+ Error message if task not found or invalid input.
114
+ Examples:
115
+ > update_task_status('65118069')
116
+ "✅ Task [65118069] marked as complete: Repair my computer"
117
+ > update_task_status('65118069')
118
+ "✅ Task [65118069] marked as pending: Repair my computer"
119
+ """
120
+ # Validate task_id format
121
+ if not task_id or not isinstance(task_id, str) or len(task_id) < 1:
122
+ return "❌ Please provide a valid task ID"
123
+
124
+ try:
125
+ manager = TodoManager("./todo.jsonl")
126
+ tasks = manager._read_tasks()
127
+
128
+ if not tasks:
129
+ return "❌ No tasks found in the todo list"
130
+
131
+ # Find and update the task
132
+ for task in tasks:
133
+ if task.id.startswith(task_id):
134
+ task.completed = not task.completed
135
+ task.last_updated = datetime.date.today().strftime("%Y-%m-%d")
136
+ manager._save_tasks(tasks)
137
+ return f"✅ Task [{task_id}] marked as {'complete' if task.completed else 'pending'}: {task.description}"
138
+
139
+ return f"❌ No task found with ID '{task_id}'"
140
+
141
+ except (json.JSONDecodeError, IOError) as e:
142
+ return f"❌ Error accessing todo list: {str(e)}"
143
+ except Exception as e:
144
+ return f"❌ Unexpected error: {str(e)}"
145
+
146
+
147
+ @tool
148
+ def add_task(description: str) -> str:
149
+ """Add a new task to the todo list.
150
+ Args:
151
+ description: The text description of the task to add.
152
+ Returns:
153
+ A confirmation message indicating the task was added.
154
+ """
155
+ manager = TodoManager("./todo.jsonl")
156
+ tasks = manager._read_tasks()
157
+
158
+ new_task = Task(
159
+ description=description,
160
+ completed=False,
161
+ last_updated=datetime.date.today().strftime("%Y-%m-%d"),
162
+ )
163
+
164
+ tasks.append(new_task)
165
+ manager._save_tasks(tasks)
166
+ return f"✅ Added new task: {description}"