WingNeville commited on
Commit
4a18162
·
verified ·
1 Parent(s): dba720b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -107
app.py CHANGED
@@ -1,123 +1,64 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
- import requests
4
  import pytz
5
- import yaml
6
- from tools.final_answer import FinalAnswerTool
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.
33
- Args:
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,
116
- planning_interval=None,
117
- name=None,
118
- description=None,
119
- prompt_templates=prompt_templates
120
  )
121
 
122
- # Launch Gradio UI
123
- GradioUI(agent).launch()
 
 
 
1
  import datetime
 
2
  import pytz
 
 
 
3
  import gradio as gr
 
 
4
 
5
+ # Define tools
6
+ def combine_string_and_number(text: str, number: int) -> str:
7
+ """Combines a string and a number into a message."""
8
+ return f"You entered '{text}' and the number {number}."
 
9
 
10
+ def get_time_in_timezone(timezone: str) -> str:
11
+ """Gets the current time in the specified timezone."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  try:
13
  tz = pytz.timezone(timezone)
14
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
15
+ return f"Current time in {timezone}: {local_time}"
16
  except Exception as e:
17
+ return f"Error: Invalid timezone '{timezone}'"
18
 
19
+ # Simple agent class
20
+ class MyFirstAgent:
21
+ def __init__(self):
22
+ self.tools = {
23
+ "combine": combine_string_and_number,
24
+ "time": get_time_in_timezone
25
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ def run(self, query: str) -> str:
28
+ query = query.lower().strip()
29
+ if query.startswith("combine"):
30
+ try:
31
+ parts = query.split("combine")[-1].strip().split("and")
32
+ text = parts[0].strip()
33
+ number = int(parts[1].strip())
34
+ return self.tools["combine"](text, number)
35
+ except:
36
+ return "Error: Please use format 'combine <text> and <number>'"
37
+ elif query.startswith("time in"):
38
+ try:
39
+ timezone = query.split("time in")[-1].strip()
40
+ return self.tools["time"](timezone)
41
+ except:
42
+ return "Error: Please use format 'time in <timezone>'"
43
+ else:
44
+ return "Sorry, I only understand 'combine <text> and <number>' or 'time in <timezone>'"
45
 
46
+ # Create agent
47
+ agent = MyFirstAgent()
48
 
49
+ # Define Gradio interface function
50
+ def run_agent(query: str) -> str:
51
+ return agent.run(query)
 
 
 
52
 
53
+ # Create and launch Gradio interface
54
+ interface = gr.Interface(
55
+ fn=run_agent,
56
+ inputs=gr.Textbox(label="Enter your command", placeholder="e.g., combine hello and 42 or time in America/New_York"),
57
+ outputs=gr.Textbox(label="Agent Response"),
58
+ title="My First Agent",
59
+ description="Try commands like 'combine hello and 42' or 'time in America/New_York'"
 
 
 
 
60
  )
61
 
62
+ if __name__ == "__main__":
63
+ interface.launch(server_port=7860, share=False, quiet=True)
64
+