DoNotChoke commited on
Commit
e8093cc
·
verified ·
1 Parent(s): 05ca424

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -36
app.py CHANGED
@@ -1,27 +1,19 @@
1
  import gradio as gr
2
  import requests
3
  import os
4
- from geopy.geocoders import Nominatim
5
  from smolagents import tool, CodeAgent, HfApiModel, GoogleSearchTool, VisitWebpageTool
6
 
7
  # Lấy API keys từ biến môi trường
8
  OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY")
9
  SERPER_API_KEY = os.environ.get("SERPER_API_KEY")
10
 
11
- # Định nghĩa tool get_weather
12
  @tool
13
  def get_weather(lat: float, lon: float) -> dict | None:
14
- """
15
- Call API to retrieve weather information for the given location.
16
- Args:
17
- lat: latitude of the location
18
- lon: longitude of the location
19
- """
20
  url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric"
21
  try:
22
  response = requests.get(url)
23
- data = response.json()
24
  if response.status_code == 200:
 
25
  return {
26
  "condition": data["weather"][0]["description"],
27
  "temperature": data["main"]["temp"],
@@ -30,51 +22,50 @@ def get_weather(lat: float, lon: float) -> dict | None:
30
  }
31
  return None
32
  except Exception as e:
33
- print(f"Weather API Error: {e}")
34
  return None
35
 
36
-
37
- # Khởi tạo agent
38
  weather_agent = CodeAgent(
39
  model=HfApiModel("deepseek-ai/DeepSeek-R1", max_tokens=8096, provider="together"),
40
- tools=[
41
- GoogleSearchTool(provider="serper"),
42
- VisitWebpageTool(),
43
- get_weather
44
- ],
45
- name="weather_agent",
46
- description="Fetch the weather condition of the given location."
47
  )
48
 
49
- # Hàm xử lý chat
50
  def respond(message, history):
51
  try:
52
- # Thêm prompt engineering để hướng dẫn agent
53
- system_prompt = """Bạn trợ thời tiết chuyên nghiệp. Hãy:
54
- 1. Xác định tọa độ địa lý từ tên địa điểm
55
- 2. Lấy thông tin thời tiết từ API
56
- 3. Trả lời bằng tiếng Việt với định dạng markdown
57
- 4. Kiểm tra độ chính xác của dữ liệu"""
 
 
 
 
 
58
 
59
  response = weather_agent.run(
60
- f"{system_prompt}\n\nYêu cầu người dùng: {message}"
61
  )
62
 
63
- return response if response else "Không thể lấy thông tin thời tiết"
64
 
65
  except Exception as e:
66
- print(f"Error: {e}")
67
- return "Đã xảy ra lỗi khi xử lý yêu cầu"
68
 
69
- # Tạo giao diện Gradio
70
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
71
- gr.Markdown("# 🗺️ Weather Chat Agent")
72
- gr.Markdown("Nhập địa điểm để xem thông tin thời tiết")
73
-
74
  chatbot = gr.ChatInterface(
75
  respond,
76
- examples=[" Nội", "New York", "Tokyo", "Paris"],
77
- title="Weather Chatbot",
 
 
 
78
  )
79
 
80
  if __name__ == "__main__":
 
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
  def get_weather(lat: float, lon: float) -> dict | None:
 
 
 
 
 
 
12
  url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric"
13
  try:
14
  response = requests.get(url)
 
15
  if response.status_code == 200:
16
+ data = response.json()
17
  return {
18
  "condition": data["weather"][0]["description"],
19
  "temperature": data["main"]["temp"],
 
22
  }
23
  return None
24
  except Exception as e:
25
+ print(f"Lỗi API thời tiết: {e}")
26
  return None
27
 
 
 
28
  weather_agent = CodeAgent(
29
  model=HfApiModel("deepseek-ai/DeepSeek-R1", max_tokens=8096, provider="together"),
30
+ tools=[GoogleSearchTool(provider="serper"), get_weather],
31
+ name="Weather Expert",
32
+ description="Xử lý yêu cầu thời tiết theo quy trình"
 
 
 
 
33
  )
34
 
 
35
  def respond(message, history):
36
  try:
37
+ system_prompt = """BẠN CHUYÊN GIA THỜI TIẾT:
38
+ 1. Phân tích địa điểm từ input
39
+ 2. Google search "tọa độ [địa điểm]"
40
+ 3. Trích xuất LAT/LON dạng số thực
41
+ 4. Gọi get_weather(LAT, LON)
42
+ 5. Trả lời markdown tiếng Việt
43
+
44
+ LƯU Ý:
45
+ - Luôn kiểm tra số liệu
46
+ - Nếu không tìm được tọa độ → hỏi lại
47
+ - Đơn vị: °C, %, m/s"""
48
 
49
  response = weather_agent.run(
50
+ f"[Hệ thống] {system_prompt}\n[Người dùng] {message}"
51
  )
52
 
53
+ return response if response else "Không thể xử yêu cầu"
54
 
55
  except Exception as e:
56
+ print(f"[DEBUG] {str(e)}")
57
+ return "Xin lỗi, tôi gặp sự cố xử lý yêu cầu này"
58
 
 
59
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
60
+ gr.Markdown("# 🌦️ Weather Assistant")
61
+ gr.Markdown("Nhập địa điểm bất kỳ để tra cứu thời tiết")
 
62
  chatbot = gr.ChatInterface(
63
  respond,
64
+ title="Tra cứu Thời tiết",
65
+ submit_btn="Gửi",
66
+ retry_btn="Thử lại",
67
+ undo_btn="Hủy",
68
+ clear_btn="Xóa"
69
  )
70
 
71
  if __name__ == "__main__":