WingNeville commited on
Commit
35976fe
·
verified ·
1 Parent(s): 43b3029

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -77
app.py CHANGED
@@ -1,93 +1,57 @@
1
  import datetime
2
  import pytz
3
- import gradio as gr
4
- from typing import Callable, List
5
 
6
- # Define a simple tool decorator (mimicking smolagents' @tool)
7
- def tool(func: Callable) -> Callable:
8
- return func
 
9
 
10
- # Define the FinalAnswerTool
11
- class FinalAnswerTool:
12
- def __call__(self, answer: str) -> str:
13
- return f"Final Answer: {answer}"
14
-
15
- @tool
16
- def my_custom_tool(arg1: str, arg2: int) -> str:
17
- """A tool that combines two arguments into a message.
18
-
19
- Args:
20
- arg1: the first argument (string)
21
- arg2: the second argument (integer)
22
-
23
- Returns:
24
- A message combining both arguments.
25
- """
26
- return f"You provided '{arg1}' and the number {arg2}."
27
-
28
- @tool
29
- def get_current_time_in_timezone(timezone: str) -> str:
30
- """A tool that fetches the current local time in a specified timezone.
31
-
32
- Args:
33
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
34
-
35
- Returns:
36
- The current local time in the specified timezone.
37
- """
38
  try:
39
  tz = pytz.timezone(timezone)
40
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
41
- return f"The current local time in {timezone} is: {local_time}"
42
  except Exception as e:
43
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
44
 
45
- # Simple CodeAgent class (mimicking smolagents' CodeAgent)
46
- class CodeAgent:
47
- def __init__(self, tools: List[Callable]):
48
- self.tools = {tool.__name__: tool for tool in tools}
 
 
 
49
 
50
  def run(self, query: str) -> str:
51
- # Simple logic to route queries to tools
52
- if "time in" in query.lower():
53
- # Extract timezone from query (e.g., "time in America/New_York")
54
  try:
55
- timezone = query.lower().split("time in")[-1].strip()
56
- return self.tools["get_current_time_in_timezone"](timezone)
57
- except Exception as e:
58
- return f"Error processing timezone: {str(e)}"
59
- elif "combine" in query.lower():
60
- # Extract arguments for my_custom_tool (e.g., "combine hello and 42")
 
61
  try:
62
- parts = query.lower().split("combine")[-1].strip().split("and")
63
- arg1 = parts[0].strip()
64
- arg2 = int(parts[1].strip())
65
- return self.tools["my_custom_tool"](arg1, arg2)
66
- except Exception as e:
67
- return f"Error processing combine query: {str(e)}"
68
  else:
69
- return "Sorry, I don't understand the query. Try 'time in <timezone>' or 'combine <string> and <number>'."
70
-
71
- # Initialize tools and agent
72
- final_answer = FinalAnswerTool()
73
- agent = CodeAgent(tools=[final_answer, my_custom_tool, get_current_time_in_timezone])
74
-
75
- # Define Gradio interface function
76
- def run_agent(query: str) -> str:
77
- try:
78
- response = agent.run(query)
79
- return final_answer(response)
80
- except Exception as e:
81
- return f"Error: {str(e)}"
82
-
83
- # Create and launch Gradio interface
84
- interface = gr.Interface(
85
- fn=run_agent,
86
- inputs=gr.Textbox(label="Enter your query"),
87
- outputs=gr.Textbox(label="Agent Response"),
88
- title="Simple Agent Example",
89
- description="Try queries like 'Get the time in America/New_York' or 'Combine hello and 42'"
90
- )
91
 
 
92
  if __name__ == "__main__":
93
- interface.launch(server_port=7860, share=False, quiet=True)
 
 
 
 
 
 
 
 
 
 
 
1
  import datetime
2
  import pytz
 
 
3
 
4
+ # Define tools
5
+ def combine_string_and_number(text: str, number: int) -> str:
6
+ """Combines a string and a number into a message."""
7
+ return f"You entered '{text}' and the number {number}."
8
 
9
+ def get_time_in_timezone(timezone: str) -> str:
10
+ """Gets the current time in the specified timezone."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  try:
12
  tz = pytz.timezone(timezone)
13
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
14
+ return f"Current time in {timezone}: {local_time}"
15
  except Exception as e:
16
+ return f"Error: Invalid timezone '{timezone}'"
17
 
18
+ # Simple agent class
19
+ class MyFirstAgent:
20
+ def __init__(self):
21
+ self.tools = {
22
+ "combine": combine_string_and_number,
23
+ "time": get_time_in_timezone
24
+ }
25
 
26
  def run(self, query: str) -> str:
27
+ query = query.lower().strip()
28
+ if query.startswith("combine"):
 
29
  try:
30
+ parts = query.split("combine")[-1].strip().split("and")
31
+ text = parts[0].strip()
32
+ number = int(parts[1].strip())
33
+ return self.tools["combine"](text, number)
34
+ except:
35
+ return "Error: Please use format 'combine <text> and <number>'"
36
+ elif query.startswith("time in"):
37
  try:
38
+ timezone = query.split("time in")[-1].strip()
39
+ return self.tools["time"](timezone)
40
+ except:
41
+ return "Error: Please use format 'time in <timezone>'"
 
 
42
  else:
43
+ return "Sorry, I only understand 'combine <text> and <number>' or 'time in <timezone>'"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ # Create and run the agent
46
  if __name__ == "__main__":
47
+ agent = MyFirstAgent()
48
+ print("Welcome to My First Agent!")
49
+ print("Try commands like 'combine hello and 42' or 'time in America/New_York'")
50
+ print("Type 'quit' to exit")
51
+ while True:
52
+ query = input("Enter your command: ")
53
+ if query.lower() == "quit":
54
+ print("Goodbye!")
55
+ break
56
+ response = agent.run(query)
57
+ print("Response:", response)