MathWizard1729 commited on
Commit
7ad4ea6
·
verified ·
1 Parent(s): 3828a36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +233 -63
app.py CHANGED
@@ -1,64 +1,234 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import requests
4
+ import boto3
5
+ import streamlit as st
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ # Environment config
11
+ OPENWEATHERMAP_API_KEY = os.getenv("OPENWEATHERMAP_API_KEY")
12
+ AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
13
+
14
+ # Bedrock Claude client
15
+ bedrock = boto3.client("bedrock-runtime", region_name=AWS_REGION)
16
+
17
+ # App UI
18
+ st.title("Weather Assistant - Umbrella Advisor")
19
+ st.markdown("Ask me if you should carry an umbrella tomorrow!")
20
+
21
+ # Session state for chat
22
+ if "messages" not in st.session_state:
23
+ st.session_state.messages = []
24
+
25
+ # Chat history display
26
+ for msg in st.session_state.messages:
27
+ with st.chat_message(msg["role"]):
28
+ st.markdown(msg["content"])
29
+
30
+
31
+ def get_weather(location):
32
+ """Get weather forecast for a specific location"""
33
+ print(f"Getting weather for: {location}")
34
+
35
+ # Validate location input
36
+ if not location or location.strip() == "":
37
+ return {"error": "Please specify a valid location/city name."}
38
+
39
+ location = location.strip()
40
+ geo_url = f"http://api.openweathermap.org/geo/1.0/direct?q={location}&limit=1&appid={OPENWEATHERMAP_API_KEY}"
41
+
42
+ try:
43
+ geo_resp = requests.get(geo_url).json()
44
+
45
+ if not geo_resp or len(geo_resp) == 0:
46
+ return {"error": f"Location '{location}' not found. Please check the spelling and try again."}
47
+
48
+ lat, lon = geo_resp[0]['lat'], geo_resp[0]['lon']
49
+ except (KeyError, IndexError, requests.RequestException) as e:
50
+ return {"error": f"Error getting location data for '{location}': {str(e)}"}
51
+ try:
52
+ weather_url = f"http://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={OPENWEATHERMAP_API_KEY}&units=metric"
53
+ weather_data = requests.get(weather_url).json()
54
+
55
+ if 'list' not in weather_data:
56
+ return {"error": f"Unable to get weather forecast for '{location}'."}
57
+
58
+ forecast = []
59
+ for f in weather_data['list'][:8]: # Next 24 hours
60
+ forecast.append({
61
+ "time": f["dt_txt"],
62
+ "description": f["weather"][0]["description"],
63
+ "rain_probability": f.get("pop", 0) * 100,
64
+ "temp": f["main"]["temp"],
65
+ "humidity": f["main"]["humidity"]
66
+ })
67
+
68
+ return {
69
+ "location": location,
70
+ "forecast": forecast
71
+ }
72
+ except (KeyError, requests.RequestException) as e:
73
+ return {"error": f"Error getting weather forecast for '{location}': {str(e)}"}
74
+
75
+
76
+ def generate_react_response(user_input, conversation_history=""):
77
+ """Generate response using ReAct (Reasoning + Acting) approach"""
78
+
79
+ system_prompt = """You are a helpful weather assistant that uses ReAct (Reasoning + Acting) methodology to help users decide about carrying umbrellas.
80
+
81
+ Follow this process:
82
+ 1. **Think**: Analyze what the user is asking
83
+ 2. **Act**: Use available tools if needed
84
+ 3. **Observe**: Process the results
85
+ 4. **Reason**: Draw conclusions and provide advice
86
+
87
+ Available tools:
88
+ - get_weather(location): Gets weather forecast for tomorrow
89
+
90
+ When you need to get weather data, respond with this JSON format:
91
+ {
92
+ "thought": "I need to get weather data for [location] to advise about umbrella",
93
+ "action": "get_weather",
94
+ "action_input": {"location": "city_name"}
95
+ }
96
+
97
+ When you have all needed information, provide a conversational response that includes:
98
+ - The location
99
+ - Your reasoning based on weather conditions
100
+ - Clear umbrella advice
101
+
102
+ Example: "You do not need to carry an umbrella tomorrow as the weather in New York will be sunny with no chance of rain."
103
+
104
+ If the user doesn't specify a location, ask them to specify it conversationally."""
105
+
106
+ # Build conversation context
107
+ messages = [
108
+ {"role": "user", "content": f"{system_prompt}\n\nConversation history: {conversation_history}\n\nUser: {user_input}"}
109
+ ]
110
+
111
+ claude_body = {
112
+ "anthropic_version": "bedrock-2023-05-31",
113
+ "max_tokens": 1000,
114
+ "temperature": 0.7,
115
+ "top_p": 0.9,
116
+ "messages": messages
117
+ }
118
+
119
+ response = bedrock.invoke_model(
120
+ modelId="anthropic.claude-3-sonnet-20240229-v1:0",
121
+ contentType="application/json",
122
+ accept="application/json",
123
+ body=json.dumps(claude_body),
124
+ )
125
+
126
+ content = json.loads(response["body"].read())["content"][0]["text"].strip()
127
+
128
+ # Try to parse as ReAct JSON
129
+ try:
130
+ react_response = json.loads(content)
131
+
132
+ if react_response.get("action") == "get_weather":
133
+ location = react_response.get("action_input", {}).get("location", "").strip()
134
+ thought = react_response.get("thought", "")
135
+
136
+ # Validate location before calling weather function
137
+ if not location:
138
+ return "I need to know which city or location you're asking about. Could you please specify the location?"
139
+
140
+ # Get weather data
141
+ weather_data = get_weather(location)
142
+
143
+ if "error" in weather_data:
144
+ return weather_data["error"]
145
+
146
+ # Process weather data and generate final reasoning
147
+ try:
148
+ reasoning_prompt = f"""Based on this weather data for {location}, provide your final umbrella recommendation:
149
+
150
+ Weather forecast: {json.dumps(weather_data, indent=2)}
151
+
152
+ Your previous thought: {thought}
153
+
154
+ Provide a conversational response that includes:
155
+ 1. The location
156
+ 2. Your reasoning based on the weather conditions
157
+ 3. Clear umbrella advice
158
+
159
+ Format like: "You [do/do not] need to carry an umbrella tomorrow as the weather in [location] will be [conditions and reasoning]."
160
  """
161
+
162
+ final_messages = [{"role": "user", "content": reasoning_prompt}]
163
+
164
+ final_body = {
165
+ "anthropic_version": "bedrock-2023-05-31",
166
+ "max_tokens": 500,
167
+ "temperature": 0.7,
168
+ "messages": final_messages
169
+ }
170
+
171
+ final_response = bedrock.invoke_model(
172
+ modelId="anthropic.claude-3-sonnet-20240229-v1:0",
173
+ contentType="application/json",
174
+ accept="application/json",
175
+ body=json.dumps(final_body),
176
+ )
177
+
178
+ final_content = json.loads(final_response["body"].read())["content"][0]["text"].strip()
179
+ return final_content
180
+ except Exception as e:
181
+ return f"Error processing weather data: {str(e)}"
182
+
183
+ except json.JSONDecodeError:
184
+ # If not JSON, return the content as is (probably asking for location)
185
+ pass
186
+
187
+ return content
188
+
189
+
190
+ def build_conversation_history():
191
+ """Build conversation history for context"""
192
+ history = []
193
+ for msg in st.session_state.messages[-4:]: # Last 4 messages for context
194
+ history.append(f"{msg['role'].capitalize()}: {msg['content']}")
195
+ return "\n".join(history)
196
+
197
+
198
+ if prompt := st.chat_input("Type your question here..."):
199
+ st.session_state.messages.append({"role": "user", "content": prompt})
200
+ with st.chat_message("user"):
201
+ st.markdown(prompt)
202
+
203
+ with st.chat_message("assistant"):
204
+ with st.spinner("Thinking..."):
205
+ conversation_history = build_conversation_history()
206
+ reply = generate_react_response(prompt, conversation_history)
207
+ st.markdown(reply)
208
+ st.session_state.messages.append({"role": "assistant", "content": reply})
209
+
210
+
211
+ with st.sidebar:
212
+ st.header("About")
213
+ st.markdown("""
214
+ - Powered by **AWS Bedrock (Claude Sonnet)**
215
+ - Uses **ReAct (Reasoning + Acting)** methodology
216
+ - Retrieves real-time data from **OpenWeatherMap**
217
+ - Provides step-by-step reasoning for umbrella advice
218
+ """)
219
+
220
+ st.subheader("Sample Prompts")
221
+ st.markdown("""
222
+ - Should I bring an umbrella tomorrow?
223
+ - Will it rain in Delhi tomorrow?
224
+ - Do I need an umbrella in Tokyo?
225
+ - Should I carry an umbrella tomorrow in London?
226
+ """)
227
+
228
+ st.subheader("ReAct Process")
229
+ st.markdown("""
230
+ 1. **Think**: Analyze your question
231
+ 2. **Act**: Get weather data if needed
232
+ 3. **Observe**: Process weather information
233
+ 4. **Reason**: Provide umbrella advice with explanation
234
+ """)