WingNeville commited on
Commit
dba720b
·
verified ·
1 Parent(s): 7847ff0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -30
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
@@ -7,21 +7,26 @@ from tools.final_answer import FinalAnswerTool
7
  from openai import OpenAI
8
  import gradio as gr
9
  import os
 
 
 
10
  api_key = os.getenv("OPENAI_API_KEY")
 
 
11
  client = OpenAI(api_key=api_key)
12
- from Gradio_UI import GradioUI
13
 
14
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
15
- @tool
16
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
17
- #Keep this format for the description / args / args description but feel free to modify the tool
18
- """A tool that does nothing yet
19
- Args:
20
- arg1: the first argument
21
- arg2: the second argument
22
- """
23
- return "What magic will you build ?"
24
 
 
25
  @tool
26
  def get_current_time_in_timezone(timezone: str) -> str:
27
  """A tool that fetches the current local time in a specified timezone.
@@ -29,37 +34,82 @@ def get_current_time_in_timezone(timezone: str) -> str:
29
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
30
  """
31
  try:
32
- # Create timezone object
33
  tz = pytz.timezone(timezone)
34
- # Get current time in that timezone
35
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
36
  return f"The current local time in {timezone} is: {local_time}"
37
  except Exception as e:
38
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
 
41
  final_answer = FinalAnswerTool()
42
 
43
- # 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:
44
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
45
-
46
- model = HfApiModel(
47
- max_tokens=2096,
48
- temperature=0.5,
49
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
50
- custom_role_conversions=None,
51
- )
52
-
 
 
 
 
 
 
53
 
54
- # Import tool from Hub
55
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
56
 
57
- with open("prompts.yaml", 'r') as stream:
58
- prompt_templates = yaml.safe_load(stream)
59
-
 
 
 
 
 
60
  agent = CodeAgent(
61
  model=model,
62
- tools=[final_answer], ## add your tools here (don't remove final answer)
63
  max_steps=6,
64
  verbosity_level=1,
65
  grammar=None,
@@ -69,5 +119,5 @@ agent = CodeAgent(
69
  prompt_templates=prompt_templates
70
  )
71
 
72
-
73
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
 
7
  from openai import OpenAI
8
  import gradio as gr
9
  import os
10
+ from huggingface_hub import login
11
+
12
+ # Initialize OpenAI client (optional, kept from original code)
13
  api_key = os.getenv("OPENAI_API_KEY")
14
+ if not api_key:
15
+ raise ValueError("OPENAI_API_KEY environment variable not set.")
16
  client = OpenAI(api_key=api_key)
 
17
 
18
+ # Authenticate with Hugging Face
19
+ hf_token = os.getenv("HF_TOKEN")
20
+ if not hf_token:
21
+ print("HF_TOKEN not set. Attempting to log in via huggingface-cli...")
22
+ try:
23
+ login() # Prompts for token if not already logged in
24
+ except Exception as e:
25
+ raise ValueError(f"Failed to authenticate with Hugging Face: {str(e)}. Please run `huggingface-cli login` or set HF_TOKEN environment variable.")
26
+ else:
27
+ login(token=hf_token)
28
 
29
+ # Tool to get current time in a specified timezone
30
  @tool
31
  def get_current_time_in_timezone(timezone: str) -> str:
32
  """A tool that fetches the current local time in a specified timezone.
 
34
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
35
  """
36
  try:
 
37
  tz = pytz.timezone(timezone)
 
38
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
39
  return f"The current local time in {timezone} is: {local_time}"
40
  except Exception as e:
41
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
42
 
43
+ # Tool to verify timezone output
44
+ @tool
45
+ def verify_timezone_output(timezone: str, time_output: str) -> str:
46
+ """A tool that verifies the output of get_current_time_in_timezone.
47
+ Args:
48
+ timezone: A string representing the timezone to verify (e.g., 'America/New_York').
49
+ time_output: The time string returned by get_current_time_in_timezone (e.g., 'The current local time in America/New_York is: 2025-05-29 10:53:00').
50
+ Returns:
51
+ A string indicating whether the timezone and time are valid, with details.
52
+ """
53
+ try:
54
+ if timezone not in pytz.all_timezones:
55
+ return f"Verification failed: '{timezone}' is not a valid timezone."
56
+ if "The current local time" not in time_output or timezone not in time_output:
57
+ return "Verification failed: Invalid time output format."
58
+ time_str = time_output.split("is: ")[-1].strip()
59
+ try:
60
+ parsed_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
61
+ except ValueError:
62
+ return "Verification failed: Time format is incorrect (expected 'YYYY-MM-DD HH:MM:SS')."
63
+ try:
64
+ response = requests.get(f"http://worldtimeapi.org/api/timezone/{timezone}", timeout=5)
65
+ response.raise_for_status()
66
+ api_data = response.json()
67
+ api_time = datetime.datetime.fromisoformat(api_data["datetime"].replace("Z", "+00:00"))
68
+ api_time = api_time.astimezone(pytz.timezone(timezone))
69
+ api_time_str = api_time.strftime("%Y-%m-%d %H:%M:%S")
70
+ time_diff = abs((parsed_time - api_time).total_seconds())
71
+ if time_diff > 60:
72
+ return f"Verification failed: Time '{time_str}' differs significantly from API time '{api_time_str}'."
73
+ except requests.RequestException as e:
74
+ return f"Verification warning: Could not verify with external API due to {str(e)}. Local time format is valid."
75
+ return f"Verification passed: Timezone '{timezone}' and time '{time_str}' are valid."
76
+ except Exception as e:
77
+ return f"Verification error: {str(e)}"
78
 
79
+ # Initialize FinalAnswerTool
80
  final_answer = FinalAnswerTool()
81
 
82
+ # Initialize Hugging Face model with fallback endpoint
83
+ try:
84
+ model = HfApiModel(
85
+ max_tokens=2096,
86
+ temperature=0.5,
87
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
88
+ custom_role_conversions=None,
89
+ )
90
+ except Exception as e:
91
+ print(f"Primary model failed: {str(e)}. Switching to fallback endpoint...")
92
+ model = HfApiModel(
93
+ max_tokens=2096,
94
+ temperature=0.5,
95
+ model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
96
+ custom_role_conversions=None,
97
+ )
98
 
99
+ # Load external tool (e.g., text-to-image)
100
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
101
 
102
+ # Load prompt templates from YAML
103
+ try:
104
+ with open("prompts.yaml", 'r') as stream:
105
+ prompt_templates = yaml.safe_load(stream)
106
+ except FileNotFoundError:
107
+ raise FileNotFoundError("prompts.yaml not found. Ensure the file exists in the working directory.")
108
+
109
+ # Initialize CodeAgent with tools
110
  agent = CodeAgent(
111
  model=model,
112
+ tools=[get_current_time_in_timezone, verify_timezone_output, final_answer],
113
  max_steps=6,
114
  verbosity_level=1,
115
  grammar=None,
 
119
  prompt_templates=prompt_templates
120
  )
121
 
122
+ # Launch Gradio UI
123
  GradioUI(agent).launch()