Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,63 +1,153 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
response = ""
|
| 29 |
-
|
| 30 |
-
for message in client.chat_completion(
|
| 31 |
-
messages,
|
| 32 |
-
max_tokens=max_tokens,
|
| 33 |
-
stream=True,
|
| 34 |
-
temperature=temperature,
|
| 35 |
-
top_p=top_p,
|
| 36 |
-
):
|
| 37 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
-
|
| 42 |
-
"""
|
| 43 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 44 |
-
"""
|
| 45 |
-
demo = gr.ChatInterface(
|
| 46 |
-
respond,
|
| 47 |
-
additional_inputs=[
|
| 48 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 49 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 50 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 51 |
-
gr.Slider(
|
| 52 |
-
minimum=0.1,
|
| 53 |
-
maximum=1.0,
|
| 54 |
-
value=0.95,
|
| 55 |
-
step=0.05,
|
| 56 |
-
label="Top-p (nucleus sampling)",
|
| 57 |
-
),
|
| 58 |
-
],
|
| 59 |
)
|
| 60 |
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 5 |
+
from langchain_core.tools import tool
|
| 6 |
+
from langchain.pydantic_v1 import BaseModel, Field
|
| 7 |
+
import requests
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from typing import List
|
| 10 |
+
from langchain.prompts import ChatPromptTemplate
|
| 11 |
+
from langchain.output_parsers import PydanticOutputParser
|
| 12 |
+
from langchain.memory import ConversationBufferMemory
|
| 13 |
+
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 14 |
+
|
| 15 |
+
load_dotenv(dotenv_path='api.env.txt')
|
| 16 |
+
Langchain_API_KEY = os.getenv('LANGCHAIN_API')
|
| 17 |
+
GOOGLE_API_KEY = os.getenv('GOOGLE_API')
|
| 18 |
+
WEATHER_API_KEY = os.getenv('WEATHER_API')
|
| 19 |
+
|
| 20 |
+
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
|
| 21 |
+
|
| 22 |
+
llm = ChatGoogleGenerativeAI(
|
| 23 |
+
model="gemini-1.5-flash",
|
| 24 |
+
temperature=0,
|
| 25 |
+
max_tokens=None,
|
| 26 |
+
timeout=None,
|
| 27 |
+
max_retries=2,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
|
| 30 |
|
| 31 |
+
|
| 32 |
+
class WeatherInput(BaseModel):
|
| 33 |
+
city: str = Field(default=None, description="The city to get the weather for.")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_location_from_ip():
|
| 37 |
+
ip = requests.get('https://api.ipify.org').text
|
| 38 |
+
response = requests.get(f"https://ipapi.co/{ip}/json/").json()
|
| 39 |
+
return {
|
| 40 |
+
'city': response.get('city'),
|
| 41 |
+
'latitude': response.get('latitude'),
|
| 42 |
+
'longitude': response.get('longitude')
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@tool("get_weather_by_location", args_schema=WeatherInput, return_direct=True)
|
| 47 |
+
def get_weather_by_location(city: str = None):
|
| 48 |
+
if not city:
|
| 49 |
+
location = get_location_from_ip()
|
| 50 |
+
city = location['city']
|
| 51 |
+
|
| 52 |
+
url = f"https://api.tomorrow.io/v4/timelines?apikey={WEATHER_API_KEY}"
|
| 53 |
+
payload = {
|
| 54 |
+
"location": city,
|
| 55 |
+
"fields": ["temperature", "humidity", "windSpeed"],
|
| 56 |
+
"units": "metric",
|
| 57 |
+
"timesteps": ["1d"],
|
| 58 |
+
"startTime": "now",
|
| 59 |
+
"endTime": "nowPlus5d",
|
| 60 |
+
"timezone": "auto"
|
| 61 |
+
}
|
| 62 |
+
headers = {
|
| 63 |
+
"accept": "application/json",
|
| 64 |
+
"content-type": "application/json"
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
response = requests.post(url, json=payload, headers=headers).json()
|
| 68 |
+
|
| 69 |
+
return format_weather_response(response, city)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def format_weather_response(weather_data, city):
|
| 73 |
+
intervals = weather_data['data']['timelines'][0]['intervals']
|
| 74 |
+
response = f"Weather forecast for {city}:\n\n"
|
| 75 |
+
|
| 76 |
+
for interval in intervals:
|
| 77 |
+
date = datetime.fromisoformat(interval['startTime']).strftime("%A, %B %d")
|
| 78 |
+
temp = round(interval['values']['temperature'], 1)
|
| 79 |
+
humidity = round(interval['values']['humidity'], 1)
|
| 80 |
+
wind_speed = round(interval['values']['windSpeed'], 1)
|
| 81 |
+
|
| 82 |
+
response += f"{date}:\n"
|
| 83 |
+
response += f" Temperature: {temp}°C\n"
|
| 84 |
+
response += f" Humidity: {humidity}%\n"
|
| 85 |
+
response += f" Wind Speed: {wind_speed} km/h\n\n"
|
| 86 |
+
|
| 87 |
+
return response
|
| 88 |
+
|
| 89 |
+
class DailyWeather(BaseModel):
|
| 90 |
+
date: str
|
| 91 |
+
temperature: float
|
| 92 |
+
condition: str
|
| 93 |
+
humidity: float
|
| 94 |
+
wind_speed: float
|
| 95 |
+
advice: str
|
| 96 |
+
|
| 97 |
+
class WeatherOutput(BaseModel):
|
| 98 |
+
location: str = Field(description="The location or the city for which the weather is reported")
|
| 99 |
+
forecast: List[DailyWeather] = Field(description="The weather forecast for multiple days")
|
| 100 |
+
|
| 101 |
+
parser = PydanticOutputParser(pydantic_object=WeatherOutput)
|
| 102 |
+
|
| 103 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 104 |
+
("system", """You are a helpful weather assistant. Your primary function is to provide weather information for cities around the world and offer advice based on the weather conditions. Here are your key responsibilities:
|
| 105 |
+
|
| 106 |
+
1. If a user asks about the weather in a specific city, use the get_weather_by_location tool to fetch and provide that information for today and the next few days.
|
| 107 |
+
2. If a user asks about the weather without specifying a city (e.g., "tell me the weather in my city" or "what is the weather in our city/town"), assume they're asking about their current location. Use the get_weather_by_location tool with an empty string as input to get this information.
|
| 108 |
+
3. After getting the weather data, always use the format_weather tool to present the information in a user-friendly format and include advice for each day.
|
| 109 |
+
4. Based on the weather conditions, provide relevant advice to the user for each day. For example:
|
| 110 |
+
- If it's sunny, suggest outdoor activities or remind them to use sunscreen.
|
| 111 |
+
- If it's rainy, advise them to bring an umbrella or suggest indoor activities.
|
| 112 |
+
- If it's very cold or hot, give appropriate clothing or safety recommendations.
|
| 113 |
+
5. If you're unsure about the location or need more information, politely ask the user for clarification.
|
| 114 |
+
6. Be prepared to answer follow-up questions about the weather for the rest of the week or for a specific day.
|
| 115 |
+
|
| 116 |
+
Remember to be friendly and informative in your responses, and focus on providing a full weather forecast when asked. Use the conversation history to provide context-aware responses and avoid repeating information."""),
|
| 117 |
+
("human", "{input}"),
|
| 118 |
+
("ai", "Hello! I'd be happy to help you with the weather information for the next few days and provide some helpful advice. What would you like to know?"),
|
| 119 |
+
("human", "{input}"),
|
| 120 |
+
("ai", "I understand. Let me fetch that weather information for you and offer some advice based on the conditions."),
|
| 121 |
+
("placeholder", "{agent_scratchpad}"),
|
| 122 |
+
])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Initialize tools and agent
|
| 126 |
+
tools = [get_weather_by_location]
|
| 127 |
+
|
| 128 |
+
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
| 129 |
+
|
| 130 |
+
agent = create_tool_calling_agent(llm, tools, prompt=prompt)
|
| 131 |
+
|
| 132 |
+
agent_executor = AgentExecutor(
|
| 133 |
+
agent=agent,
|
| 134 |
+
tools=tools,
|
| 135 |
+
memory=memory,
|
| 136 |
+
output_parser=PydanticOutputParser(pydantic_object=WeatherOutput)
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def gradio_interface(user_input):
|
| 141 |
+
result = agent_executor.invoke({"input": user_input})
|
| 142 |
+
return result['output']
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# Gradio UI
|
| 146 |
+
with gr.Blocks() as demo:
|
| 147 |
+
gr.Markdown("# Weather Assistant")
|
| 148 |
+
chatbot = gr.Chatbot()
|
| 149 |
+
with gr.Row():
|
| 150 |
+
txt = gr.Textbox(show_label=False, placeholder="Ask about the weather...").style(container=False)
|
| 151 |
+
txt.submit(gradio_interface, txt, chatbot)
|
| 152 |
+
|
| 153 |
+
demo.launch()
|