haepa_mac commited on
Commit
9a949d6
·
1 Parent(s): cf51d25

Fix Gradio 4.x chat format compatibility - Convert chat functions to use [[user, bot]] format instead of messages format - Remove unsupported type='messages' parameter

Browse files
Files changed (1) hide show
  1. app.py +22 -16
app.py CHANGED
@@ -690,7 +690,7 @@ def export_persona_to_json(persona):
690
  # return None, "이 기능은 더 이상 사용하지 않습니다. JSON 업로드를 사용하세요.", {}, {}, None, [], [], [], ""
691
 
692
  def chat_with_loaded_persona(persona, user_message, chat_history=None):
693
- """페르소나와 채팅 (환경변수 API 사용)"""
694
 
695
  if chat_history is None:
696
  chat_history = []
@@ -698,26 +698,33 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
698
  # 페르소나 체크
699
  if not persona:
700
  error_msg = "❌ 먼저 페르소나를 불러와주세요! 대화하기 탭에서 JSON 파일을 업로드하세요."
701
- chat_history.append({"role": "user", "content": user_message})
702
- chat_history.append({"role": "assistant", "content": error_msg})
703
  return chat_history, ""
704
 
705
  # 환경변수 API 키 체크
706
  if not persona_generator or not hasattr(persona_generator, 'api_key') or not persona_generator.api_key:
707
  error_msg = "❌ API 키가 설정되지 않았습니다. 허깅페이스 스페이스 설정에서 GEMINI_API_KEY 환경변수를 추가해주세요!"
708
- chat_history.append({"role": "user", "content": user_message})
709
- chat_history.append({"role": "assistant", "content": error_msg})
710
  return chat_history, ""
711
 
712
  try:
713
  # 글로벌 persona_generator 사용 (환경변수에서 설정된 API 키 사용)
714
  generator = persona_generator
715
 
716
- # Gradio messages 형식에서 대화 기록 변환
717
  conversation_history = []
718
- for message in chat_history:
719
- if isinstance(message, dict) and 'role' in message and 'content' in message:
720
- conversation_history.append(message)
 
 
 
 
 
 
 
 
721
 
722
  # 🧠 세션 ID 생성 (페르소나 이름 기반)
723
  persona_name = persona.get("기본정보", {}).get("이름", "알 수 없는 페르소나")
@@ -726,9 +733,8 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
726
  # 페르소나와 채팅 (3단계 기억 시스템 활용)
727
  response = generator.chat_with_persona(persona, user_message, conversation_history, session_id)
728
 
729
- # Gradio messages 형식으로 채팅 기록 업데이트
730
- chat_history.append({"role": "user", "content": user_message})
731
- chat_history.append({"role": "assistant", "content": response})
732
 
733
  return chat_history, ""
734
 
@@ -746,8 +752,8 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
746
  else:
747
  friendly_error = f"앗, 미안해... 뭔가 문제가 생긴 것 같아... 😅\n\n🔍 **기술적 정보**: {str(e)}"
748
 
749
- chat_history.append({"role": "user", "content": user_message})
750
- chat_history.append({"role": "assistant", "content": friendly_error})
751
  return chat_history, ""
752
 
753
  def import_persona_from_json(json_file):
@@ -1211,8 +1217,8 @@ def create_main_interface():
1211
 
1212
  with gr.Column(scale=1):
1213
  gr.Markdown("### 💬 대화")
1214
- # Gradio 4.44.1에서 권장하는 messages 형식 사용
1215
- chatbot = gr.Chatbot(height=400, label="대화", type="messages")
1216
  with gr.Row():
1217
  message_input = gr.Textbox(
1218
  placeholder="메시지를 입력하세요...",
 
690
  # return None, "이 기능은 더 이상 사용하지 않습니다. JSON 업로드를 사용하세요.", {}, {}, None, [], [], [], ""
691
 
692
  def chat_with_loaded_persona(persona, user_message, chat_history=None):
693
+ """페르소나와 채팅 (환경변수 API 사용) - Gradio 4.x 호환"""
694
 
695
  if chat_history is None:
696
  chat_history = []
 
698
  # 페르소나 체크
699
  if not persona:
700
  error_msg = "❌ 먼저 페르소나를 불러와주세요! 대화하기 탭에서 JSON 파일을 업로드하세요."
701
+ # Gradio 4.x 형식: [user_message, bot_response] 튜플의 리스트
702
+ chat_history.append([user_message, error_msg])
703
  return chat_history, ""
704
 
705
  # 환경변수 API 키 체크
706
  if not persona_generator or not hasattr(persona_generator, 'api_key') or not persona_generator.api_key:
707
  error_msg = "❌ API 키가 설정되지 않았습니다. 허깅페이스 스페이스 설정에서 GEMINI_API_KEY 환경변수를 추가해주세요!"
708
+ chat_history.append([user_message, error_msg])
 
709
  return chat_history, ""
710
 
711
  try:
712
  # 글로벌 persona_generator 사용 (환경변수에서 설정된 API 키 사용)
713
  generator = persona_generator
714
 
715
+ # Gradio 4.x 형식에서 대화 기록 변환: [[user, bot], [user, bot]] -> [{"role": "user", "content": "..."}, ...]
716
  conversation_history = []
717
+ for chat_turn in chat_history:
718
+ if isinstance(chat_turn, (list, tuple)) and len(chat_turn) >= 2:
719
+ # [user_message, bot_response] 형태
720
+ user_msg, bot_msg = chat_turn[0], chat_turn[1]
721
+ if user_msg:
722
+ conversation_history.append({"role": "user", "content": str(user_msg)})
723
+ if bot_msg:
724
+ conversation_history.append({"role": "assistant", "content": str(bot_msg)})
725
+ elif isinstance(chat_turn, dict) and 'role' in chat_turn and 'content' in chat_turn:
726
+ # 혹시 messages 형식이 들어온 경우
727
+ conversation_history.append(chat_turn)
728
 
729
  # 🧠 세션 ID 생성 (페르소나 이름 기반)
730
  persona_name = persona.get("기본정보", {}).get("이름", "알 수 없는 페르소나")
 
733
  # 페르소나와 채팅 (3단계 기억 시스템 활용)
734
  response = generator.chat_with_persona(persona, user_message, conversation_history, session_id)
735
 
736
+ # Gradio 4.x 형식으로 채팅 기록 업데이트: [user_message, bot_response]
737
+ chat_history.append([user_message, response])
 
738
 
739
  return chat_history, ""
740
 
 
752
  else:
753
  friendly_error = f"앗, 미안해... 뭔가 문제가 생긴 것 같아... 😅\n\n🔍 **기술적 정보**: {str(e)}"
754
 
755
+ # Gradio 4.x 형식으로 오류 메시지 추가
756
+ chat_history.append([user_message, friendly_error])
757
  return chat_history, ""
758
 
759
  def import_persona_from_json(json_file):
 
1217
 
1218
  with gr.Column(scale=1):
1219
  gr.Markdown("### 💬 대화")
1220
+ # Gradio 4.x 호환: type="messages" 제거
1221
+ chatbot = gr.Chatbot(height=400, label="대화")
1222
  with gr.Row():
1223
  message_input = gr.Textbox(
1224
  placeholder="메시지를 입력하세요...",