uru commited on
Commit
a4fcb76
·
1 Parent(s): eb04e0a

refactoring

Browse files
.idea/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
app.py CHANGED
@@ -1,18 +1,32 @@
1
- from smolagents import CodeAgent, HfApiModel, load_tool, tool
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
  import shutil
7
  from pathlib import Path
 
8
  import gradio as gr
9
- print("Gradio version:", gr.__version__)
 
 
10
  from tools.final_answer import FinalAnswerTool
11
  from tools.web_search import DuckDuckGoSearchTool
12
  from tools.visit_webpage import VisitWebpageTool
 
 
13
  from src.first_agent.ui import GradioUI
14
 
15
- import os
 
 
 
 
 
 
 
 
 
 
 
16
  if not os.getenv("HF_TOKEN"):
17
  raise RuntimeError(
18
  "HF_TOKEN is not set. "
@@ -26,81 +40,30 @@ if OUTPUT_DIR.exists():
26
  shutil.rmtree(OUTPUT_DIR)
27
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
28
 
29
- @tool
30
- def disk_free(path: str = "/") -> str:
31
- """
32
- Show total/used/free disk space for a given filesystem path.
33
- Args:
34
- path: Filesystem path to inspect (e.g., '/', '/home/user').
35
- Returns:
36
- A human-friendly string with total/used/free sizes.
37
- """
38
- try:
39
- usage = shutil.disk_usage(path) # returns (total, used, free) in bytes
40
- except Exception as e:
41
- return f"Error reading disk usage for path='{path}': {e}"
42
-
43
- def fmt_bytes(n: int) -> str:
44
- # binary units (KiB, MiB, GiB...)
45
- units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]
46
- x = float(n)
47
- i = 0
48
- while x >= 1024.0 and i < len(units) - 1:
49
- x /= 1024.0
50
- i += 1
51
- return f"{x:.2f} {units[i]}"
52
-
53
- total = fmt_bytes(usage.total)
54
- used = fmt_bytes(usage.used)
55
- free = fmt_bytes(usage.free)
56
- return f"Disk usage for '{path}': total={total}, used={used}, free={free}"
57
-
58
- @tool
59
- def get_current_time_in_timezone(timezone: str) -> str:
60
- """A tool that fetches the current local time in a specified timezone.
61
- Args:
62
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
63
- """
64
- try:
65
- # Create timezone object
66
- tz = pytz.timezone(timezone)
67
- # Get current time in that timezone
68
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
69
- return f"The current local time in {timezone} is: {local_time}"
70
- except Exception as e:
71
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
72
-
73
 
 
74
  final_answer = FinalAnswerTool()
75
  web_search = DuckDuckGoSearchTool(max_results=10)
76
  visit_webpage = VisitWebpageTool()
77
 
78
- import os
79
- try:
80
- from dotenv import load_dotenv
81
- load_dotenv()
82
- except Exception:
83
- # On HF this is not necessary; there you can access env from Settings → Secrets
84
- pass
85
-
86
-
87
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
88
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
89
-
90
  model = HfApiModel(
91
- max_tokens=2096,
92
- temperature=0.5,
93
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
94
- custom_role_conversions=None,
95
  )
96
 
97
-
98
- # Import tool from Hub
99
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
100
 
101
- with open("prompts.yaml", 'r') as stream:
 
102
  prompt_templates = yaml.safe_load(stream)
103
-
 
104
  agent = CodeAgent(
105
  model=model,
106
  tools=[
@@ -117,8 +80,8 @@ agent = CodeAgent(
117
  planning_interval=None,
118
  name=None,
119
  description=None,
120
- prompt_templates=prompt_templates
121
  )
122
 
123
-
124
- GradioUI(agent).launch()
 
1
+ from __future__ import annotations
2
+
3
+ import os
 
 
4
  import shutil
5
  from pathlib import Path
6
+
7
  import gradio as gr
8
+ import yaml
9
+ from smolagents import CodeAgent, HfApiModel, load_tool
10
+
11
  from tools.final_answer import FinalAnswerTool
12
  from tools.web_search import DuckDuckGoSearchTool
13
  from tools.visit_webpage import VisitWebpageTool
14
+ from tools.disk_free import disk_free
15
+ from tools.timezone_time import get_current_time_in_timezone
16
  from src.first_agent.ui import GradioUI
17
 
18
+
19
+ print("Gradio version:", gr.__version__)
20
+
21
+ # --- Load .env locally (HF Spaces will use Settings → Secrets instead) ---
22
+ try:
23
+ from dotenv import load_dotenv
24
+
25
+ load_dotenv()
26
+ except Exception:
27
+ pass
28
+
29
+ # --- Required env ---
30
  if not os.getenv("HF_TOKEN"):
31
  raise RuntimeError(
32
  "HF_TOKEN is not set. "
 
40
  shutil.rmtree(OUTPUT_DIR)
41
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
42
 
43
+ # Make FinalAnswerTool write into the same folder
44
+ os.environ["FINAL_ANSWER_DIR"] = str(OUTPUT_DIR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # --- Tools ---
47
  final_answer = FinalAnswerTool()
48
  web_search = DuckDuckGoSearchTool(max_results=10)
49
  visit_webpage = VisitWebpageTool()
50
 
51
+ # --- Model ---
 
 
 
 
 
 
 
 
 
 
 
52
  model = HfApiModel(
53
+ max_tokens=2096,
54
+ temperature=0.5,
55
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct", # may be overloaded sometimes
56
+ custom_role_conversions=None,
57
  )
58
 
59
+ # Tool from Hub
 
60
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
61
 
62
+ # Prompts
63
+ with open("prompts.yaml", "r", encoding="utf-8") as stream:
64
  prompt_templates = yaml.safe_load(stream)
65
+
66
+ # --- Agent ---
67
  agent = CodeAgent(
68
  model=model,
69
  tools=[
 
80
  planning_interval=None,
81
  name=None,
82
  description=None,
83
+ prompt_templates=prompt_templates,
84
  )
85
 
86
+ # On HF Spaces, share=True is not supported; force share=False
87
+ GradioUI(agent).launch()
src/first_agent/__init__.py CHANGED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/first_agent/__init__.py
2
+
3
+ """
4
+ first_agent package.
5
+
6
+ Public API surface:
7
+ - GradioUI: UI wrapper to launch agent in Gradio
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from importlib.metadata import PackageNotFoundError, version
13
+
14
+ try:
15
+ __version__ = version("first_agent")
16
+ except PackageNotFoundError:
17
+ # When running from source without installation
18
+ __version__ = "0.0.0"
19
+
20
+ # Keep imports lightweight: only re-export core public objects.
21
+ from .ui import GradioUI # noqa: E402
22
+
23
+ __all__ = [
24
+ "GradioUI",
25
+ "__version__",
26
+ ]
src/first_agent/ui.py CHANGED
@@ -295,7 +295,7 @@ class GradioUI:
295
  [stored_messages, text_input],
296
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
297
 
298
- demo.launch(debug=True, share=True, **kwargs)
299
 
300
 
301
  __all__ = ["stream_to_gradio", "GradioUI"]
 
295
  [stored_messages, text_input],
296
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
297
 
298
+ demo.launch(debug=True, **kwargs)
299
 
300
 
301
  __all__ = ["stream_to_gradio", "GradioUI"]
tools/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .disk_free import disk_free
2
+ from .timezone_time import get_current_time_in_timezone
3
+
4
+ __all__ = [
5
+ "disk_free",
6
+ "get_current_time_in_timezone",
7
+ ]
tools/disk_free.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ from smolagents import tool
5
+
6
+
7
+ @tool
8
+ def disk_free(path: str = "/") -> str:
9
+ """
10
+ Show total/used/free disk space for a given filesystem path.
11
+
12
+ Args:
13
+ path: Filesystem path to inspect (e.g., '/', '/home/user').
14
+
15
+ Returns:
16
+ A human-friendly string with total/used/free sizes.
17
+ """
18
+ try:
19
+ usage = shutil.disk_usage(path) # (total, used, free) in bytes
20
+ except Exception as e:
21
+ return f"Error reading disk usage for path='{path}': {e}"
22
+
23
+ def fmt_bytes(n: int) -> str:
24
+ units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]
25
+ x = float(n)
26
+ i = 0
27
+ while x >= 1024.0 and i < (len(units) - 1):
28
+ x /= 1024.0
29
+ i += 1
30
+ return f"{x:.2f} {units[i]}"
31
+
32
+ total = fmt_bytes(usage.total)
33
+ used = fmt_bytes(usage.used)
34
+ free = fmt_bytes(usage.free)
35
+ return f"Disk usage for '{path}': total={total}, used={used}, free={free}"
tools/timezone_time.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime
4
+ import pytz
5
+ from smolagents import tool
6
+
7
+
8
+ @tool
9
+ def get_current_time_in_timezone(timezone: str) -> str:
10
+ """
11
+ Fetch current local time in a specified timezone.
12
+
13
+ Args:
14
+ timezone: A valid timezone string (e.g., 'America/New_York').
15
+
16
+ Returns:
17
+ A human-readable string with local time.
18
+ """
19
+ try:
20
+ tz = pytz.timezone(timezone)
21
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
22
+ return f"The current local time in {timezone} is: {local_time}"
23
+ except Exception as e:
24
+ return f"Error fetching time for timezone '{timezone}': {e}"