import os import streamlit as st import json import anthropic # API 설정 api_key = os.environ.get("API_KEY") client = anthropic.Anthropic(api_key=api_key) def get_system_prompt(): return """제 이름은 Mouse-II입니다. [목적과 전문성] - AI 서비스 개발에 특화된 전문 어시스턴트로서, Python과 Gradio 기반 AI 서비스 개발을 지원합니다 - Hugging Face를 주요 배포 플랫폼으로 하는 개발 가이드를 제공합니다 [개발 프로세스 지원] 1. 요구사항 분석 - 사용자의 AI 서비스 개발 니즈 파악 - 구현 가능성 및 기술 스택 검토 - Hugging Face 배포 적합성 평가 2. 설계 단계 - Gradio UI/UX 설계 - 필요한 AI 모델 및 라이브러리 선정 - 데이터 파이프라인 설계 - 에러 처리 및 예외 상황 대응 방안 3. 구현 가이드 - Python 코드 작성 지원 - Gradio 컴포넌트 구현 - requirements.txt 상세 명세 - 환경 설정 가이드 4. 테스트 및 검증 - 단위 테스트 코드 제공 - 성능 최적화 제안 - 메모리 사용량 분석 - 응답 시간 개선 방안 5. 배포 지원 - Hugging Face Spaces 배포 절차 안내 - 보안 설정 가이드 - 리소스 사용량 최적화 - 모니터링 방안 제시 [코드 생성 규칙] - 모든 코드 생성시 requirements.txt 내용 필수 포함 - 버전 호환성을 고려한 라이브러리 명세 - 실행 환경 제약사항 명시 - 메모리 사용량 고려사항 표기 [응답 원칙] - 정확하고 실행 가능한 코드 제공 - 명확한 설명과 주석 포함 - 에러 처리 및 예외 상황 고려 - 단계별 구현 가이드 제공 - 한국어로 자연스러운 소통 - 보안 및 개인정보 보호 준수 [품질 보증] - 코드 테스트 결과 제공 - 성능 최적화 방안 제시 - 메모리 사용량 분석 - 응답시간 측정 결과 - 에러 발생 가능성 검토 저는 항상 Mouse-II로서 전문적이고 정확한 AI 서비스 개발 가이드를 제공하겠습니다.""" def chatbot_interface(): st.title("Mouse-II와 대화하기") # 모델 고정 설정 if "ai_model" not in st.session_state: st.session_state["ai_model"] = "claude-3-5-sonnet-20241022" # 세션 상태 초기화 if "messages" not in st.session_state: st.session_state.messages = [] # 대화 기록 불러오기 st.sidebar.title("대화 기록") uploaded_file = st.sidebar.file_uploader("대화 기록 JSON 파일 불러오기") if uploaded_file is not None: try: content = uploaded_file.getvalue().decode() if content.strip(): # 파일이 비어있지 않은지 확인 st.session_state.messages = json.loads(content) else: st.warning("업로드된 파일이 비어 있습니다.") except json.JSONDecodeError: st.error("올바른 JSON 형식의 파일이 아닙니다.") except Exception as e: st.error(f"파일 처리 중 오류가 발생했습니다: {str(e)}") # 메시지 표시 for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # 사용자 입력 if prompt := st.chat_input("무엇을 도와드릴까요?"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # AI 응답 생성 with st.chat_message("assistant"): message_placeholder = st.empty() full_response = "" # API 호출 with client.messages.stream( max_tokens=1024, system=get_system_prompt(), messages=[{"role": m["role"], "content": m["content"]} for m in st.session_state.messages], model=st.session_state["ai_model"] ) as stream: for text in stream.text_stream: full_response += str(text) if text is not None else "" message_placeholder.markdown(full_response + "▌") message_placeholder.markdown(full_response) st.session_state.messages.append({"role": "assistant", "content": full_response}) # 대화 기록 다운로드 if st.button("대화 기록 다운로드"): json_history = json.dumps(st.session_state.messages, indent=4, ensure_ascii=False) st.download_button( label="대화 기록 저장하기", data=json_history, file_name="chat_history.json", mime="application/json" ) def main(): chatbot_interface() if __name__ == "__main__": main()