Spaces:
Sleeping
Sleeping
haepa_mac
commited on
Commit
·
1b519a7
1
Parent(s):
1660aff
Fix chat API integration - dynamic API configuration for chat functions
Browse files
app.py
CHANGED
@@ -615,9 +615,8 @@ def export_persona_to_json(persona):
|
|
615 |
# """선택된 페르소나 로드 - 더 이상 사용하지 않음"""
|
616 |
# return None, "이 기능은 더 이상 사용하지 않습니다. JSON 업로드를 사용하세요.", {}, {}, None, [], [], [], ""
|
617 |
|
618 |
-
def chat_with_loaded_persona(persona, user_message, chat_history=None):
|
619 |
-
"""현재 로드된 페르소나와 대화 - API 설정 적용"""
|
620 |
-
global persona_generator
|
621 |
|
622 |
if not persona:
|
623 |
return chat_history or [], ""
|
@@ -626,10 +625,15 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
|
|
626 |
return chat_history or [], ""
|
627 |
|
628 |
try:
|
629 |
-
#
|
630 |
-
if
|
631 |
-
|
632 |
-
|
|
|
|
|
|
|
|
|
|
|
633 |
|
634 |
# 대화 기록을 올바른 형태로 변환 (Gradio 5.x messages 형태)
|
635 |
conversation_history = []
|
@@ -644,7 +648,7 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
|
|
644 |
conversation_history.append({"role": "assistant", "content": message[1]})
|
645 |
|
646 |
# 페르소나와 대화 (설정된 API 사용)
|
647 |
-
response =
|
648 |
|
649 |
# 새로운 대화를 messages 형태로 추가
|
650 |
if chat_history is None:
|
@@ -660,7 +664,12 @@ def chat_with_loaded_persona(persona, user_message, chat_history=None):
|
|
660 |
except Exception as e:
|
661 |
import traceback
|
662 |
traceback.print_exc()
|
663 |
-
|
|
|
|
|
|
|
|
|
|
|
664 |
|
665 |
if chat_history is None:
|
666 |
chat_history = []
|
@@ -777,7 +786,12 @@ def create_api_config_section():
|
|
777 |
with gr.Accordion("🔧 API 설정", open=False):
|
778 |
gr.Markdown("""
|
779 |
### AI 모델 선택 및 API 키 설정
|
780 |
-
|
|
|
|
|
|
|
|
|
|
|
781 |
""")
|
782 |
|
783 |
with gr.Row():
|
@@ -799,26 +813,26 @@ def create_api_config_section():
|
|
799 |
apply_api_btn = gr.Button("🔧 API 설정 적용", variant="primary")
|
800 |
test_api_btn = gr.Button("🧪 API 연결 테스트", variant="secondary")
|
801 |
|
802 |
-
api_status = gr.Markdown("**상태**: API가 설정되지 않았습니다.")
|
803 |
|
804 |
return api_provider, api_key_input, apply_api_btn, test_api_btn, api_status
|
805 |
|
806 |
def apply_api_configuration(api_provider, api_key):
|
807 |
-
"""API 설정 적용"""
|
808 |
global persona_generator
|
809 |
|
810 |
if not api_key or not api_key.strip():
|
811 |
-
return "❌ API 키를
|
812 |
|
813 |
try:
|
814 |
# 새로운 PersonaGenerator 인스턴스 생성
|
815 |
persona_generator = PersonaGenerator(api_provider=api_provider, api_key=api_key.strip())
|
816 |
|
817 |
provider_name = "Google Gemini" if api_provider == "gemini" else "OpenAI"
|
818 |
-
return f"✅ **{provider_name}
|
819 |
|
820 |
except Exception as e:
|
821 |
-
return f"❌ API 설정 중 오류
|
822 |
|
823 |
def test_api_connection(api_provider, api_key):
|
824 |
"""API 연결 테스트"""
|
@@ -1124,13 +1138,13 @@ def create_main_interface():
|
|
1124 |
# 대화 관련 이벤트 핸들러
|
1125 |
send_btn.click(
|
1126 |
fn=chat_with_loaded_persona,
|
1127 |
-
inputs=[current_persona, message_input, chatbot],
|
1128 |
outputs=[chatbot, message_input]
|
1129 |
)
|
1130 |
|
1131 |
message_input.submit(
|
1132 |
fn=chat_with_loaded_persona,
|
1133 |
-
inputs=[current_persona, message_input, chatbot],
|
1134 |
outputs=[chatbot, message_input]
|
1135 |
)
|
1136 |
|
@@ -1140,20 +1154,29 @@ def create_main_interface():
|
|
1140 |
outputs=[chatbot]
|
1141 |
)
|
1142 |
|
1143 |
-
# 예시 메시지 버튼들
|
|
|
|
|
|
|
|
|
|
|
|
|
1144 |
example_btn1.click(
|
1145 |
-
fn=lambda: "안녕!",
|
1146 |
-
|
|
|
1147 |
)
|
1148 |
|
1149 |
example_btn2.click(
|
1150 |
-
fn=lambda: "너는 누구야?",
|
1151 |
-
|
|
|
1152 |
)
|
1153 |
|
1154 |
example_btn3.click(
|
1155 |
-
fn=lambda: "뭘 좋아해?",
|
1156 |
-
|
|
|
1157 |
)
|
1158 |
|
1159 |
# API 설정 이벤트 핸들러
|
|
|
615 |
# """선택된 페르소나 로드 - 더 이상 사용하지 않음"""
|
616 |
# return None, "이 기능은 더 이상 사용하지 않습니다. JSON 업로드를 사용하세요.", {}, {}, None, [], [], [], ""
|
617 |
|
618 |
+
def chat_with_loaded_persona(persona, user_message, chat_history=None, api_provider="gemini", api_key=None):
|
619 |
+
"""현재 로드된 페르소나와 대화 - 동적 API 설정 적용"""
|
|
|
620 |
|
621 |
if not persona:
|
622 |
return chat_history or [], ""
|
|
|
625 |
return chat_history or [], ""
|
626 |
|
627 |
try:
|
628 |
+
# API 설정이 제공된 경우 동적으로 PersonaGenerator 생성
|
629 |
+
if api_key and api_key.strip():
|
630 |
+
generator = PersonaGenerator(api_provider=api_provider, api_key=api_key.strip())
|
631 |
+
else:
|
632 |
+
# 글로벌 persona_generator 사용 (기본 설정)
|
633 |
+
global persona_generator
|
634 |
+
if persona_generator is None:
|
635 |
+
persona_generator = PersonaGenerator()
|
636 |
+
generator = persona_generator
|
637 |
|
638 |
# 대화 기록을 올바른 형태로 변환 (Gradio 5.x messages 형태)
|
639 |
conversation_history = []
|
|
|
648 |
conversation_history.append({"role": "assistant", "content": message[1]})
|
649 |
|
650 |
# 페르소나와 대화 (설정된 API 사용)
|
651 |
+
response = generator.chat_with_persona(persona, user_message, conversation_history)
|
652 |
|
653 |
# 새로운 대화를 messages 형태로 추가
|
654 |
if chat_history is None:
|
|
|
664 |
except Exception as e:
|
665 |
import traceback
|
666 |
traceback.print_exc()
|
667 |
+
|
668 |
+
# API 키가 없거나 잘못된 경우의 에러 메시지
|
669 |
+
if not api_key or not api_key.strip():
|
670 |
+
error_response = "😅 API 키가 설정되지 않았어요! 상단의 '🔧 API 설정'에서 Gemini 또는 OpenAI API 키를 입력해주세요."
|
671 |
+
else:
|
672 |
+
error_response = f"😓 API 연결에 문제가 있어요: {str(e)}"
|
673 |
|
674 |
if chat_history is None:
|
675 |
chat_history = []
|
|
|
786 |
with gr.Accordion("🔧 API 설정", open=False):
|
787 |
gr.Markdown("""
|
788 |
### AI 모델 선택 및 API 키 설정
|
789 |
+
**대화 기능을 사용하려면 반드시 API 키를 설정해야 합니다.**
|
790 |
+
|
791 |
+
- **Gemini**: 무료 티어 제공, 한국어 지원 우수
|
792 |
+
- **OpenAI**: 고품질 응답, 유료 서비스
|
793 |
+
|
794 |
+
⚠️ **API 키를 설정하지 않으면 대화 기능이 작동하지 않습니다!**
|
795 |
""")
|
796 |
|
797 |
with gr.Row():
|
|
|
813 |
apply_api_btn = gr.Button("🔧 API 설정 적용", variant="primary")
|
814 |
test_api_btn = gr.Button("🧪 API 연결 테스트", variant="secondary")
|
815 |
|
816 |
+
api_status = gr.Markdown("⚠️ **상태**: API가 설정되지 않았습니다. 대화 기능을 사용하려면 위에서 API 키를 설정하세요.")
|
817 |
|
818 |
return api_provider, api_key_input, apply_api_btn, test_api_btn, api_status
|
819 |
|
820 |
def apply_api_configuration(api_provider, api_key):
|
821 |
+
"""API 설정 적용 - 개선된 피드백"""
|
822 |
global persona_generator
|
823 |
|
824 |
if not api_key or not api_key.strip():
|
825 |
+
return "❌ **API 키를 입력해주세요.**\n\n🔑 **API 키 발급 방법:**\n- **Gemini**: https://makersuite.google.com/app/apikey\n- **OpenAI**: https://platform.openai.com/api-keys"
|
826 |
|
827 |
try:
|
828 |
# 새로운 PersonaGenerator 인스턴스 생성
|
829 |
persona_generator = PersonaGenerator(api_provider=api_provider, api_key=api_key.strip())
|
830 |
|
831 |
provider_name = "Google Gemini" if api_provider == "gemini" else "OpenAI"
|
832 |
+
return f"✅ **{provider_name} API 설정 완료!**\n\n🎯 **이제 대화 기능을 사���할 수 있습니다.**\n\n💡 **사용법**: 대화하기 탭에서 JSON 파일을 업로드하여 페르소나와 대화를 시작하세요."
|
833 |
|
834 |
except Exception as e:
|
835 |
+
return f"❌ **API 설정 중 오류 발생**\n\n🔍 **오류 내용**: {str(e)}\n\n💡 **확인사항**:\n- API 키가 올바른지 확인하세요\n- 인터넷 연결을 확인하세요"
|
836 |
|
837 |
def test_api_connection(api_provider, api_key):
|
838 |
"""API 연결 테스트"""
|
|
|
1138 |
# 대화 관련 이벤트 핸들러
|
1139 |
send_btn.click(
|
1140 |
fn=chat_with_loaded_persona,
|
1141 |
+
inputs=[current_persona, message_input, chatbot, api_provider, api_key_input],
|
1142 |
outputs=[chatbot, message_input]
|
1143 |
)
|
1144 |
|
1145 |
message_input.submit(
|
1146 |
fn=chat_with_loaded_persona,
|
1147 |
+
inputs=[current_persona, message_input, chatbot, api_provider, api_key_input],
|
1148 |
outputs=[chatbot, message_input]
|
1149 |
)
|
1150 |
|
|
|
1154 |
outputs=[chatbot]
|
1155 |
)
|
1156 |
|
1157 |
+
# 예시 메시지 버튼들 - API 설정 정보 포함
|
1158 |
+
def handle_example_message(persona, message, api_provider, api_key):
|
1159 |
+
if not persona:
|
1160 |
+
return [], ""
|
1161 |
+
chat_result, _ = chat_with_loaded_persona(persona, message, [], api_provider, api_key)
|
1162 |
+
return chat_result, ""
|
1163 |
+
|
1164 |
example_btn1.click(
|
1165 |
+
fn=lambda persona, api_provider, api_key: handle_example_message(persona, "안녕!", api_provider, api_key),
|
1166 |
+
inputs=[current_persona, api_provider, api_key_input],
|
1167 |
+
outputs=[chatbot, message_input]
|
1168 |
)
|
1169 |
|
1170 |
example_btn2.click(
|
1171 |
+
fn=lambda persona, api_provider, api_key: handle_example_message(persona, "너는 누구야?", api_provider, api_key),
|
1172 |
+
inputs=[current_persona, api_provider, api_key_input],
|
1173 |
+
outputs=[chatbot, message_input]
|
1174 |
)
|
1175 |
|
1176 |
example_btn3.click(
|
1177 |
+
fn=lambda persona, api_provider, api_key: handle_example_message(persona, "뭘 좋아해?", api_provider, api_key),
|
1178 |
+
inputs=[current_persona, api_provider, api_key_input],
|
1179 |
+
outputs=[chatbot, message_input]
|
1180 |
)
|
1181 |
|
1182 |
# API 설정 이벤트 핸들러
|