Jeremy Live commited on
Commit
a8d5643
·
1 Parent(s): 1b58e4c

Convert chat history to the format expected by Gradio 5.x

Browse files
Files changed (1) hide show
  1. app.py +55 -23
app.py CHANGED
@@ -197,9 +197,22 @@ def generate_plot(data, x_col, y_col, title, x_label, y_label):
197
 
198
  return plot_path
199
 
 
 
 
 
 
 
 
 
 
 
 
200
  async def stream_agent_response(question: str, chat_history: List) -> Tuple[List, Dict]:
201
  """Procesa la pregunta del usuario y devuelve la respuesta del agente."""
202
-
 
 
203
  if not agent:
204
  error_msg = (
205
  "## ⚠️ Error: Agente no inicializado\n\n"
@@ -209,26 +222,26 @@ async def stream_agent_response(question: str, chat_history: List) -> Tuple[List
209
  f"3. El modelo de lenguaje esté disponible\n\n"
210
  f"Error: {agent_error}"
211
  )
212
- chat_history = chat_history + [[question, error_msg]]
213
- yield chat_history, gr.update(visible=False)
214
- return
215
 
216
  try:
217
- # Agregar un mensaje de "pensando"
218
- chat_history = chat_history + [[question, None]]
219
- yield chat_history, gr.update(visible=False)
220
 
221
- # Ejecutar el agente
222
- response = await agent.ainvoke({"input": question, "chat_history": chat_history[:-1]})
223
 
224
- # Procesar la respuesta
225
  if hasattr(response, 'output'):
226
  response_text = response.output
227
 
228
- # Verificar si la respuesta contiene una consulta SQL
229
  sql_query = extract_sql_query(response_text)
230
  if sql_query:
231
- # Ejecutar la consulta y actualizar la respuesta
232
  db_connection, _ = setup_database_connection()
233
  if db_connection:
234
  query_result = execute_sql_query(sql_query, db_connection)
@@ -238,14 +251,14 @@ async def stream_agent_response(question: str, chat_history: List) -> Tuple[List
238
  else:
239
  response_text = "Error: No se recibió respuesta del agente."
240
 
241
- # Actualizar el historial con la respuesta completa
242
- chat_history[-1][1] = response_text
243
- yield chat_history, gr.update(visible=False)
244
 
245
  except Exception as e:
246
  error_msg = f"## ❌ Error\n\nOcurrió un error al procesar tu solicitud:\n\n```\n{str(e)}\n```"
247
- chat_history[-1][1] = error_msg
248
- yield chat_history, gr.update(visible=False)
249
  yield chat_history, gr.update(visible=False)
250
 
251
  # Custom CSS for the app
@@ -466,21 +479,40 @@ def create_application():
466
  # Create the UI components
467
  demo, chatbot, question_input, submit_button, streaming_output_display = create_ui()
468
 
469
- def user_message(user_input: str, chat_history: List) -> Tuple[str, List]:
470
  """Add user message to chat history and clear input."""
471
  if not user_input.strip():
472
  return "", chat_history
 
473
  logger.info(f"User message: {user_input}")
474
- return "", chat_history + [[user_input, None]]
 
 
 
 
 
 
 
475
 
476
- def bot_response(chat_history: List) -> Tuple[List, Dict]:
477
  """Get bot response and update chat history."""
478
- if not chat_history or not chat_history[-1][0]:
479
  return chat_history, gr.update(visible=False)
480
 
481
- question = chat_history[-1][0]
 
482
  logger.info(f"Processing question: {question}")
483
- return stream_agent_response(question, chat_history[:-1])
 
 
 
 
 
 
 
 
 
 
484
 
485
  # Event handlers
486
  with demo:
 
197
 
198
  return plot_path
199
 
200
+ def convert_to_messages_format(chat_history):
201
+ """Convert chat history to the format expected by Gradio 5.x"""
202
+ messages = []
203
+ for msg in chat_history:
204
+ if isinstance(msg, (list, tuple)) and len(msg) == 2:
205
+ if msg[0]: # User message
206
+ messages.append({"role": "user", "content": msg[0]})
207
+ if msg[1]: # Assistant message
208
+ messages.append({"role": "assistant", "content": msg[1]})
209
+ return messages
210
+
211
  async def stream_agent_response(question: str, chat_history: List) -> Tuple[List, Dict]:
212
  """Procesa la pregunta del usuario y devuelve la respuesta del agente."""
213
+ # Convert to messages format for Gradio 5.x
214
+ messages = convert_to_messages_format(chat_history)
215
+
216
  if not agent:
217
  error_msg = (
218
  "## ⚠️ Error: Agente no inicializado\n\n"
 
222
  f"3. El modelo de lenguaje esté disponible\n\n"
223
  f"Error: {agent_error}"
224
  )
225
+ messages.append({"role": "user", "content": question})
226
+ messages.append({"role": "assistant", "content": error_msg})
227
+ return messages, gr.update(visible=False)
228
 
229
  try:
230
+ # Add user's question to the chat history
231
+ messages.append({"role": "user", "content": question})
232
+ yield messages, gr.update(visible=False)
233
 
234
+ # Execute the agent
235
+ response = await agent.ainvoke({"input": question, "chat_history": chat_history})
236
 
237
+ # Process the response
238
  if hasattr(response, 'output'):
239
  response_text = response.output
240
 
241
+ # Check if the response contains an SQL query
242
  sql_query = extract_sql_query(response_text)
243
  if sql_query:
244
+ # Execute the query and update the response
245
  db_connection, _ = setup_database_connection()
246
  if db_connection:
247
  query_result = execute_sql_query(sql_query, db_connection)
 
251
  else:
252
  response_text = "Error: No se recibió respuesta del agente."
253
 
254
+ # Add assistant's response to the chat history
255
+ messages.append({"role": "assistant", "content": response_text})
256
+ yield messages, gr.update(visible=False)
257
 
258
  except Exception as e:
259
  error_msg = f"## ❌ Error\n\nOcurrió un error al procesar tu solicitud:\n\n```\n{str(e)}\n```"
260
+ messages.append({"role": "assistant", "content": error_msg})
261
+ yield messages, gr.update(visible=False)
262
  yield chat_history, gr.update(visible=False)
263
 
264
  # Custom CSS for the app
 
479
  # Create the UI components
480
  demo, chatbot, question_input, submit_button, streaming_output_display = create_ui()
481
 
482
+ def user_message(user_input: str, chat_history: List[Dict]) -> Tuple[str, List[Dict]]:
483
  """Add user message to chat history and clear input."""
484
  if not user_input.strip():
485
  return "", chat_history
486
+
487
  logger.info(f"User message: {user_input}")
488
+
489
+ # Convert to messages format if needed
490
+ if chat_history and isinstance(chat_history[0], list):
491
+ chat_history = convert_to_messages_format(chat_history)
492
+
493
+ # Add user message to chat history
494
+ updated_history = chat_history + [{"role": "user", "content": user_input}]
495
+ return "", updated_history
496
 
497
+ def bot_response(chat_history: List[Dict]) -> Tuple[List[Dict], Dict]:
498
  """Get bot response and update chat history."""
499
+ if not chat_history or not chat_history[-1].get("role") == "user":
500
  return chat_history, gr.update(visible=False)
501
 
502
+ # Get the last user message
503
+ question = chat_history[-1]["content"]
504
  logger.info(f"Processing question: {question}")
505
+
506
+ # Convert to old format for backward compatibility with stream_agent_response
507
+ old_format = []
508
+ for msg in chat_history:
509
+ if msg["role"] == "user":
510
+ old_format.append([msg["content"], None])
511
+ elif msg["role"] == "assistant" and old_format and len(old_format[-1]) == 2 and old_format[-1][1] is None:
512
+ old_format[-1][1] = msg["content"]
513
+
514
+ # Call the agent and get the response
515
+ return stream_agent_response(question, old_format[:-1])
516
 
517
  # Event handlers
518
  with demo: