YeeJun02 commited on
Commit
9e3bb03
·
verified ·
1 Parent(s): bca58e3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -0
app.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, InferenceClientModel
3
+ import datetime
4
+ import pytz
5
+ import math
6
+ import os
7
+
8
+ # ============ TOOLS ============
9
+
10
+ @tool
11
+ def web_search_tool(query: str) -> str:
12
+ """Search the web for current information using DuckDuckGo.
13
+
14
+ Args:
15
+ query: The search query string to look up.
16
+ """
17
+ try:
18
+ search = DuckDuckGoSearchTool()
19
+ results = search(query)
20
+ if not results:
21
+ return "No results found for your query."
22
+ return results
23
+ except Exception as e:
24
+ return f"Search error: {str(e)}"
25
+
26
+ @tool
27
+ def time_tool(timezone: str = "UTC") -> str:
28
+ """Get current time in a specific timezone.
29
+
30
+ Args:
31
+ timezone: The timezone to check (e.g., 'Asia/Tokyo') or 'list' to see options.
32
+ """
33
+ try:
34
+ if timezone.lower() == "list":
35
+ timezones = ["UTC", "America/New_York", "Europe/London",
36
+ "Asia/Tokyo", "Australia/Sydney", "Europe/Paris"]
37
+ return "Available timezones:\n" + "\n".join(f"• {tz}" for tz in timezones)
38
+
39
+ tz = pytz.timezone(timezone)
40
+ time = datetime.datetime.now(tz)
41
+ return (f"⏰ Time in {timezone}:\n"
42
+ f"• Date: {time.strftime('%Y-%m-%d')}\n"
43
+ f"• Time: {time.strftime('%H:%M:%S')}\n"
44
+ f"• Day: {time.strftime('%A')}")
45
+ except Exception as e:
46
+ return f"Error: {str(e)}. Try 'list' to see available timezones."
47
+
48
+ @tool
49
+ def calculator_tool(expression: str) -> str:
50
+ """Perform mathematical calculations.
51
+
52
+ Args:
53
+ expression: The math expression to evaluate (e.g., '2 + 2' or 'sqrt(16)').
54
+ """
55
+ try:
56
+ # Simple cleanup for user-friendly operators
57
+ expr = expression.replace('^', '**').replace('×', '*').replace('÷', '/')
58
+ safe_dict = {
59
+ 'abs': abs, 'round': round, 'min': min, 'max': max,
60
+ 'sqrt': math.sqrt, 'pow': pow, 'sin': math.sin,
61
+ 'cos': math.cos, 'tan': math.tan, 'pi': math.pi, 'e': math.e
62
+ }
63
+ result = eval(expr, {"__builtins__": {}}, safe_dict)
64
+ return f"🧮 Calculation Result: {result}"
65
+ except Exception as e:
66
+ return f"Calculation error: {str(e)}"
67
+
68
+ @tool
69
+ def unit_converter_tool(query: str) -> str:
70
+ """Convert between different units of measurement.
71
+
72
+ Args:
73
+ query: The conversion string (e.g., '10 km to miles').
74
+ """
75
+ try:
76
+ parts = query.lower().split()
77
+ if len(parts) < 4:
78
+ return "Format: '10 km to miles' or '100 celsius to fahrenheit'"
79
+
80
+ value = float(parts[0])
81
+ from_unit = parts[1]
82
+ to_unit = parts[3]
83
+
84
+ conversions = {
85
+ 'km': {'miles': 0.621371, 'meters': 1000},
86
+ 'miles': {'km': 1.60934, 'meters': 1609.34},
87
+ 'meters': {'km': 0.001, 'miles': 0.000621371},
88
+ 'kg': {'pounds': 2.20462, 'grams': 1000},
89
+ 'pounds': {'kg': 0.453592},
90
+ 'liters': {'gallons': 0.264172}
91
+ }
92
+
93
+ if from_unit == 'celsius' and to_unit == 'fahrenheit':
94
+ result = (value * 9/5) + 32
95
+ elif from_unit == 'fahrenheit' and to_unit == 'celsius':
96
+ result = (value - 32) * 5/9
97
+ elif from_unit in conversions and to_unit in conversions[from_unit]:
98
+ result = value * conversions[from_unit][to_unit]
99
+ else:
100
+ return f"Can't convert {from_unit} to {to_unit}."
101
+
102
+ return f"📏 {value} {from_unit} = {result:.4f} {to_unit}"
103
+ except Exception as e:
104
+ return f"Conversion error: {str(e)}"
105
+
106
+ # ============ AGENT SETUP ============
107
+
108
+ HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN", "")
109
+
110
+ # Using HfApiModel ensures the correct message format (list of dicts)
111
+ # Qwen-2.5-Coder is highly recommended for CodeAgent tool use
112
+ model = InferenceClientModel(
113
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
114
+ token=HF_TOKEN # Make sure your token has "Inference" permissions
115
+ )
116
+
117
+ agent = CodeAgent(
118
+ model=model,
119
+ tools=[web_search_tool, time_tool, calculator_tool],
120
+ max_steps=5,
121
+ additional_authorized_imports=['math', 'datetime', 'pytz']
122
+ )
123
+
124
+ # ============ GRADIO UI ============
125
+
126
+ def chat_with_agent(message, history):
127
+ if not HF_TOKEN:
128
+ return "Please set your HUGGINGFACE_TOKEN as an environment variable to use the AI."
129
+ try:
130
+ # agent.run returns the final answer string
131
+ response = agent.run(message)
132
+ return str(response)
133
+ except Exception as e:
134
+ return f"Agent Error: {str(e)}"
135
+
136
+ demo = gr.ChatInterface(
137
+ fn=chat_with_agent,
138
+ title="🤖 Alfred AI Assistant",
139
+ description="I am Alfred, your tool-equipped assistant. I can search the web, calculate math, convert units, and check the time!",
140
+ examples=[
141
+ "What time is it in Tokyo?",
142
+ "Convert 150 pounds to kg",
143
+ "Calculate the square root of 144 plus 50",
144
+ "Search for the latest news on AI agents"
145
+ ],
146
+ )
147
+
148
+ if __name__ == "__main__":
149
+ demo.launch(theme=gr.themes.Soft())