keenthinker's picture
Create WebSearch.py
75454b9 verified
raw
history blame
2.09 kB
# from langchain_community.tools import DuckDuckGoSearchRun
# search_tool = DuckDuckGoSearchRun()
# results = search_tool.invoke("Who's the current President of France?")
# print(results)
from langchain.tools import Tool
import random
import requests
import os
from dotenv import load_dotenv
load_dotenv()
weather_API_key = os.getenv("OPENWEATHER_KEY")
#print(f'weather_API_key: {weather_API_key}')
def get_weather_info(location: str) -> str:
"""Fetches weather information for a given location."""
try:
base_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": location,
"appid": weather_API_key,
"units": "metric"
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
weather = data["weather"][0]["description"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
print(f"\nWeather in {location.title()}:")
print(f"- Condition: {weather}")
print(f"- Temperature: {temp}°C (feels like {feels_like}°C)")
print(f"- Humidity: {humidity}%")
data= {"condition": weather, "temp_c": temp,"humidity": humidity}
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
# If the API call fails, we can use dummy data
# Dummy weather data
weather_conditions = [
{"condition": "Rainy", "temp_c": 15,"humidity": 30},
{"condition": "Clear", "temp_c": 25,"humidity": 50},
{"condition": "Windy", "temp_c": 20,"humidity": 80}
]
# Randomly select a weather condition
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
# Initialize the tool
weather_info_tool = Tool(
name="get_weather_info",
func=get_weather_info,
description="Fetches dummy weather information for a given location."
)