umair1ali2 commited on
Commit
6606dd9
·
verified ·
1 Parent(s): 05d4ef4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -62
app.py CHANGED
@@ -2,27 +2,22 @@ import os
2
  import datetime
3
  import pytz
4
  import yaml
5
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
 
 
 
 
6
 
7
- # --- STEP 1: SECURITY & CONFIGURATION ---
8
- # Replace with your NEW token.
9
- # Best practice: Set this in your system environment variables as HF_TOKEN
10
- #os.environ["HF_TOKEN"] = ""
11
 
12
- # Creating a proper prompts.yaml to guide the agent's logic
13
- prompt_content = {
14
- "system_prompt": (
15
- "You are an expert AI assistant that can use python code to solve tasks. "
16
- "You have access to tools. For every step, explain your thought process in 'Thought:', "
17
- "then write the code in a 'Code:' block. Once you have the final answer, "
18
- "provide it clearly."
19
- )
20
- }
21
-
22
- with open("prompts.yaml", "w") as f:
23
- yaml.dump(prompt_content, f)
24
-
25
- # --- STEP 2: DEFINE TOOLS ---
26
 
27
  @tool
28
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -31,72 +26,55 @@ def get_current_time_in_timezone(timezone: str) -> str:
31
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
32
  """
33
  try:
34
- # Normalize common inputs
35
- if timezone.lower() == "new york":
36
- timezone = "America/New_York"
37
- elif timezone.lower() == "london":
38
- timezone = "Europe/London"
39
-
40
  tz = pytz.timezone(timezone)
41
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
42
  return f"The current local time in {timezone} is: {local_time}"
43
  except Exception as e:
44
- return f"Error: '{timezone}' is not a recognized timezone. Please use format like 'Europe/Paris'."
45
 
46
- @tool
47
- def my_custom_tool(arg1: str, arg2: int) -> str:
48
- """A placeholder tool for future custom logic.
49
- Args:
50
- arg1: A descriptive string.
51
- arg2: An integer multiplier or count.
52
- """
53
- return f"Logic processed: {arg1} received with value {arg2}."
54
 
55
- # --- STEP 3: INITIALIZE MODEL & TOOLS ---
 
 
 
56
 
57
- # Use a highly available model. If Qwen 32B gives a 403, try 'meta-llama/Llama-3.3-70B-Instruct'
58
  model = HfApiModel(
59
  max_tokens=2096,
60
  temperature=0.5,
61
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
 
62
  )
63
 
64
- # Load the image generation tool
65
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
66
 
67
- # Load the prompt template from the file we just created
68
  with open("prompts.yaml", 'r') as stream:
69
  prompt_templates = yaml.safe_load(stream)
70
 
71
- # --- STEP 4: INITIALIZE AGENT ---
72
 
73
  agent = CodeAgent(
74
  model=model,
75
  tools=[
 
76
  get_current_time_in_timezone,
77
- DuckDuckGoSearchTool(),
78
- image_generation_tool,
79
- my_custom_tool
80
- ],
81
- max_steps=6,
82
  verbosity_level=1,
83
- prompt_templates=prompt_templates
 
 
84
  )
85
 
86
- # --- STEP 5: EXECUTION ---
87
-
88
- if __name__ == "__main__":
89
- print("--- Starting Agent Test ---")
90
-
91
- task = "What is the current time in New York? After you find the time, generate a beautiful image of a clock that reflects the style of that city."
92
-
93
- try:
94
- result = agent.run(task)
95
- print("\n--- FINAL ANSWER ---")
96
- print(result)
97
- except Exception as e:
98
- print(f"\nAn error occurred during execution: {e}")
99
 
100
- # Optional: If you want to launch a UI (requires 'gradio' installed)
101
- # from Gradio_UI import GradioUI
102
- # GradioUI(agent).launch()
 
2
  import datetime
3
  import pytz
4
  import yaml
5
+ import requests
6
+ from PIL import Image
7
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, load_tool, tool
8
+ from tools.final_answer import FinalAnswerTool
9
+ from Gradio_UI import GradioUI
10
 
11
+ # --- 1. SETUP TOOLS ---
 
 
 
12
 
13
+ @tool
14
+ def my_custom_tool(arg1: str, arg2: int) -> str:
15
+ """A tool that returns a creative message.
16
+ Args:
17
+ arg1: the first argument
18
+ arg2: the second argument
19
+ """
20
+ return f"Magic is happening with {arg1} and {arg2}!"
 
 
 
 
 
 
21
 
22
  @tool
23
  def get_current_time_in_timezone(timezone: str) -> str:
 
26
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
27
  """
28
  try:
 
 
 
 
 
 
29
  tz = pytz.timezone(timezone)
30
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
31
  return f"The current local time in {timezone} is: {local_time}"
32
  except Exception as e:
33
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
34
 
35
+ # Initialize the mandatory final answer tool
36
+ final_answer = FinalAnswerTool()
 
 
 
 
 
 
37
 
38
+ # --- 2. SETUP MODEL ---
39
+
40
+ # Get your token from Space Secrets (Settings > Variables and secrets)
41
+ hf_token = os.getenv("HF_TOKEN")
42
 
 
43
  model = HfApiModel(
44
  max_tokens=2096,
45
  temperature=0.5,
46
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
47
+ token=hf_token
48
  )
49
 
50
+ # Load external tools
51
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
+ search_tool = DuckDuckGoSearchTool()
53
+
54
+ # --- 3. LOAD PROMPTS ---
55
 
 
56
  with open("prompts.yaml", 'r') as stream:
57
  prompt_templates = yaml.safe_load(stream)
58
 
59
+ # --- 4. INITIALIZE AGENT ---
60
 
61
  agent = CodeAgent(
62
  model=model,
63
  tools=[
64
+ final_answer,
65
  get_current_time_in_timezone,
66
+ my_custom_tool,
67
+ image_generation_tool,
68
+ search_tool
69
+ ],
70
+ max_steps=10,
71
  verbosity_level=1,
72
+ prompt_templates=prompt_templates,
73
+ # IMPORTANT: Allow these imports so the agent's code doesn't crash
74
+ additional_authorized_imports=['pytz', 'requests', 'PIL', 'datetime', 'io']
75
  )
76
 
77
+ # --- 5. LAUNCH UI ---
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
+ # This starts the Gradio interface defined in your course files
80
+ GradioUI(agent).launch()