Source code for langchain_community.utilities.openweathermap
"""Util that calls OpenWeatherMap using PyOWM."""fromtypingimportAny,Dict,Optionalfromlangchain_core.utilsimportget_from_dict_or_envfrompydanticimportBaseModel,ConfigDict,model_validator
[docs]classOpenWeatherMapAPIWrapper(BaseModel):"""Wrapper for OpenWeatherMap API using PyOWM. Docs for using: 1. Go to OpenWeatherMap and sign up for an API key 2. Save your API KEY into OPENWEATHERMAP_API_KEY env variable 3. pip install pyowm """owm:Any=Noneopenweathermap_api_key:Optional[str]=Nonemodel_config=ConfigDict(extra="forbid",)@model_validator(mode="before")@classmethoddefvalidate_environment(cls,values:Dict)->Any:"""Validate that api key exists in environment."""openweathermap_api_key=get_from_dict_or_env(values,"openweathermap_api_key","OPENWEATHERMAP_API_KEY")try:importpyowmexceptImportError:raiseImportError("pyowm is not installed. Please install it with `pip install pyowm`")owm=pyowm.OWM(openweathermap_api_key)values["owm"]=owmreturnvaluesdef_format_weather_info(self,location:str,w:Any)->str:detailed_status=w.detailed_statuswind=w.wind()humidity=w.humiditytemperature=w.temperature("celsius")rain=w.rainheat_index=w.heat_indexclouds=w.cloudsreturn(f"In {location}, the current weather is as follows:\n"f"Detailed status: {detailed_status}\n"f"Wind speed: {wind['speed']} m/s, direction: {wind['deg']}°\n"f"Humidity: {humidity}%\n"f"Temperature: \n"f" - Current: {temperature['temp']}°C\n"f" - High: {temperature['temp_max']}°C\n"f" - Low: {temperature['temp_min']}°C\n"f" - Feels like: {temperature['feels_like']}°C\n"f"Rain: {rain}\n"f"Heat index: {heat_index}\n"f"Cloud cover: {clouds}%")
[docs]defrun(self,location:str)->str:"""Get the current weather information for a specified location."""mgr=self.owm.weather_manager()observation=mgr.weather_at_place(location)w=observation.weatherreturnself._format_weather_info(location,w)