Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add weather tool #125

Merged
merged 5 commits into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/pai_rag/config/settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,5 @@ type = "SimpleSummarize"
text_qa_template = "参考内容信息如下\n---------------------\n{context_str}\n---------------------根据提供内容而非其他知识回答问题.\n问题: {query_str}\n答案: \n"

[rag.tool]
type = ["calculator"]
type = ["calculator","weather"]
weather_api_key =""
18 changes: 18 additions & 0 deletions src/pai_rag/modules/tool/default_tool_description_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,21 @@

Example uses of this tool include but are not limited to calculating age differences, determining the number of items sold from inventory, working out loan repayments, and any other context where subtraction of numerical values plays a key role.
"""

DEFAULT_GET_WEATHER = """
The get_weather tool has been meticulously crafted to fetch real-time weather data for any global location, empowering users with accurate meteorological insights. Whether you're planning outdoor activities, assessing travel conditions, monitoring agricultural climates, or simply staying informed about the day's weather, this tool offers a streamlined solution. It taps into reputable weather APIs to deliver up-to-date information on temperature, humidity, precipitation, wind conditions, and more, ensuring you're equipped with the latest atmospheric conditions.

get_weather(city: str) -> str
This function not only provides current weather conditions but also encompasses forecast data when supported by the API, thereby catering to a wide array of weather-dependent decision-making processes. The returned dictionary encapsulates various weather parameters, enabling detailed analysis tailored to your needs.

Args:
city (str): The name of the city, town, or specific location for which weather data is desired. Ensure the input adheres to the API's naming conventions for optimal results.

Returns:
str: A neatly packaged string presenting the time, city, temperature in Celsius or Fahrenheit (as per the API's standard setting), and a brief description of the weather, such as "sunny," "partly cloudy," or "light rain." This format facilitates easy reading and can be seamlessly integrated into messages, notifications, or displayed on-screen.

Raises:
ValueError: If the 'city' input is invalid or unrecognizable, ensuring that errors are promptly communicated for corrective action.

Embracing versatility, the get_weather tool finds application in travel planning, event organization, health advisories related to extreme weather, educational projects studying climatology, and everyday life decisions influenced by the elements. Its capability to distill complex meteorological data into digestible insights underscores its value as an indispensable utility in understanding our dynamic atmospheric surroundings.
"""
4 changes: 4 additions & 0 deletions src/pai_rag/modules/tool/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
get_google_web_search_tools,
get_calculator_tools,
get_customized_tools,
get_weather_tool,
moria97 marked this conversation as resolved.
Show resolved Hide resolved
)


Expand Down Expand Up @@ -36,4 +37,7 @@ def _create_new_instance(self, new_params: Dict[str, Any]):
if "custom" in type:
tools.extend(get_customized_tools(self.config))

if "weather" in type:
tools.extend(get_weather_tool(self.config))

return tools
31 changes: 31 additions & 0 deletions src/pai_rag/modules/tool/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
import json
import os
import sys
import requests
from pai_rag.modules.tool.default_tool_description_template import (
DEFAULT_GOOGLE_SEARCH_TOOL_DESP,
DEFAULT_CALCULATE_MULTIPLY,
DEFAULT_CALCULATE_ADD,
DEFAULT_CALCULATE_DIVIDE,
DEFAULT_CALCULATE_SUBTRACT,
DEFAULT_GET_WEATHER,
)


Expand Down Expand Up @@ -75,6 +77,35 @@ def subtract(a: int, b: int) -> int:
return [multiply_tool, add_tool, divide_tool, subtract_tool]


def get_weather_tool(config):
def get_place_weather(city: str) -> str:
"""Get city name and return city weather"""
api_key = config.get("weather_api_key", None)
# 可以直接赋值给api_key,原始代码的config只有type类型。
base_url = "http://api.openweathermap.org/data/2.5/forecast?"
complete_url = f"{base_url}q={city}&appid={api_key}&lang=zh_cn&units=metric"
response = requests.get(complete_url)
weather_data = response.json()

if weather_data["cod"] != "200":
print(f"获取天气信息失败,错误代码:{weather_data['cod']}")
return None

element = weather_data["list"][0]

return str(
f"{city}的天气:\n 时间: {element['dt_txt']}\n 温度: {element['main']['temp']} °C\n 天气描述: {element['weather'][0]['description']}\n"
)

weather_tool = FunctionTool.from_defaults(
fn=get_place_weather,
name="get_weather",
description=DEFAULT_GET_WEATHER,
)

return [weather_tool]


def get_customized_tools(config):
func_path = config["func_path"]
sys.path.append(func_path)
Expand Down
Loading