Skip to content

feat: CI/CD 적용#1

Closed
idealHyun wants to merge 11 commits into
mainfrom
feat/ci-cd
Closed

feat: CI/CD 적용#1
idealHyun wants to merge 11 commits into
mainfrom
feat/ci-cd

Conversation

@idealHyun

@idealHyun idealHyun commented Jul 1, 2025

Copy link
Copy Markdown
Contributor

PR Type

enhancement, other


Description

  • 주간 및 연간 보고서 평가 에이전트 추가

  • MongoDB 및 MariaDB 데이터베이스 연동

  • Dockerfile을 통한 이미지 빌드 및 FastAPI 서버 실행

  • JSON 파일 MongoDB 업로드 스크립트 추가


Changes walkthrough 📝

Relevant files
Enhancement
3 files
weekly_report_reference.py
주간 보고서 평가 에이전트 추가                                                                               
+1542/-0
agent_annual.py
연간 보고서 평가 에이전트 추가                                                                               
+1320/-0
db_upload_quarter.py
JSON 파일 MongoDB 업로드 스크립트 추가                                                           
+72/-0   
Configuration changes
1 files
Dockerfile
Dockerfile을 통한 이미지 빌드 및 FastAPI 서버 실행                                       
+10/-2   
Additional files
32 files
ci.yaml +61/-0   
main.py +1144/-4
main_past.py +349/-0 
annual_evaluation_user_1_20250623_110454.json +44/-0   
db_upload_annual.py +67/-0   
mongo_check.py +163/-0 
mongo_inspector.py +107/-0 
peer_annual_agent.py +731/-0 
database.ipynb +183/-0 
peer_evaluation_results_2024Q1.json +6995/-0
peer_personal_agent.py +445/-0 
peer_evaluation_results_2024Q1_v2.json +6111/-0
peer_evaluation_results_2024Q2_v2.json +6136/-0
peer_evaluation_results_2024Q3_v2.json +6121/-0
peer_evaluation_results_2024Q4_v2.json +6089/-0
peer_personal_agent_v2.py +111/-205
config.py +19/-0   
data_processor.py +79/-0   
database_manager.py +72/-0   
llm_evaluator.py +220/-0 
main_evaluator.py +210/-0 
pinecone_manager.py +113/-0 
weekly_annual_main.py +692/-0 
weekly_quarter_main.py +981/-0 
weekly_evaluations.py +10/-9   
weekly_report_agent.py +345/-500
weekly_summary_agent.py +923/-0 
pinecone_check.py +322/-0 
pinecone_file.py +545/-0 
rdb_to_chroma.py +343/-0 
vectordb_create.py +342/-0 
requirements.txt [link]   

Need help?
  • Type /help how to ... in the comments thread for any questions about PR-Agent usage.
  • Check out the documentation for more information.
  • @idealHyun

    Copy link
    Copy Markdown
    Contributor Author

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Code Duplication

    The function validate_data_sources appears to be duplicated in the code. This could lead to maintenance challenges and inconsistencies. Consider refactoring to remove duplication.

    def validate_data_sources(self, user_id: str) -> Dict[str, Any]:
        """
        데이터 소스들의 연결 상태와 데이터 존재 여부를 검증합니다.
        """
        logger.info("데이터 소스 검증 시작")
    
        validation_result = {
            "valid": True,
            "errors": [],
            "warnings": [],
            "source_info": {}
        }
    
        # Pinecone 연결 및 데이터 확인
        try:
            # 인덱스 정보 확인
            index_stats = self.index.describe_index_stats()
            validation_result["source_info"]["pinecone"] = {
                "index_name": self.pinecone_index_name,
                "total_vectors": index_stats.total_vector_count,
                "dimension": 1024,
                "namespace": self.namespace,
                "status": "connected"
            }
    
            # 특정 사용자 데이터 존재 확인
            dummy_vector = [0.0] * 1024
    
            # 쿼리 파라미터 설정
            query_params = {
                "vector": dummy_vector,
                "filter": {"user_id": str(user_id)},  # 문자열로 변환
                "top_k": 1,
                "include_metadata": True
            }
    
            # 네임스페이스가 있으면 추가
            if self.namespace:
                query_params["namespace"] = self.namespace
    
            test_search = self.index.query(**query_params)
    
            if not test_search.matches:
                validation_result["errors"].append(f"사용자 ID {user_id}에 해당하는 데이터가 Pinecone에 없습니다.")
                validation_result["valid"] = False
            else:
                validation_result["source_info"]["pinecone"]["user_data_found"] = True
    
        except Exception as e:
            validation_result["errors"].append(f"Pinecone 연결 오류: {str(e)}")
            validation_result["valid"] = False
    
        # MariaDB 연결 및 테이블 확인
        try:
            connection = self.connect_to_mariadb()
            cursor = connection.cursor()
    
            # 테이블 존재 확인
            cursor.execute("SHOW TABLES LIKE 'team_criteria'")
            if not cursor.fetchone():
                validation_result["errors"].append("team_criteria 테이블이 존재하지 않습니다.")
                validation_result["valid"] = False
    
            cursor.execute("SHOW TABLES LIKE 'team_goal'")
            if not cursor.fetchone():
                validation_result["errors"].append("team_goal 테이블이 존재하지 않습니다.")
                validation_result["valid"] = False
    
            # 테이블 레코드 수 확인
            cursor.execute("SELECT COUNT(*) FROM team_criteria")
            criteria_count = cursor.fetchone()[0]
    
            cursor.execute("SELECT COUNT(*) FROM team_goal")
            goals_count = cursor.fetchone()[0]
    
            validation_result["source_info"]["mariadb"] = {
                "host": self.db_config["host"],
                "database": self.db_config["database"],
                "team_criteria_records": criteria_count,
                "team_goals_records": goals_count,
                "status": "connected"
            }
    
            connection.close()
    
        except Exception as e:
            validation_result["errors"].append(f"MariaDB 연결 오류: {str(e)}")
            validation_result["valid"] = False
    
        if validation_result["valid"]:
            logger.info("모든 데이터 소스 검증 성공")
        else:
            logger.error(f"데이터 소스 검증 실패: {validation_result['errors']}")
    
        return validation_result
    Exception Handling

    There are multiple instances where exceptions are caught and logged, but the original exception is not re-raised or handled further. This could lead to silent failures. Consider re-raising exceptions or handling them appropriately.

    except Exception as e:
        logger.warning(f"네임스페이스 감지 실패: {e}")
        return ""

    @idealHyun

    Copy link
    Copy Markdown
    Contributor Author

    PR Description updated to latest commit (568f102)

    @idealHyun

    idealHyun commented Jul 1, 2025

    Copy link
    Copy Markdown
    Contributor Author

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Impact
    Security
    Remove sensitive info from logs

    API 키의 길이와 일부를 로그에 남기는 것은 보안상 위험할 수 있습니다. 이러한 정보는 로그에 기록하지 않도록 수정하세요.

    app/main.py [129-131]

    -logger.info(f"🔑 OpenAI Key 길이: {len(openai_key) if openai_key else 0}")
    -logger.info(f"🔑 Pinecone Key 길이: {len(pinecone_key) if pinecone_key else 0}")
    -logger.info(f"🔑 Pinecone Key 앞부분: {pinecone_key[:10] + '...' if pinecone_key else 'None'}")
    +logger.info("🔑 OpenAI Key 설정 여부 확인")
    +logger.info("🔑 Pinecone Key 설정 여부 확인")
    Suggestion importance[1-10]: 9

    __

    Why: Logging API key lengths and partial values can pose a security risk. The suggestion to remove this sensitive information from logs significantly improves the security posture of the application.

    High
    Remove hardcoded API keys

    OpenAI API 키가 코드에 하드코딩되어 있습니다. 보안 문제를 방지하기 위해 환경 변수 또는 안전한 비밀 관리 시스템을 사용하여 API 키를
    관리하세요.

    app/personal_annual_reports/agents/agent_annual.py [1167]

    -openai_key = "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"
    +openai_key = os.getenv("OPENAI_API_KEY")
    Suggestion importance[1-10]: 9

    __

    Why: Hardcoding API keys poses a significant security risk. Using environment variables for sensitive information like API keys is a best practice to enhance security and prevent unauthorized access.

    High
    Secure MongoDB credentials

    MongoDB URI에 사용자명과 비밀번호가 하드코딩되어 있습니다. 보안을 위해 환경 변수로 관리하거나 안전한 비밀 관리 시스템을 사용하세요.

    app/personal_annual_reports/agents/db_upload_annual.py [6]

    -mongo_uri = "mongodb://root:root@13.209.110.151:27017/"
    +mongo_uri = os.getenv("MONGO_URI")
    Suggestion importance[1-10]: 9

    __

    Why: Hardcoding database credentials is a critical security vulnerability. Using environment variables or a secure secret management system to store credentials helps protect against unauthorized access and data breaches.

    High
    보안 강화를 위한 비밀번호 관리

    MongoDB 연결 문자열에 하드코딩된 비밀번호가 포함되어 있습니다. 보안 강화를 위해 환경 변수나 안전한 비밀 저장소를 사용하여 민감한 정보를
    관리하세요.

    app/personal_annual_reports/agents/peer_annual_agent.py [21]

    -mongodb_connection_string = "mongodb://root:root@13.209.110.151:27017/"
    +mongodb_connection_string = os.getenv("MONGODB_CONNECTION_STRING")
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion addresses a critical security issue by recommending the use of environment variables for sensitive information, reducing the risk of exposing credentials in the codebase.

    High
    API 키 보안 관리 개선

    OpenAI API 키가 코드에 직접 설정되어 있습니다. 보안을 위해 환경 변수나 안전한 비밀 저장소를 사용하여 API 키를 관리하세요.

    app/personal_annual_reports/agents/peer_annual_agent.py [38]

    -openai.api_key = openai_api_key
    +openai.api_key = os.getenv("OPENAI_API_KEY")
    Suggestion importance[1-10]: 9

    __

    Why: This suggestion enhances security by advising the use of environment variables for managing API keys, preventing potential exposure of sensitive information in the code.

    High
    MongoDB URI 보안 개선

    MongoDB URI에 하드코딩된 비밀번호가 포함되어 있습니다. 보안을 위해 환경 변수나 안전한 비밀 저장소를 사용하여 민감한 정보를 관리하세요.

    app/personal_quarter_reports/agents/weekly/db_upload_quarter.py [7]

    -mongo_uri = "mongodb://root:root@13.209.110.151:27017/"
    +mongo_uri = os.getenv("MONGO_URI")
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion improves security by recommending the use of environment variables for MongoDB URI, which helps protect sensitive credentials from being exposed in the codebase.

    High
    Enable SSL for MongoDB connections

    MongoDB 클라이언트 생성 시 ssl=True 옵션을 추가하여 데이터 전송 시 보안을 강화하세요.

    app/personal_annual_reports/agents/agent_annual.py [148-152]

     self.mongo_client = MongoClient(
         connection_string,
         serverSelectionTimeoutMS=10000,
         connectTimeoutMS=10000,
    -    socketTimeoutMS=10000
    +    socketTimeoutMS=10000,
    +    ssl=True
     )
    Suggestion importance[1-10]: 8

    __

    Why: Enabling SSL for MongoDB connections enhances data security by encrypting the data in transit, which is crucial for protecting sensitive information from interception.

    Medium
    Possible issue
    Handle None user_ids in batch evaluation

    request.user_idsNone일 경우 모든 사용자를 평가하도록 되어 있으나, 실제로는 None이 전달되면 오류가 발생할 수 있습니다.
    None일 때 모든 사용자를 평가하도록 로직을 추가하세요.

    app/main.py [432-456]

     @weekly_report_router.post("/batch-evaluate")
     async def batch_evaluate_weekly_report(request: BatchEvaluationRequest):
         """주간 보고서 배치 평가 실행"""
         try:
             logger.info("주간 보고서 배치 평가 시작")
             
             agent = get_weekly_report_agent()
             
    +        # 사용자 ID가 None이면 모든 사용자 평가
    +        user_ids = request.user_ids or agent.get_available_user_ids()
    +        
             # 배치 평가 실행 (블로킹 작업을 별도 스레드에서 실행)
             result = await asyncio.get_event_loop().run_in_executor(
                 None, 
                 agent.execute_batch_evaluation,
    -            request.user_ids
    +            user_ids
             )
             
             return {
                 "success": True,
                 "message": "주간 보고서 배치 평가 완료",
                 "data": result,
                 "timestamp": datetime.now().isoformat()
             }
             
         except Exception as e:
             logger.error(f"배치 평가 실패: {e}")
             raise HTTPException(status_code=500, detail=f"배치 평가 실패: {str(e)}")
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion addresses a potential issue where None user_ids could cause an error during batch evaluation. By adding logic to handle None values and evaluate all users, the suggestion enhances the robustness and correctness of the function.

    Medium

    @idealHyun idealHyun closed this Jul 1, 2025
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    2 participants