DoNotChoke commited on
Commit
6042e7f
·
verified ·
1 Parent(s): d50b3be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -34
app.py CHANGED
@@ -1,28 +1,27 @@
1
  import gradio as gr
2
  import requests
3
  import os
4
- from smolagents import tool, CodeAgent, HfApiModel, GoogleSearchTool, VisitWebpageTool
5
 
6
- # Lấy API keys từ biến môi trường
7
  OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY")
8
  SERPER_API_KEY = os.environ.get("SERPER_API_KEY")
9
 
10
- @tool
11
- @tool
12
  def get_weather(lat: float, lon: float) -> dict | None:
13
  """
14
- Gọi API OpenWeatherMap để lấy thông tin thời tiết theo tọa độ địa lý
15
 
16
  Args:
17
- lat (float): độ của địa điểm (từ -90 đến 90)
18
- lon (float): Kinh độ của địa điểm (từ -180 đến 180)
19
 
20
  Returns:
21
- dict | None: Dictionary chứa thông tin thời tiết hoặc None nếu có lỗi. Cấu trúc:
22
- - condition (str): tả điều kiện thời tiết
23
- - temperature (float): Nhiệt độ (°C)
24
- - humidity (float): Độ ẩm (%)
25
- - wind_speed (float): Tốc độ gió (m/s)
26
  """
27
  url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric"
28
  try:
@@ -37,50 +36,50 @@ def get_weather(lat: float, lon: float) -> dict | None:
37
  }
38
  return None
39
  except Exception as e:
40
- print(f"Lỗi API thời tiết: {e}")
41
  return None
42
-
43
  weather_agent = CodeAgent(
44
  model=HfApiModel("deepseek-ai/DeepSeek-R1", max_tokens=8096, provider="together"),
45
  tools=[GoogleSearchTool(provider="serper"), get_weather],
46
  name="Weather Expert",
47
- description="Xử yêu cầu thời tiết theo quy trình"
48
  )
49
 
50
  def respond(message, history):
51
  try:
52
- system_prompt = """BẠN CHUYÊN GIA THỜI TIẾT:
53
- 1. Phân tích địa điểm từ input
54
- 2. Google search "tọa độ [địa điểm]"
55
- 3. Trích xuất LAT/LON dạng số thực
56
- 4. Gọi get_weather(LAT, LON)
57
- 5. Trả lời markdown tiếng Việt
58
 
59
- LƯU Ý:
60
- - Luôn kiểm tra số liệu
61
- - Nếu không tìm được tọa độ → hỏi lại
62
- - Đơn vị: °C, %, m/s"""
63
 
64
  response = weather_agent.run(
65
- f"[Hệ thống] {system_prompt}\n[Người dùng] {message}"
66
  )
67
 
68
- return response if response else "Không thể xử lý yêu cầu"
69
 
70
  except Exception as e:
71
  print(f"[DEBUG] {str(e)}")
72
- return "Xin lỗi, tôi gặp sự cố xử yêu cầu này"
73
 
74
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
75
  gr.Markdown("# 🌦️ Weather Assistant")
76
- gr.Markdown("Nhập địa điểm bất kỳ để tra cứu thời tiết")
77
  chatbot = gr.ChatInterface(
78
  respond,
79
- title="Tra cứu Thời tiết",
80
- submit_btn="Gửi",
81
- retry_btn="Thử lại",
82
- undo_btn="Hủy",
83
- clear_btn="Xóa"
84
  )
85
 
86
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import requests
3
  import os
4
+ from smolagents import tool, CodeAgent, HfApiModel, GoogleSearchTool
5
 
6
+ # Get API keys from environment
7
  OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY")
8
  SERPER_API_KEY = os.environ.get("SERPER_API_KEY")
9
 
10
+ @tool # <-- CHỈ DÙNG 1 DECORATOR
 
11
  def get_weather(lat: float, lon: float) -> dict | None:
12
  """
13
+ Fetches current weather data from OpenWeatherMap API using geographic coordinates
14
 
15
  Args:
16
+ lat (float): Latitude of the location (-90 to 90)
17
+ lon (float): Longitude of the location (-180 to 180)
18
 
19
  Returns:
20
+ dict | None: Weather data dictionary containing:
21
+ - condition (str): Weather description
22
+ - temperature (float): Temperature in Celsius
23
+ - humidity (float): Humidity percentage
24
+ - wind_speed (float): Wind speed in m/s
25
  """
26
  url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric"
27
  try:
 
36
  }
37
  return None
38
  except Exception as e:
39
+ print(f"Weather API Error: {e}")
40
  return None
41
+
42
  weather_agent = CodeAgent(
43
  model=HfApiModel("deepseek-ai/DeepSeek-R1", max_tokens=8096, provider="together"),
44
  tools=[GoogleSearchTool(provider="serper"), get_weather],
45
  name="Weather Expert",
46
+ description="Processes weather queries through coordinate search and API calls"
47
  )
48
 
49
  def respond(message, history):
50
  try:
51
+ system_prompt = """YOU ARE A WEATHER SPECIALIST:
52
+ 1. Analyze location from user input
53
+ 2. Google search "coordinates of [location]"
54
+ 3. Extract LAT/LON numeric values
55
+ 4. Call get_weather(LAT, LON)
56
+ 5. Respond in Vietnamese markdown
57
 
58
+ NOTES:
59
+ - Always verify data accuracy
60
+ - Ask for clarification if coordinates not found
61
+ - Units: °C, %, m/s"""
62
 
63
  response = weather_agent.run(
64
+ f"[System] {system_prompt}\n[User] {message}"
65
  )
66
 
67
+ return response if response else "Could not process request"
68
 
69
  except Exception as e:
70
  print(f"[DEBUG] {str(e)}")
71
+ return "Sorry, I encountered an error processing your request"
72
 
73
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
74
  gr.Markdown("# 🌦️ Weather Assistant")
75
+ gr.Markdown("Enter any location to check weather conditions")
76
  chatbot = gr.ChatInterface(
77
  respond,
78
+ title="Weather Query",
79
+ submit_btn="Submit",
80
+ retry_btn="Retry",
81
+ undo_btn="Undo",
82
+ clear_btn="Clear"
83
  )
84
 
85
  if __name__ == "__main__":