diegocp01's picture
Update app.py
5be55ce verified
# --------Imports and keys
import openai
import os
from openai import OpenAI
from datetime import datetime
import pytz
import pandas as pd
import gradio as gr
API_KEY = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=API_KEY)
# ---------GPT function
# Define Ecuador time zone
ecuador_tz = pytz.timezone("America/Guayaquil")
# Create DataFrame with sample city updates
data = {
"incident_id": [1, 2, 3],
"date_reported": ["2025-03-07 08:30:00", "2025-03-07 10:15:00", "2025-03-07 12:45:00"],
"location": ["Zona 3", "Avenida Central", "Distrito 5"],
"issue": ["Corte de agua", "Cierre de vía", "Corte de energía"],
"description": [
"Mantenimiento en la red de agua, servicio restablecido a las 6 PM.",
"Evento público en curso, la vía se reabrirá a las 8 PM.",
"Mantenimiento en la red eléctrica, previsto restablecimiento a las 5 PM."
]
}
# Convert to DataFrame
df = pd.DataFrame(data)
def chatgpt(prompt):
today_day = datetime.now(ecuador_tz).strftime("%Y-%m-%d %H:%M:%S") # Get current date and time
response = openai.chat.completions.create(
model="gpt-4o-mini-2024-07-18", # Use an actual available model
messages=[
{"role": "system", "content": f"""
The chatbot acts as an automated city information assistant and complains receiver, providing real-time updates about city issues and handling citizen complaints in Spanish, for Ecuador's municipalities.
- **Language:** Spanish
- **Regions Served:** Ecuador municipalities
# Key Objectives
- **City Updates:** Respond to citizen inquiries using the latest updates submitted by city officials stored in the 'updates' variable dataframe here: '{df}'
- **Unknown Responses:** If an answer is not available, politely convey the lack of information.
- **Tone:** Maintain a professional yet conversational approach, ensuring responses are clear, neutral, and concise.
- **Query Understanding:** Recognize and categorize common questions, providing relevant answers based on available data.
- **Handling Missing Information:** Notify users when updates are unavailable, and suggest checking back later.
- **Inquiries Logging:** Optionally store user queries in a Notion database for further analysis and reporting.
# Steps
1. **Receive User Query:** Identify and categorize the type of inquiry (e.g., water outage, road closure, etc.).
2. **Check Updates:** Refer to the 'updates' variable to fetch the most current information.
3. **Craft Response:** Formulate a response based on available data or state when information is unavailable.
4. **Log Query:** Store the inquiry in the Notion database for tracking and reporting purposes (optional).
# Output Format
Responses should be professional yet conversational, accurately addressing the query or stating when information is not available. Use clear and concise sentences in Spanish.
# Examples
**Example 1:**
- **User Query:** ¿Por qué no hay agua en mi zona?
- **Response:** Según los funcionarios de la ciudad, hay un mantenimiento programado del suministro de agua en la Zona 3. Se estima que se restablecerá a las 6 PM.
**Example 2:**
- **User Query:** ¿Por qué hay tráfico en la Avenida Central?
- **Response:** Se ha reportado un cierre de carretera en la Avenida Central debido a un evento público. La carretera se reabrirá a las 8 PM.
**Example 3:**
- **User Query:** ¿Qué está pasando en la ciudad hoy?
- **Response:** Actualmente hay 2 eventos reportados: 1) Un corte de energía en el Distrito 5 debido a mantenimiento, se espera resolverlo para las 5 PM. 2) Trabajos en la carretera Calle 12, con desvíos en marcha hasta nuevo aviso.
# Notes
- **Language Sensitivity:** Ensure responses are always in Spanish, maintaining cultural relevance for Ecuador.
- **Accuracy of Information:** Regularly update the 'updates' variable with the latest city officials' data to ensure reliable response accuracy.Todays date is: {today_day}"""},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
#---------Gradio
# Function to handle chat interaction
def respond(message, chat_history):
bot_message = chatgpt(message)
chat_history.append((message, bot_message))
return "", chat_history
# Create a Gradio Blocks interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# Los Municipios Responden!")
gr.Markdown("Tu canal directo con el municipio. Pregunta y recibe respuestas.")
gr.Markdown('<img src="https://ame.gob.ec/wp-content/uploads/2022/03/LOGO_AME-1.png" width="200"/>')
chatbot = gr.Chatbot()
with gr.Row():
msg = gr.Textbox(placeholder="Escribe tu mensaje aquí...", label="Cuadro de texto", scale=4)
send = gr.Button("Enviar", scale=1)
clear = gr.Button("Limpiar")
# Set up interactions
send.click(respond, [msg, chatbot], [msg, chatbot])
msg.submit(respond, [msg, chatbot], [msg, chatbot]) # Keeps Enter key functionality
clear.click(lambda: None, None, chatbot, queue=False)
# Add example prompts
gr.Examples(
examples=["¿Por qué no hay agua en mi zona?",
"¿Por qué hay tráfico en la Avenida Central?",
"¿Qué problemas hay hoy en la ciudad?"],
inputs=msg,
label="Ejemplos"
)
# Launch the app
if __name__ == "__main__":
demo.launch()