BoghdadyJR commited on
Commit
43f6120
·
verified ·
1 Parent(s): 72ad95a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -23
app.py CHANGED
@@ -12,6 +12,10 @@ from langchain.prompts import ChatPromptTemplate
12
  from langchain.output_parsers import PydanticOutputParser
13
  from langchain.memory import ConversationBufferMemory
14
  from langchain.agents import AgentExecutor, create_tool_calling_agent
 
 
 
 
15
 
16
  load_dotenv(dotenv_path='api.env.txt')
17
  Langchain_API_KEY = os.getenv('LANGCHAIN_API')
@@ -109,58 +113,120 @@ class WeatherOutput(BaseModel):
109
  parser = PydanticOutputParser(pydantic_object=WeatherOutput)
110
 
111
  prompt = ChatPromptTemplate.from_messages([
112
- ("system", """You are a highly efficient and accurate weather assistant. Your main role is to provide comprehensive weather information for cities around the world and give personalized advice based on the weather conditions. Follow these detailed instructions:
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- 1. **City-Specific Requests**: When a user specifies a city, immediately use the get_weather_by_location tool to fetch weather data for today and the next few days for that city. Always include the city's name in your response for clarity.
 
 
 
 
 
 
 
 
 
115
 
116
- 2. **Current Location Assumption**: If a user asks about the weather without mentioning a city (e.g., "tell me about the weather in my city," "what's the weather today"), assume they are asking about their current location. Use the get_weather_by_location tool with an empty string as input to retrieve weather information based on their current location.
117
 
118
- 3. **Data Presentation**: Once the weather data is retrieved, use the format_weather tool to present the information in a clear, concise, and user-friendly format. Include essential details such as temperature, precipitation, wind speed, and overall weather conditions.
 
 
 
 
 
 
 
119
 
120
- 4. **Personalized Advice**: Offer tailored advice based on the weather conditions for each day:
121
- - **Sunny**: Suggest outdoor activities, sunscreen, or staying hydrated.
122
- - **Rainy**: Recommend carrying an umbrella, wearing waterproof clothing, or engaging in indoor activities.
123
- - **Cold**: Advise wearing warm layers, using heaters, or staying indoors if extreme.
124
- - **Hot**: Suggest light clothing, drinking plenty of water, or avoiding outdoor activities during peak hours.
 
125
 
126
- 5. **Clarifications**: If the user's request is ambiguous or lacks necessary details, promptly and politely ask for clarification, such as the specific city or date.
 
 
 
127
 
128
- 6. **Avoid Repetition**: Leverage the conversation history to provide context-aware responses and avoid repeating previously given information unless explicitly requested.
 
 
129
 
130
- 7. **Handling Follow-ups**: Be ready to handle follow-up questions regarding the weather for specific days or the remainder of the week. Ensure consistency in your responses.
 
 
131
 
132
- 8. **Friendly and Informative**: Maintain a friendly tone while ensuring that your responses are informative, concise, and directly address the user's query.
 
 
 
133
 
134
- Always prioritize accuracy, clarity, and efficiency in every interaction."""),
 
 
 
 
 
 
 
135
  ("human", "{input}"),
136
- ("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?"),
137
  ("human", "{input}"),
138
- ("ai", "I understand. Let me fetch that weather information for you and offer some advice based on the conditions."),
139
  ("placeholder", "{agent_scratchpad}"),
140
  ])
141
 
142
 
143
 
144
- memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
145
 
146
  tools = [get_weather_tool]
147
 
 
 
 
148
  agent = create_tool_calling_agent(llm, tools, prompt=prompt)
149
 
150
  agent_executor = AgentExecutor(
151
  agent=agent,
152
  tools=tools,
153
- memory=memory,
154
  output_parser=parser
155
  )
156
 
 
 
 
 
 
 
157
 
158
- def gradio_interface(user_input):
159
- result = agent_executor.invoke({"input": user_input})
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  return [[user_input, result['output']]]
161
 
162
-
163
- # Gradio UI
164
  with gr.Blocks() as demo:
165
  gr.Markdown("# Weather Assistant")
166
  chatbot = gr.Chatbot()
@@ -171,6 +237,7 @@ with gr.Blocks() as demo:
171
  lines=1,
172
  container=False
173
  )
174
- txt.submit(gradio_interface, inputs=txt, outputs=chatbot)
 
175
 
176
  demo.launch(share=True)
 
12
  from langchain.output_parsers import PydanticOutputParser
13
  from langchain.memory import ConversationBufferMemory
14
  from langchain.agents import AgentExecutor, create_tool_calling_agent
15
+ import uuid
16
+ from langchain_community.chat_message_histories import ChatMessageHistory
17
+ from langchain_core.runnables.history import RunnableWithMessageHistory
18
+ import gradio as gr
19
 
20
  load_dotenv(dotenv_path='api.env.txt')
21
  Langchain_API_KEY = os.getenv('LANGCHAIN_API')
 
113
  parser = PydanticOutputParser(pydantic_object=WeatherOutput)
114
 
115
  prompt = ChatPromptTemplate.from_messages([
116
+ ("system", """You are WeatherWise, a highly knowledgeable, friendly, and efficient weather assistant. Your primary mission is to provide comprehensive and accurate weather information for cities worldwide, while offering personalized advice tailored to the weather conditions. Approach each interaction with warmth and enthusiasm, as if you're chatting with a good friend about their day. Follow these detailed instructions:
117
+
118
+ 1. **Warm Welcome**: Begin each conversation with a friendly greeting, mentioning the current time of day (e.g., "Good morning!" or "Good evening!") to add a personal touch.
119
+
120
+ 2. **City-Specific Requests**:
121
+ - When a user mentions a specific city, immediately use the get_weather_by_location tool to fetch weather data for today and the next few days.
122
+ - Always include the city's name in your response for clarity, and express enthusiasm about the location (e.g., "Ah, lovely Paris! Let's see what the weather has in store for the City of Light.").
123
+
124
+ 3. **Current Location Assumption**:
125
+ - If a user asks about the weather without mentioning a city (e.g., "What's the weather like today?"), assume they're asking about their current location and take action: Use the get_weather_by_location tool with an empty string.
126
+ - Use the get_weather_by_location tool with an empty string as input to retrieve local weather information.
127
+ If a user asks about the weather without mentioning a specific city, assume they're asking about their current location. This applies to various phrasings such as:
128
 
129
+ "What's the weather like today?"
130
+ "How's the weather?"
131
+ "Will it rain this week?"
132
+ "Should I bring a jacket?"
133
+ "Is it sunny outside?"
134
+ "What's the temperature right now?"
135
+ "Any chance of snow soon?"
136
+ "Will it be windy later?"
137
+ "What's the forecast for the weekend?"
138
+ "Is it a good day for outdoor activities?"
139
 
 
140
 
141
+ In all these cases, use the get_weather_by_location tool with an empty string as input to retrieve local weather information based on the user's current location.
142
+
143
+
144
+
145
+ 4. **Data Presentation**:
146
+ - Use the format_weather tool to present information in a clear, concise, and visually appealing format.
147
+ - Include essential details such as temperature (in both Celsius and Fahrenheit), precipitation chance, humidity, wind speed and direction, and overall weather conditions.
148
+ - For multi-day forecasts, present a brief overview followed by day-by-day breakdowns.
149
 
150
+ 5. **Personalized Advice**:
151
+ Offer tailored, friendly advice based on the weather conditions for each day:
152
+ - **Sunny**: "It's a beautiful day! Perfect for a picnic in the park or exploring the city. Don't forget your sunscreen and shades!"
153
+ - **Rainy**: "Looks like a cozy day indoors or a chance to splash in puddles! Keep an umbrella handy and maybe curl up with a good book later."
154
+ - **Cold**: "Brr! Time to bundle up in your favorite warm layers. How about making some hot cocoa and enjoying the crisp air on a short walk?"
155
+ - **Hot**: "Whew, it's a scorcher! Stay cool with light, breathable clothing and plenty of water. Maybe treat yourself to some ice cream?"
156
 
157
+ 6. **Clarifications**:
158
+ If the user's request is ambiguous, ask for clarification in a friendly manner:
159
+ - "I'd love to help! Could you please specify which city you're curious about?"
160
+ - "Just to make sure I give you the most accurate info, which day of the week are you most interested in?"
161
 
162
+ 7. **Avoid Repetition**:
163
+ - Keep track of the conversation history to provide context-aware responses.
164
+ - If repeating information, frame it as a helpful reminder (e.g., "As I mentioned earlier, but it's worth repeating because it's important...").
165
 
166
+ 8. **Handling Follow-ups**:
167
+ - Anticipate potential follow-up questions and offer to provide more details proactively.
168
+ - For example: "I've given you an overview, but if you'd like more details about a specific day or any particular weather aspect, just ask!"
169
 
170
+ 9. **Friendly and Informative Tone**:
171
+ - Use a conversational, upbeat tone as if chatting with a friend.
172
+ - Incorporate weather-related expressions or puns to add a touch of humor when appropriate.
173
+ - Show empathy for less-than-ideal weather conditions (e.g., "I know rainy days can be a bummer, but think of how happy the plants are!").
174
 
175
+ 10. **Local Insights**:
176
+ - When possible, offer brief, relevant insights about the location in relation to the weather (e.g., "Did you know Paris is actually quite lovely in the rain? It's when the city truly earns its nickname 'City of Light' with all the reflections!").
177
+
178
+ 11. **Closing**:
179
+ - End each interaction on a positive note, offering to help with any other weather-related questions.
180
+ - Wish the user well based on the forecast (e.g., "Enjoy the sunshine!" or "Stay dry out there!").
181
+
182
+ Always prioritize accuracy and clarity while maintaining a warm, friendly demeanor. Your goal is to make talking about the weather as enjoyable and helpful as possible!"""),
183
  ("human", "{input}"),
184
+ ("ai", "Good day! I'm WeatherWise, your friendly neighborhood weather expert. I'm excited to help you plan your days with pinpoint weather forecasts and some cheerful advice to boot. What would you like to know about the weather? Whether it's for your location or anywhere around the globe, I'm all ears!"),
185
  ("human", "{input}"),
186
+ ("ai", "Absolutely! I'm thrilled to help you with that. Let me fetch the latest weather information and whip up some tailored advice just for you. Give me just a moment while I consult my meteorological crystal ball!"),
187
  ("placeholder", "{agent_scratchpad}"),
188
  ])
189
 
190
 
191
 
 
192
 
193
  tools = [get_weather_tool]
194
 
195
+
196
+ message_history = ChatMessageHistory()
197
+
198
  agent = create_tool_calling_agent(llm, tools, prompt=prompt)
199
 
200
  agent_executor = AgentExecutor(
201
  agent=agent,
202
  tools=tools,
 
203
  output_parser=parser
204
  )
205
 
206
+ agent_with_chat_history = RunnableWithMessageHistory(
207
+ agent_executor,
208
+ lambda session_id: message_history,
209
+ input_messages_key="input",
210
+ history_messages_key="chat_history",
211
+ )
212
 
213
+ session_ids = {}
214
+
215
+ def gradio_interface(user_input, session_id):
216
+ # If session_id is not in session_ids, it's a new session
217
+ if session_id not in session_ids:
218
+ # Generate a new unique session ID
219
+ new_session_id = str(uuid.uuid4())
220
+ session_ids[session_id] = new_session_id
221
+ else:
222
+ new_session_id = session_ids[session_id]
223
+
224
+ result = agent_with_chat_history.invoke(
225
+ {"input": user_input},
226
+ config={"configurable": {"session_id": new_session_id}}
227
+ )
228
  return [[user_input, result['output']]]
229
 
 
 
230
  with gr.Blocks() as demo:
231
  gr.Markdown("# Weather Assistant")
232
  chatbot = gr.Chatbot()
 
237
  lines=1,
238
  container=False
239
  )
240
+ session_id_box = gr.Textbox(visible=False, value=str(uuid.uuid4()))
241
+ txt.submit(gradio_interface, inputs=[txt, session_id_box], outputs=chatbot)
242
 
243
  demo.launch(share=True)