# 프롬프트 생성기 개발 V9: CLI 사용성 개선 및 코드 리팩토링 > 2025년 12월 3일 ## 개발 목표 모든 주요 의도에 대한 2단계 프롬프트 생성을 성공적으로 구현했다. 이제 사용자 경험을 향상시키고 스크립트의 견고성을 높이기 위해 CLI 사용성 개선 및 추가적인 코드 리팩토링을 진행한다. ## 주요 개선 사항 ### 1. API 호출 재시도(Retry) 로직 구현 API 호출은 네트워크 문제, 일시적인 서버 오류, 또는 레이트 리밋(Rate Limit) 등의 이유로 실패할 수 있다. 이러한 상황에 대비하여, 일정 횟수만큼 자동으로 재시도하는 로직을 추가하여 스크립트의 안정성을 높인다. `tenacity` 라이브러리를 사용하여 이를 간결하게 구현할 것이다. - **설치:** `uv pip install tenacity` - **적용:** `get_intent` 및 `generate_detailed_prompt` 함수에 `@retry` 데코레이터를 적용한다. ### 2. 출력 메시지 개선 스크립트의 진행 상황과 최종 결과물을 사용자에게 더 명확하고 보기 좋게 전달하기 위해 출력 메시지 형식을 개선한다. - 진행 단계(Step 1, Step 2) 메시지를 더 명확하게. - 최종 프롬프트 문단을 강조하는 형식 추가. ### 3. 오류 처리 강화 API 호출 실패 시 사용자에게 더 유용한 정보를 제공하도록 예외 처리 메시지를 구체화한다. ## `main.py` 업데이트 재시도 로직을 위해 `tenacity` 라이브러리를 추가하고, `get_intent`와 `generate_detailed_prompt` 함수에 재시도 데코레이터를 적용한다. 또한 `main` 함수의 출력 부분을 개선한다. ```python import os import sys import google.generativeai as genai from dotenv import load_dotenv from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_type import time # For potential sleep in retry if needed # ... (setup_generative_ai 함수는 변경 없음) ... @retry(stop_after_attempt=3, wait_fixed=2, retry_if_exception_type=Exception) def get_intent(model, user_input): """Calls the API to infer the user's intent with retry logic.""" print(" (Retrying get_intent...)") # Indicate retry attempts meta_prompt = """You are an expert at understanding user intent. Analyze the following user request and classify it into one of these categories: [Image Generation], [Text Summarization], [Code Generation], [General Question]. Respond with only the category name in brackets. User Request: "{{user_input}}" """ prompt_for_api = meta_prompt.replace("{{user_input}}", user_input) response = model.generate_content(prompt_for_api) return response.text.strip() @retry(stop_after_attempt=3, wait_fixed=2, retry_if_exception_type=Exception) def generate_detailed_prompt(model, user_input, intent): """Generates the final detailed prompt based on the intent with retry logic.""" print(" (Retrying generate_detailed_prompt...)") # Indicate retry attempts # ... (specialized_prompts 딕셔너리는 변경 없음) ... prompt_template = specialized_prompts.get(intent) if not prompt_template: raise ValueError(f"No specialized prompt found for intent: '{intent}'") # Raise specific error prompt_for_api = prompt_template.replace("{{user_input}}", user_input) response = model.generate_content(prompt_for_api) return response.text.strip() def main(): """Main function to run the prompt generator.""" load_dotenv() api_key = os.getenv("GOOGLE_API_KEY") if not api_key: print("Error: GOOGLE_API_KEY not found in .env file. Please set it in your .env file.") sys.exit(1) model = setup_generative_ai(api_key) print("\n--- Gemini-powered Prompt Generator ---") user_input = input("Enter your simple prompt idea: ") try: # Step 1: Infer Intent print("\n[Step 1/2] Inferring intent...") intent = get_intent(model, user_input) print(f" Intent detected: {intent}") # Step 2: Generate Detailed Prompt print("\n[Step 2/2] Generating detailed prompt...") detailed_prompt = generate_detailed_prompt(model, user_input, intent) print("\n--- Your Detailed Prompt Paragraph ---") print(detailed_prompt) print("------------------------------------") except ValueError as ve: # Catch specific errors print(f"\nConfiguration Error: {ve}") except Exception as e: print(f"\nAn unexpected error occurred during prompt generation: {e}") if __name__ == "__main__": main() ``` ## `requirements.txt` 업데이트 `tenacity` 라이브러리를 추가한다. ``` google-generativeai python-dotenv tenacity ``` ## 다음 단계 다음 단계(`V10`)는 최종 검토 및 문서화 단계가 될 것이다. 전체 스크립트의 완성도를 점검하고, 사용자가 쉽게 사용할 수 있도록 사용법과 개발 과정을 정리하는 작업이 포함될 것이다.