Wayne0102 commited on
Commit
88234d0
·
verified ·
1 Parent(s): 8902182

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -70
app.py CHANGED
@@ -1,100 +1,93 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
 
2
  import datetime
3
  import pytz
4
- import yaml
5
- from Gradio_UI import GradioUI
6
 
7
  # ==================== YOUR TOOLS ====================
8
  @tool
9
  def get_current_time_in_timezone(timezone: str) -> str:
10
- """A tool that fetches the current local time in a specified timezone.
11
  Args:
12
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
13
  """
14
  try:
15
  tz = pytz.timezone(timezone)
16
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
17
- return f"The current local time in {timezone} is: {local_time}"
18
- except Exception as e:
19
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
20
 
21
  @tool
22
  def calculate_tip(bill_amount: float, tip_percent: float) -> str:
23
- """Calculate tip amount for a restaurant bill.
24
  Args:
25
- bill_amount: Total bill amount in dollars
26
  tip_percent: Tip percentage (e.g., 15 for 15%)
27
  """
28
- try:
29
- tip = bill_amount * (tip_percent / 100)
30
- total = bill_amount + tip
31
- return f"💰 Tip: ${tip:.2f}, Total: ${total:.2f} ({tip_percent}%)"
32
- except Exception as e:
33
- return f"Error: {str(e)}"
34
 
35
  @tool
36
  def word_counter(text: str) -> str:
37
- """Count words and characters in text.
38
  Args:
39
- text: The text to analyze
40
  """
41
- try:
42
- words = len(text.split())
43
- chars = len(text)
44
- return f"📝 Words: {words}, Characters: {chars}"
45
- except Exception as e:
46
- return f"Error: {str(e)}"
47
-
48
- # ==================== AGENT SETUP ====================
49
- final_answer = FinalAnswerTool()
50
-
51
- # Load image generation tool
52
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
53
 
54
- # ⚠️ FIX: ADD THE MISSING MODEL SETUP
55
- # Try different model import approaches:
56
-
57
- # OPTION 1: Use HfApiModel (common in spaces)
58
- try:
59
- from smolagents import HfApiModel
60
- model = HfApiModel(
61
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
62
- max_tokens=512,
63
- temperature=0.5
64
- )
65
- except ImportError:
66
- # OPTION 2: Use InferenceClientModel with correct import path
67
  try:
68
- from smolagents.models import InferenceClientModel
69
- model = InferenceClientModel(
70
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
71
- max_tokens=512,
72
- temperature=0.5
73
- )
74
- except ImportError:
75
- # OPTION 3: Use default model
76
- from smolagents.models import DefaultModel
77
- model = DefaultModel()
78
-
79
- # Load system prompt
80
- with open("prompts.yaml", 'r') as stream:
81
- prompt_templates = yaml.safe_load(stream)
82
 
83
  # ==================== CREATE AGENT ====================
 
84
  agent = CodeAgent(
85
- model=model, # ⚠️ THIS WAS MISSING!
86
  tools=[
87
- final_answer,
88
- DuckDuckGoSearchTool(),
89
- image_generation_tool,
90
- get_current_time_in_timezone,
91
- calculate_tip,
92
- word_counter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  ],
94
- max_steps=8,
95
- verbosity_level=1,
96
- prompt_templates=prompt_templates
97
  )
98
 
99
- # ==================== LAUNCH ====================
100
- GradioUI(agent).launch()
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, tool
2
+ import gradio as gr
3
  import datetime
4
  import pytz
 
 
5
 
6
  # ==================== YOUR TOOLS ====================
7
  @tool
8
  def get_current_time_in_timezone(timezone: str) -> str:
9
+ """Get current time in any timezone.
10
  Args:
11
+ timezone: Timezone like 'America/New_York' or 'Asia/Tokyo'
12
  """
13
  try:
14
  tz = pytz.timezone(timezone)
15
+ time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
16
+ return f" Time in {timezone}: {time}"
17
+ except:
18
+ return "Invalid timezone. Try: America/New_York, Europe/London, Asia/Tokyo"
19
 
20
  @tool
21
  def calculate_tip(bill_amount: float, tip_percent: float) -> str:
22
+ """Calculate restaurant tip.
23
  Args:
24
+ bill_amount: Bill total in dollars
25
  tip_percent: Tip percentage (e.g., 15 for 15%)
26
  """
27
+ tip = bill_amount * (tip_percent / 100)
28
+ total = bill_amount + tip
29
+ return f"💰 Tip: ${tip:.2f}\n💵 Total: ${total:.2f}\n📊 {tip_percent}% of ${bill_amount}"
 
 
 
30
 
31
  @tool
32
  def word_counter(text: str) -> str:
33
+ """Count words and characters.
34
  Args:
35
+ text: Text to analyze
36
  """
37
+ words = len(text.split())
38
+ chars = len(text)
39
+ return f"📝 Words: {words}\n🔤 Characters: {chars}"
 
 
 
 
 
 
 
 
 
40
 
41
+ @tool
42
+ def simple_calculator(expression: str) -> str:
43
+ """Do basic math calculations.
44
+ Args:
45
+ expression: Math like '2 + 2' or '10 * 5 / 2'
46
+ """
 
 
 
 
 
 
 
47
  try:
48
+ # Safe calculation
49
+ allowed = {'+', '-', '*', '/', '(', ')', '.', ' '}
50
+ if all(c.isdigit() or c in allowed for c in expression):
51
+ result = eval(expression)
52
+ return f"🧮 {expression} = {result}"
53
+ return "❌ Only basic math allowed: + - * / ( )"
54
+ except:
55
+ return "❌ Invalid math expression"
 
 
 
 
 
 
56
 
57
  # ==================== CREATE AGENT ====================
58
+ # ✨ NO FinalAnswerTool needed!
59
  agent = CodeAgent(
 
60
  tools=[
61
+ DuckDuckGoSearchTool(), # Web search
62
+ get_current_time_in_timezone, # Time tool
63
+ calculate_tip, # Tip calculator
64
+ word_counter, # Word counter
65
+ simple_calculator # Math calculator
66
+ ],
67
+ max_steps=8, # Increased for complex tasks
68
+ verbosity_level=1 # Show thinking process
69
+ )
70
+
71
+ # ==================== GRADIO INTERFACE ====================
72
+ def chat_with_agent(message, history):
73
+ """Handle chat messages"""
74
+ response = agent.run(message)
75
+ return response
76
+
77
+ # Create chat interface
78
+ demo = gr.ChatInterface(
79
+ fn=chat_with_agent,
80
+ title="🤖 Super Assistant Pro",
81
+ description="I can: 🔍 Search web • ⏰ Tell time • 💰 Calculate tips • 📝 Count words • 🧮 Do math",
82
+ examples=[
83
+ "What time is it in Tokyo and calculate 15% tip on ¥5000?",
84
+ "Count words in 'Hello world' and search for current news",
85
+ "Calculate 25 * 4 + 10 and tell time in London",
86
+ "What's the weather in Paris? Also calculate 18% tip on €75"
87
  ],
88
+ theme="soft"
 
 
89
  )
90
 
91
+ # Launch the app
92
+ if __name__ == "__main__":
93
+ demo.launch()