legendlc commited on
Commit
06688af
·
verified ·
1 Parent(s): b5f4d0e

Add amap weather

Browse files
Files changed (1) hide show
  1. app.py +130 -7
app.py CHANGED
@@ -7,15 +7,138 @@ from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  @tool
12
- def get_current_temperature(city: str)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that fetches the current temperature in a specified city.
15
  Args:
16
- city: A string representing a valid city name (e.g., 'Shanghai')
17
  """
18
- return f"{city} 现在天气是36摄氏度"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  @tool
21
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -54,7 +177,7 @@ with open("prompts.yaml", 'r') as stream:
54
 
55
  agent = CodeAgent(
56
  model=model,
57
- tools=[final_answer, get_current_temperature, get_current_time_in_timezone], ## add your tools here (don't remove final answer)
58
  max_steps=6,
59
  verbosity_level=1,
60
  grammar=None,
 
7
 
8
  from Gradio_UI import GradioUI
9
 
10
+ AMAP_API_BASE = "https://restapi.amap.com/v3/weather/weatherInfo"
11
+ AMAP_API_KEY = os.environ.get("AMAP_API_KEY", "")
12
+
13
+ city_to_adcode = {}
14
+
15
+ def load_city_adcode_map():
16
+ """加载城市名称到adcode的映射"""
17
+ try:
18
+ current_dir = os.path.dirname(os.path.abspath(__file__))
19
+ csv_file_path = os.path.join(current_dir, "AMap_adcode_citycode.csv")
20
+
21
+ with open(csv_file_path, 'r', encoding='utf-8') as file:
22
+ reader = csv.reader(file)
23
+ next(reader) # 跳过表头
24
+ for row in reader:
25
+ if len(row) >= 2:
26
+ city_name = row[0].strip()
27
+ adcode = row[1].strip()
28
+ city_to_adcode[city_name] = adcode
29
+ return True
30
+ except Exception as e:
31
+ print(f"加载城市编码文件失败: {e}")
32
+ return False
33
+
34
+ # 初始加载城市编码数据
35
+ load_city_adcode_map()
36
+
37
+ def get_adcode_by_city(city_name: str) -> Optional[str]:
38
+ """根据城市名称查找对应的adcode
39
+
40
+ Args:
41
+ city_name: 城市名称,如"北京市"、"上海市"等
42
+
43
+ Returns:
44
+ 城市对应的adcode,如果未找到则返回None
45
+ """
46
+ # 先尝试直接匹配
47
+ if city_name in city_to_adcode:
48
+ return city_to_adcode[city_name]
49
+
50
+ # 如果未找到,尝试添加"市"或"省"后缀再查找
51
+ if not city_name.endswith("市") and not city_name.endswith("省"):
52
+ city_with_suffix = city_name + "市"
53
+ if city_with_suffix in city_to_adcode:
54
+ return city_to_adcode[city_with_suffix]
55
+
56
+ city_with_suffix = city_name + "省"
57
+ if city_with_suffix in city_to_adcode:
58
+ return city_to_adcode[city_with_suffix]
59
+
60
+ # 对于区级城市,尝试判断是否为区名
61
+ for full_name, code in city_to_adcode.items():
62
+ if city_name in full_name and (full_name.endswith("区") or "区" in full_name):
63
+ return code
64
+
65
+ return None
66
+
67
+ async def make_amap_request(params: Dict[str, str]) -> Dict[str, Any]:
68
+ """向高德地图API发送请求并获取天气数据
69
+
70
+ Args:
71
+ params: API请求参数
72
+
73
+ Returns:
74
+ API返回的JSON数据,如果请求失败则返回None
75
+ """
76
+ # 添加公共参数
77
+ params["key"] = AMAP_API_KEY
78
+
79
+ headers = {
80
+ "User-Agent": USER_AGENT
81
+ }
82
+
83
+ async with httpx.AsyncClient() as client:
84
+ try:
85
+ response = await client.get(AMAP_API_BASE, params=params, headers=headers, timeout=30.0)
86
+ response.raise_for_status()
87
+ return response.json()
88
+ except Exception as e:
89
+ print(f"API请求失败: {e}")
90
+ return None
91
+
92
+ def format_current_weather(weather_data: Dict[str, Any]) -> str:
93
+ """格式化实时天气信息
94
+
95
+ Args:
96
+ weather_data: 高德地图API返回的天气数据
97
+
98
+ Returns:
99
+ 格式化后的天气信息字符串
100
+ """
101
+ if not weather_data or "lives" not in weather_data or not weather_data["lives"]:
102
+ return "无法获取天气信息或数据格式错误"
103
+
104
+ live = weather_data["lives"][0]
105
+
106
+ return f"""
107
+ 城市: {live.get('city', '未知')}
108
+ 天气: {live.get('weather', '未知')}
109
+ 温度: {live.get('temperature', '未知')}°C
110
+ 风向: {live.get('winddirection', '未知')}
111
+ 风力: {live.get('windpower', '未知')}级
112
+ 湿度: {live.get('humidity', '未知')}%
113
+ 发布时间: {live.get('reporttime', '未知')}
114
+ """
115
+
116
  @tool
117
+ def get_current_weather(city: str) -> str:
118
+ """获取指定城市的实时天气
119
+
120
  Args:
121
+ city: 中国城市名称,如"北京市"、"上海市"、"广州市"等
122
  """
123
+ adcode = get_adcode_by_city(city)
124
+ if not adcode:
125
+ return f"无法找到城市'{city}'的编码,请检查城市名称是否正确"
126
+
127
+ params = {
128
+ "city": adcode,
129
+ "extensions": "base" # 获取实时天气
130
+ }
131
+
132
+ data = await make_amap_request(params)
133
+
134
+ if not data:
135
+ return f"获取{city}的天气信息失败"
136
+
137
+ if data.get("status") != "1":
138
+ return f"API返回错误: {data.get('info', '未知错误')}"
139
+
140
+ return format_current_weather(data)
141
+
142
 
143
  @tool
144
  def get_current_time_in_timezone(timezone: str) -> str:
 
177
 
178
  agent = CodeAgent(
179
  model=model,
180
+ tools=[final_answer, get_current_weather, get_current_time_in_timezone], ## add your tools here (don't remove final answer)
181
  max_steps=6,
182
  verbosity_level=1,
183
  grammar=None,