[FEATURE] CV 분석 결과를 바탕으로 OpenAI에 설명 요청#22
Conversation
There was a problem hiding this comment.
Summary of Changes
Hello @youyeon11, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
이 Pull Request는 CV 분석 파이프라인에 OpenAI 기반의 약물 안전성 검사 기능을 통합하고, Redis Stream을 통한 비동기 작업 처리의 안정성을 대폭 향상시킵니다. 또한, 새로운 배포 스크립트와 Docker Compose 설정을 추가하여 시스템의 배포 및 운영 효율성을 높였습니다.
Highlights
- OpenAI 통합: CV 분석 결과를 바탕으로 약물의 임산부 복용 안전성에 대해 OpenAI (GPT-4o-mini)에 설명을 요청하는 기능이 추가되었습니다. 응답은 JSON 형식으로 파싱되어
isSafe여부와 설명을 제공합니다. - Redis Stream 처리 개선: Redis Stream 메시지 처리 로직이 전반적으로 리팩토링되었습니다.
RedisStreamClient클래스를 도입하여xadd,xreadgroup,xack_and_del등 Redis Stream 관련 작업을 보다 견고하게 처리하며, 메시지 타입 검증 및 Dead Letter Queue (DLQ) 처리 메커니즘이 추가되었습니다. - 데이터 모델 및 S3 서비스 변경: OpenAI 통합에 맞춰
JobResult스키마가 업데이트되었고,ImageJob및JobRequest의 필드명이 camelCase로 통일되었습니다. S3 서비스는 이제 임시 파일 대신BytesIO스트림을 사용하여 이미지를 다운로드하고 처리합니다. - 배포 환경 구성 추가: 블루-그린 배포 전략을 위한
deploy.sh스크립트,docker-compose.yml파일, Nginx 설정 파일 (nginx.conf)이 추가되어 배포 프로세스가 정의되었습니다.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
🤖 Gemini 코드 리뷰 결과1. 주요 변경 사항 요약 및 의도 파악이 PR은 #20 이슈를 해결하기 위해 CV 분석 결과(약 이름)를 바탕으로 OpenAI의 GPT 모델을 사용하여 임산부 복용 안전성 정보를 얻는 기능을 추가합니다. 2. 코드 품질 및 가독성
3. 잠재적 버그 및 엣지 케이스
4. 성능 및 효율성
5. 보안 및 아키텍처
추가적인 제안:
전반적으로 잘 작성된 PR입니다. 위에 제시된 사항들을 수정하면 더욱 견고하고 유지보수하기 쉬운 코드가 될 것입니다. 👍 |
There was a problem hiding this comment.
Code Review
CV 분석 결과를 바탕으로 OpenAI에 약품 안전성 설명을 요청하는 기능 추가 PR을 리뷰했습니다. 전반적으로 기능 구현의 목표는 잘 달성되었으나, 몇 가지 중요한 수정 사항과 개선점을 제안합니다.
주요 피드백은 다음과 같습니다:
- Critical:
async함수 내에서 동기 I/O 호출로 인한 이벤트 루프 블로킹 문제가 있습니다. - High: 설정 파일에 변수명 오타가 있어 수정이 필요합니다.
- Medium:
print대신 표준 로깅 라이브러리 사용,asyncio환경에 더 적합한AsyncOpenAI클라이언트 사용, 프롬프트 관리 방식 개선, 코드 가독성 향상을 위한 리팩토링을 제안했습니다.
자세한 내용은 각 파일의 개별 코멘트를 참고해 주세요.
| isSafe = 0 | ||
| description = "일단은 테스트입니다. 추후에 GPT 부분 추가할 예정" | ||
| print(f"[task] Start Asking GPT for job_id={correlationId}") | ||
| description, isSafe = checker.ask_chatgpt_about_pregnancy_safety(pillName) |
There was a problem hiding this comment.
async 함수 내에서 동기 함수인 ask_chatgpt_about_pregnancy_safety를 직접 호출하고 있습니다. 이 방식은 이벤트 루프를 블로킹하여 전체 애플리케이션의 성능을 심각하게 저하시킬 수 있습니다. 다른 I/O 바운드 작업과 마찬가지로 asyncio.to_thread를 사용하여 비동기적으로 실행해야 합니다.
| description, isSafe = checker.ask_chatgpt_about_pregnancy_safety(pillName) | |
| description, isSafe = await asyncio.to_thread(checker.ask_chatgpt_about_pregnancy_safety, pillName) |
There was a problem hiding this comment.
이미 실행 중인 이벤트 루프가 비동기적으로 동작하므로, 별도의 스레드를 두는 대신 동기 방식 처리를 선택
app/core/config.py
Outdated
| oepnai_key = os.getenv("OPENAI_API_KEY") | ||
|
|
||
| class Settings(BaseSettings): | ||
| REDIS_URL: str = redis_url | ||
| S3_REGION: str = bucket_name | ||
| BUCKET_NAME: str = s3_region | ||
| OPENAI_KEY: str = oepnai_key |
There was a problem hiding this comment.
oepnai_key에 오타가 있습니다. openai_key로 수정해야 합니다. 이 변수는 8라인과 12라인 두 곳에서 사용되고 있으며, 이 오타는 애플리케이션 설정 로딩 시 오류를 발생시킬 수 있습니다.
| oepnai_key = os.getenv("OPENAI_API_KEY") | |
| class Settings(BaseSettings): | |
| REDIS_URL: str = redis_url | |
| S3_REGION: str = bucket_name | |
| BUCKET_NAME: str = s3_region | |
| OPENAI_KEY: str = oepnai_key | |
| openai_key = os.getenv("OPENAI_API_KEY") | |
| class Settings(BaseSettings): | |
| REDIS_URL: str = redis_url | |
| OPENAI_KEY: str = openai_key |
| - isSafe: 안전하면 1, 안전하지 않으면 0 | ||
| - description: 복용 가능 여부 설명 | ||
| """ | ||
| def ask_chatgpt_about_pregnancy_safety(self, pill_name: str) -> tuple[str, int]: |
| prompt = f""" | ||
| 약 이름: {pill_name} | ||
| 질문: 이 약은 임산부가 복용해도 안전한가요? 복용 가능 여부와 주의사항을 알려주세요. | ||
| description 안에는 문장마다 \\n 을 적용하세요. | ||
| 결과를 JSON 형식으로 정확히 반환하세요. 설명이나 다른 텍스트를 절대 덧붙이지 마세요. | ||
| 스키마: | ||
| {{ | ||
| "description": "복용 가능 여부 및 주의사항에 대한 설명", | ||
| "isSafe": 1 또는 0 | ||
| }} | ||
| """ |
| max_tokens=600, | ||
| response_format={"type": "json_object"} | ||
| ) | ||
| print("GPT Asking 성공...") |
| if isinstance(isSafe, bool): | ||
| isSafe = 1 if isSafe else 0 | ||
| elif isinstance(isSafe, str): | ||
| isSafe = 1 if isSafe.strip() in {"1", "true", "True"} else 0 | ||
| elif not isinstance(isSafe, int): | ||
| isSafe = 0 |
There was a problem hiding this comment.
|
|
||
| isSafe = 0 | ||
| description = "일단은 테스트입니다. 추후에 GPT 부분 추가할 예정" | ||
| print(f"[task] Start Asking GPT for job_id={correlationId}") |
There was a problem hiding this comment.
디버깅 및 로깅을 위해 print를 사용하는 것보다 표준 logging 모듈을 사용하는 것이 좋습니다. 이를 통해 로그 레벨, 포맷, 출력 대상을 유연하게 관리할 수 있습니다. 파일 상단에 import logging을 추가하고 logging.info()와 같은 함수를 사용해 주세요.
| print(f"[task] Start Asking GPT for job_id={correlationId}") | |
| logging.info(f"[task] Start Asking GPT for job_id={correlationId}") |
📌 작업 목적
🗂 작업 유형
🔨 주요 작업 내용
openai_service.py🧪 테스트 결과
📎 관련 이슈
💬 논의 및 고민한 점
✅ 체크리스트