天气接口优化

This commit is contained in:
weiweiw 2025-02-26 19:41:48 +08:00
parent d9acc07c59
commit 53d1700d29
2 changed files with 95 additions and 16 deletions

View File

@ -13,12 +13,41 @@ from .tools_registry import BaseToolOutput, regist_tool
@regist_tool(title="天气查询") @regist_tool(title="天气查询")
def weather_check( def weather_check(
city: str = Field(description="City name,include city and county,like '厦门'"), city: str = Field(description="City name,include city and county,like '厦门'"),
date: str = Field(description="日期参数,支持以下格式:\n"
"- '今天':获取当前实时天气\n"
"- '明天'/'后天'获取未来24/48小时预报\n"
"- '未来X天'获取最多7天预报'未来3天'\n"
# "- 具体日期格式为YYYY-MM-DD如'2024-07-05'"
)
): ):
"""用这个工具获取指定地点和指定时间的天气""" """用这个工具获取指定地点和指定时间的天气"""
print(f"weather_check tool内部调用city{city}") # 参数校验
missing_params = []
if not city:
missing_params.append("城市名称")
if not date:
missing_params.append("日期参数")
if missing_params:
return BaseToolOutput(
error_message=f"缺少必要参数:{', '.join(missing_params)},请补充完整查询信息",
require_additional_input=True
)
print(f"city:{city}, date:{date}")
try:
weatherType, number = parse_date_parameter(date)
except ValueError as e:
print(f"错误: {str(e)}") # 输出: 错误: 未来预报仅支持1-3天
return BaseToolOutput(str(e))
print(f"weather_check tool内部调用city{city},date:{date}")
tool_config = get_tool_config("weather_check") tool_config = get_tool_config("weather_check")
api_key = tool_config.get("api_key") api_key = tool_config.get("api_key")
print(f"weatherType:{weatherType}, number:{number}")
url = ''
if weatherType == "daily":
url = f"http://api.seniverse.com/v3/weather/now.json?key={api_key}&location={city}&language=zh-Hans&unit=c" url = f"http://api.seniverse.com/v3/weather/now.json?key={api_key}&location={city}&language=zh-Hans&unit=c"
logging.info(f"url:{url}") logging.info(f"url:{url}")
response = requests.get(url) response = requests.get(url)
@ -33,4 +62,54 @@ def weather_check(
else: else:
logging.error(f"Failed to retrieve weather: {response.status_code}") logging.error(f"Failed to retrieve weather: {response.status_code}")
raise Exception(f"Failed to retrieve weather: {response.status_code}") raise Exception(f"Failed to retrieve weather: {response.status_code}")
elif weatherType == "future":
url = f"http://api.seniverse.com/v3/weather/daily.json?key={api_key}&location={city}&language=zh-Hans&unit=c"
logging.info(f"url:{url}")
response = requests.get(url)
if response.status_code == 200:
data = response.json()
logging.info(f"response.json():{data}")
if number == "1":
weather = {
"date":"明天",
"low_temperature": data["results"][0]["daily"][1]["low"],
"high_temperature": data["results"][0]["daily"][1]["high"],
"description": data["results"][0]["daily"][1]["text_day"],
}
elif number == 2:
weather = {
"date":"后天",
"low_temperature": data["results"][0]["daily"][2]["low"],
"high_temperature": data["results"][0]["daily"][2]["high"],
"description": data["results"][0]["daily"][2]["text_day"],
}
elif number == 3:
weather = {
"明天天气": data["results"][0]["daily"][1]["text_day"],
"明天最低温度": data["results"][0]["daily"][1]["low"],
"明天最高温度": data["results"][0]["daily"][1]["high"],
"后天天气": data["results"][0]["daily"][2]["text_day"],
"后天最低温度": data["results"][0]["daily"][2]["low"],
"后天最高温度": data["results"][0]["daily"][2]["high"],
}
return BaseToolOutput(weather)
else:
logging.error(f"Failed to retrieve weather: {response.status_code}")
raise Exception(f"Failed to retrieve weather: {response.status_code}")
def parse_date_parameter(date_str: str) -> tuple:
"""解析日期参数返回API参数"""
# 处理自然语言
if date_str == "今天":
return "daily", 0
elif date_str == "明天":
return "future", 1
elif date_str == "后天":
return "future", 2
elif date_str.startswith("未来"):
days = int(date_str[2:-1])
if days < 1 or days > 3:
raise ValueError("未来预报仅支持1-3天")
return "future", days

View File

@ -398,7 +398,7 @@ def knowledge_base_page(api: ApiRequest, is_lite: bool = None):
cellEditor="agLargeTextCellEditor", cellEditor="agLargeTextCellEditor",
cellEditorPopup=True, cellEditorPopup=True,
autoWidth=True, autoWidth=True,
cellEditorParams= { "maxLength": 1000} cellEditorParams= { "maxLength": 1500}
) )
gb.configure_column( gb.configure_column(
"to_del", "to_del",