Update app.py
Browse files
app.py
CHANGED
@@ -94,10 +94,11 @@ def handle_csv_upload(file):
|
|
94 |
return_intermediate_steps=True
|
95 |
)
|
96 |
|
97 |
-
logging.info("[UPLOAD] Novo agente
|
98 |
-
|
99 |
except Exception as e:
|
100 |
logging.error(f"[ERRO] Falha ao processar novo CSV: {e}")
|
|
|
101 |
|
102 |
# === Inicialização ===
|
103 |
engine = create_engine_and_load_db(get_active_csv_path(), SQL_DB_PATH)
|
@@ -105,9 +106,35 @@ db = SQLDatabase(engine=engine)
|
|
105 |
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
|
106 |
sql_agent = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True, max_iterations=40, return_intermediate_steps=True)
|
107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
def generate_initial_context(db_sample):
|
109 |
return (
|
110 |
-
f"Você é um assistente que gera queries SQL objetivas e eficientes. Sempre inclua LIMIT
|
111 |
f"Exemplos do banco de dados:\n{db_sample.head().to_string(index=False)}\n\n"
|
112 |
"\n***IMPORTANTE***: Detecte automaticamente o idioma da pergunta do usuário e responda sempre no mesmo idioma.\n"
|
113 |
"Essa base de dados representa o sellout de 2025, janeiro, fevereiro e março até dia 11, de uma farmácia.\n"
|
@@ -213,12 +240,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
213 |
with gr.Row():
|
214 |
with gr.Column(scale=1):
|
215 |
gr.Markdown("## ⚙️ Configurações")
|
216 |
-
model_selector = gr.Dropdown(
|
217 |
-
choices=list(LLAMA_MODELS.keys()),
|
218 |
-
label="Escolha o Modelo LLM para gerar a query SQL",
|
219 |
-
value="LLaMA 70B"
|
220 |
-
)
|
221 |
csv_file = gr.File(label="📂 Enviar novo CSV", file_types=[".csv"])
|
|
|
|
|
|
|
|
|
|
|
222 |
|
223 |
with gr.Column(scale=4):
|
224 |
gr.Markdown("# 🧠 Anomalia Agent")
|
@@ -226,19 +254,21 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
226 |
msg = gr.Textbox(placeholder="Digite sua pergunta aqui...", label=" ", lines=1)
|
227 |
btn = gr.Button("Enviar", variant="primary")
|
228 |
history_btn = gr.Button("Histórico", variant="secondary")
|
|
|
229 |
|
230 |
-
def respond(message, chat_history,
|
231 |
-
response = chatbot_response(message,
|
232 |
chat_history.append((message, response))
|
233 |
return "", chat_history
|
234 |
|
235 |
msg.submit(respond, [msg, chatbot, model_selector], [msg, chatbot])
|
236 |
btn.click(respond, [msg, chatbot, model_selector], [msg, chatbot])
|
|
|
237 |
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
|
243 |
if __name__ == "__main__":
|
244 |
demo.launch(share=False)
|
|
|
94 |
return_intermediate_steps=True
|
95 |
)
|
96 |
|
97 |
+
logging.info("[UPLOAD] Novo banco carregado e agente recriado. Cache limpo.")
|
98 |
+
return "✅ CSV carregado com sucesso!"
|
99 |
except Exception as e:
|
100 |
logging.error(f"[ERRO] Falha ao processar novo CSV: {e}")
|
101 |
+
return f"❌ Erro ao processar CSV: {e}"
|
102 |
|
103 |
# === Inicialização ===
|
104 |
engine = create_engine_and_load_db(get_active_csv_path(), SQL_DB_PATH)
|
|
|
106 |
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
|
107 |
sql_agent = create_sql_agent(llm, db=db, agent_type="openai-tools", verbose=True, max_iterations=40, return_intermediate_steps=True)
|
108 |
|
109 |
+
def reset_app():
|
110 |
+
global engine, db, sql_agent, query_cache, history_log, recent_history
|
111 |
+
try:
|
112 |
+
if os.path.exists(UPLOADED_CSV_PATH):
|
113 |
+
os.remove(UPLOADED_CSV_PATH)
|
114 |
+
logging.info("[RESET] CSV personalizado removido.")
|
115 |
+
engine = create_engine_and_load_db(DEFAULT_CSV_PATH, SQL_DB_PATH)
|
116 |
+
db = SQLDatabase(engine=engine)
|
117 |
+
sql_agent = create_sql_agent(ChatOpenAI(model="gpt-4o-mini", temperature=0), db=db, agent_type="openai-tools")
|
118 |
+
query_cache.clear()
|
119 |
+
history_log.clear()
|
120 |
+
recent_history.clear()
|
121 |
+
return "🔄 Sistema resetado para o estado inicial."
|
122 |
+
except Exception as e:
|
123 |
+
return f"❌ Erro ao resetar: {e}"
|
124 |
+
|
125 |
+
def export_history_json():
|
126 |
+
path = "history_log.json"
|
127 |
+
pd.DataFrame(history_log).to_json(path, orient="records", indent=2)
|
128 |
+
return path
|
129 |
+
|
130 |
+
def export_history_csv():
|
131 |
+
path = "history_log.csv"
|
132 |
+
pd.DataFrame(history_log).to_csv(path, index=False)
|
133 |
+
return path
|
134 |
+
|
135 |
def generate_initial_context(db_sample):
|
136 |
return (
|
137 |
+
f"Você é um assistente que gera queries SQL objetivas e eficientes. Sempre inclua LIMIT 10 nas queries. Aqui está o banco de dados:\n\n"
|
138 |
f"Exemplos do banco de dados:\n{db_sample.head().to_string(index=False)}\n\n"
|
139 |
"\n***IMPORTANTE***: Detecte automaticamente o idioma da pergunta do usuário e responda sempre no mesmo idioma.\n"
|
140 |
"Essa base de dados representa o sellout de 2025, janeiro, fevereiro e março até dia 11, de uma farmácia.\n"
|
|
|
240 |
with gr.Row():
|
241 |
with gr.Column(scale=1):
|
242 |
gr.Markdown("## ⚙️ Configurações")
|
243 |
+
model_selector = gr.Dropdown(list(LLAMA_MODELS.keys()), label="Modelo LLM", value="LLaMA 70B")
|
|
|
|
|
|
|
|
|
244 |
csv_file = gr.File(label="📂 Enviar novo CSV", file_types=[".csv"])
|
245 |
+
upload_feedback = gr.Markdown()
|
246 |
+
reset_btn = gr.Button("🔄 Resetar")
|
247 |
+
export_json = gr.Button("📤 Exportar JSON")
|
248 |
+
export_csv = gr.Button("📤 Exportar CSV")
|
249 |
+
download_output = gr.File()
|
250 |
|
251 |
with gr.Column(scale=4):
|
252 |
gr.Markdown("# 🧠 Anomalia Agent")
|
|
|
254 |
msg = gr.Textbox(placeholder="Digite sua pergunta aqui...", label=" ", lines=1)
|
255 |
btn = gr.Button("Enviar", variant="primary")
|
256 |
history_btn = gr.Button("Histórico", variant="secondary")
|
257 |
+
history_output = gr.JSON()
|
258 |
|
259 |
+
def respond(message, chat_history, selected_model):
|
260 |
+
response = chatbot_response(message, selected_model)
|
261 |
chat_history.append((message, response))
|
262 |
return "", chat_history
|
263 |
|
264 |
msg.submit(respond, [msg, chatbot, model_selector], [msg, chatbot])
|
265 |
btn.click(respond, [msg, chatbot, model_selector], [msg, chatbot])
|
266 |
+
history_btn.click(toggle_history, outputs=history_output)
|
267 |
|
268 |
+
csv_file.change(handle_csv_upload, inputs=csv_file, outputs=upload_feedback)
|
269 |
+
reset_btn.click(reset_app, outputs=upload_feedback)
|
270 |
+
export_json.click(export_history_json, outputs=download_output)
|
271 |
+
export_csv.click(export_history_csv, outputs=download_output)
|
272 |
|
273 |
if __name__ == "__main__":
|
274 |
demo.launch(share=False)
|