Update app.py
Browse files
app.py
CHANGED
@@ -20,9 +20,6 @@ BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
|
|
20 |
MODEL_ID = "dep89a2fld32mcm"
|
21 |
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
22 |
|
23 |
-
# 전역 변수
|
24 |
-
conversation_history = []
|
25 |
-
|
26 |
class LLMCollaborativeSystem:
|
27 |
def __init__(self):
|
28 |
self.token = FRIENDLI_TOKEN
|
@@ -66,6 +63,24 @@ class LLMCollaborativeSystem:
|
|
66 |
키워드는 다음 형식으로 제시하세요:
|
67 |
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
|
68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
70 |
"""조사자 AI 프롬프트 생성"""
|
71 |
search_summary = ""
|
@@ -92,13 +107,42 @@ class LLMCollaborativeSystem:
|
|
92 |
3. 실행자 AI가 활용할 수 있는 구체적인 데이터와 사실을 추출하세요
|
93 |
4. 최신 트렌드나 중요한 통계가 있다면 강조하세요"""
|
94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
def create_supervisor_execution_prompt(self, user_query: str, research_summary: str) -> str:
|
96 |
"""감독자 AI의 실행 지시 프롬프트"""
|
97 |
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
98 |
|
99 |
사용자 질문: {user_query}
|
100 |
|
101 |
-
조사자 AI가 정리한 조사 내용:
|
102 |
{research_summary}
|
103 |
|
104 |
위 조사 내용을 기반으로 실행자 AI에게 아주 구체적인 지시를 내려주세요:
|
@@ -147,14 +191,14 @@ class LLMCollaborativeSystem:
|
|
147 |
4. 명확한 결론과 다음 단계를 제시하세요
|
148 |
5. 전문적이고 완성도 높은 최종 보고서 형식으로 작성하세요"""
|
149 |
|
150 |
-
def extract_keywords(self,
|
151 |
-
"""
|
152 |
keywords = []
|
153 |
|
154 |
-
# [검색 키워드]: 형식으로 키워드 찾기
|
155 |
-
keyword_match = re.search(r'\[
|
156 |
if keyword_match:
|
157 |
-
keyword_str = keyword_match.group(
|
158 |
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
159 |
|
160 |
# 키워드가 없으면 기본 키워드 생성
|
@@ -252,7 +296,7 @@ class LLMCollaborativeSystem:
|
|
252 |
|
253 |
[검색 키워드]: machine learning optimization, performance improvement strategies, model efficiency techniques, hyperparameter tuning best practices, latest ML trends 2024""",
|
254 |
|
255 |
-
"
|
256 |
|
257 |
**1. Machine Learning Optimization**
|
258 |
- 최신 연구에 따르면 모델 최적화의 핵심은 아키텍처 설계와 훈련 전략의 균형입니다
|
@@ -274,273 +318,610 @@ class LLMCollaborativeSystem:
|
|
274 |
- Tesla: 실시간 객체 인식 속도 50% 개선
|
275 |
- OpenAI: GPT 모델 효율성 개선으로 비용 70% 절감""",
|
276 |
|
277 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
278 |
|
279 |
-
**1단계: 현재
|
280 |
-
- 조사된
|
281 |
-
|
282 |
-
|
|
|
|
|
|
|
283 |
|
284 |
-
**2단계: 데이터 품질
|
285 |
-
- 조사 결과의 "80% 규칙"
|
286 |
-
-
|
287 |
-
-
|
288 |
|
289 |
**3단계: 모델 최적화 구현 (4-6주차)**
|
290 |
-
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
298 |
|
299 |
-
"executor": """감독자의 지시와 조사 내용을 기반으로 구체적인 실행 계획을 수립합니다.
|
300 |
-
|
301 |
-
**
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
-
|
307 |
-
|
308 |
-
|
309 |
-
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
|
316 |
**3단계: 모델 최적화 구현 (4-6주차)**
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
341 |
|
342 |
-
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 잘 반영되었습니다. 다음과 같은 개선사항을 제안합니다.
|
343 |
|
344 |
**강점**
|
345 |
-
- 조사된
|
346 |
-
-
|
347 |
-
-
|
|
|
348 |
|
349 |
**개선 필요사항**
|
350 |
-
|
351 |
-
|
352 |
-
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
-
|
360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
361 |
|
362 |
**추가 권장사항**
|
363 |
-
-
|
364 |
-
-
|
365 |
-
-
|
366 |
-
- 실패 사례에서 배운 교훈을 축적하는 시스템 구축""",
|
367 |
|
368 |
"executor_final": """감독자 AI의 피드백을 완전히 반영하여 최종 실행 보고서를 작성합니다.
|
369 |
|
370 |
-
# 🎯
|
371 |
|
372 |
## 📋 Executive Summary
|
373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
374 |
|
375 |
-
|
|
|
|
|
|
|
|
|
|
|
376 |
|
377 |
-
###
|
378 |
-
**월-화요일: 성능 메트릭 수집**
|
379 |
-
- MLflow를 통한 현재 모델 전체 분석
|
380 |
-
- Netflix 사례 기반 핵심 지표: 정확도(92%), 지연시간(45ms), 처리량(1,000 req/s)
|
381 |
-
- 리소스 사용량: GPU 메모리 8GB, 추론 시 CPU 사용률 85%
|
382 |
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
387 |
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
392 |
|
393 |
-
###
|
394 |
-
- 상세 성능 베이스라인 문서
|
395 |
-
- 개선 기회 우선순위 매트릭스
|
396 |
-
- 리스크 레지스터 및 대응 계획
|
397 |
|
398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
399 |
|
400 |
-
|
401 |
-
**2주차: 데이터 정제 파이프라인**
|
402 |
```python
|
403 |
-
|
404 |
-
class DataQualityPipeline:
|
405 |
def __init__(self):
|
406 |
-
self.
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
|
|
411 |
]
|
412 |
-
|
413 |
-
def
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
419 |
```
|
420 |
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
###
|
432 |
-
-
|
433 |
-
-
|
434 |
-
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
-
|
452 |
-
|
453 |
-
|
454 |
-
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
-
|
464 |
-
-
|
465 |
-
-
|
466 |
-
|
467 |
-
|
468 |
-
-
|
469 |
-
-
|
470 |
-
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
-
|
506 |
-
|
507 |
-
|
508 |
-
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
### 모니터링 및 유지보수
|
513 |
-
- 월간 성능 리뷰 미팅
|
514 |
-
- 분기별 재훈련 계획
|
515 |
-
- 신기술 도입 검토 (Sparse Models, MoE)
|
516 |
-
|
517 |
-
### 지식 공유
|
518 |
-
- 내부 기술 세미나 (월 1회)
|
519 |
-
- 외부 컨퍼런스 발표 준비
|
520 |
-
- 오픈소스 기여 계획
|
521 |
-
|
522 |
-
### 차기 프로젝트
|
523 |
-
- 엣지 디바이스 배포 최적화
|
524 |
-
- 연합 학습(Federated Learning) 도입
|
525 |
-
- AutoML 플랫폼 구축
|
526 |
|
527 |
## 📝 결론
|
528 |
-
본 프로젝트는 최신
|
529 |
|
530 |
---
|
531 |
*작성일: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
|
532 |
-
*작성자: 협력적 AI 시스템 (감독자, 조사자, 실행자 AI)*
|
|
|
533 |
}
|
534 |
|
535 |
# 프롬프트 내용에 따라 적절한 응답 선택
|
536 |
-
if role == "supervisor" and "조사자 AI
|
|
|
|
|
537 |
response = test_responses["supervisor_execution"]
|
538 |
elif role == "supervisor" and messages[0]["content"].find("실행자 AI의 답변") > -1:
|
539 |
response = test_responses["supervisor_review"]
|
540 |
elif role == "supervisor":
|
541 |
response = test_responses["supervisor_initial"]
|
|
|
|
|
542 |
elif role == "researcher":
|
543 |
-
response = test_responses["
|
544 |
elif role == "executor" and "최종 보고서" in messages[0]["content"]:
|
545 |
response = test_responses["executor_final"]
|
546 |
else:
|
@@ -549,7 +930,7 @@ class DataQualityPipeline:
|
|
549 |
yield from self.simulate_streaming(response, role)
|
550 |
return
|
551 |
|
552 |
-
# 실제 API 호출
|
553 |
try:
|
554 |
system_prompts = {
|
555 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
@@ -614,12 +995,11 @@ class DataQualityPipeline:
|
|
614 |
# 시스템 인스턴스 생성
|
615 |
llm_system = LLMCollaborativeSystem()
|
616 |
|
617 |
-
def process_query_streaming(user_query: str
|
618 |
-
"""스트리밍을 지원하는 쿼리 처리"""
|
619 |
if not user_query:
|
620 |
-
return
|
621 |
|
622 |
-
conversation_log = []
|
623 |
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
624 |
|
625 |
try:
|
@@ -627,24 +1007,21 @@ def process_query_streaming(user_query: str, history: List):
|
|
627 |
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
628 |
supervisor_initial_response = ""
|
629 |
|
630 |
-
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
631 |
for chunk in llm_system.call_llm_streaming(
|
632 |
[{"role": "user", "content": supervisor_prompt}],
|
633 |
"supervisor"
|
634 |
):
|
635 |
supervisor_initial_response += chunk
|
636 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
637 |
-
yield
|
638 |
|
639 |
all_responses["supervisor"].append(supervisor_initial_response)
|
640 |
-
|
641 |
-
# 키워드 추출
|
642 |
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
643 |
-
logger.info(f"추출된 키워드: {keywords}")
|
644 |
|
645 |
-
# 2단계: 브레이브 검색
|
646 |
-
researcher_text = "[웹 검색] 🔍 검색 중...\n"
|
647 |
-
yield
|
648 |
|
649 |
search_results = {}
|
650 |
for keyword in keywords:
|
@@ -652,55 +1029,104 @@ def process_query_streaming(user_query: str, history: List):
|
|
652 |
if results:
|
653 |
search_results[keyword] = results
|
654 |
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
655 |
-
yield
|
656 |
|
657 |
-
# 3단계: 조사자 AI
|
658 |
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
659 |
researcher_response = ""
|
660 |
|
661 |
-
researcher_text = "[조사
|
662 |
for chunk in llm_system.call_llm_streaming(
|
663 |
[{"role": "user", "content": researcher_prompt}],
|
664 |
"researcher"
|
665 |
):
|
666 |
researcher_response += chunk
|
667 |
-
researcher_text = f"[조사
|
668 |
-
yield
|
669 |
|
670 |
all_responses["researcher"].append(researcher_response)
|
671 |
|
672 |
-
# 4단계: 감독자 AI가 조사 내용
|
673 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
674 |
supervisor_execution_response = ""
|
675 |
|
676 |
-
supervisor_text += "\n\n---\n\n[실행 지시] 🔄 생성 중...\n"
|
677 |
for chunk in llm_system.call_llm_streaming(
|
678 |
[{"role": "user", "content": supervisor_execution_prompt}],
|
679 |
"supervisor"
|
680 |
):
|
681 |
supervisor_execution_response += chunk
|
682 |
-
|
683 |
-
|
684 |
-
|
|
|
685 |
|
686 |
all_responses["supervisor"].append(supervisor_execution_response)
|
687 |
|
688 |
-
#
|
689 |
-
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response,
|
690 |
executor_response = ""
|
691 |
|
692 |
-
executor_text = "[초기 구현] 🔄 생성 중...\n"
|
693 |
for chunk in llm_system.call_llm_streaming(
|
694 |
[{"role": "user", "content": executor_prompt}],
|
695 |
"executor"
|
696 |
):
|
697 |
executor_response += chunk
|
698 |
-
executor_text = f"[초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
699 |
-
yield
|
700 |
|
701 |
all_responses["executor"].append(executor_response)
|
702 |
|
703 |
-
#
|
704 |
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
705 |
|
706 |
사용자 질문: {user_query}
|
@@ -711,47 +1137,46 @@ def process_query_streaming(user_query: str, history: List):
|
|
711 |
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요. 구체적이고 실행 가능한 개선 방안을 제시하세요."""
|
712 |
|
713 |
review_response = ""
|
714 |
-
supervisor_text
|
715 |
|
716 |
for chunk in llm_system.call_llm_streaming(
|
717 |
[{"role": "user", "content": review_prompt}],
|
718 |
"supervisor"
|
719 |
):
|
720 |
review_response += chunk
|
721 |
-
|
722 |
-
|
723 |
-
|
|
|
724 |
|
725 |
all_responses["supervisor"].append(review_response)
|
726 |
|
727 |
-
#
|
728 |
final_executor_prompt = llm_system.create_executor_final_prompt(
|
729 |
-
user_query,
|
730 |
-
executor_response,
|
731 |
-
review_response,
|
732 |
-
researcher_response
|
733 |
)
|
734 |
final_executor_response = ""
|
735 |
|
736 |
-
executor_text += "\n\n---\n\n[최종 보고서] 🔄 작성 중...\n"
|
737 |
for chunk in llm_system.call_llm_streaming(
|
738 |
[{"role": "user", "content": final_executor_prompt}],
|
739 |
"executor"
|
740 |
):
|
741 |
final_executor_response += chunk
|
742 |
-
|
743 |
-
|
744 |
-
|
|
|
745 |
|
746 |
all_responses["executor"].append(final_executor_response)
|
747 |
|
748 |
-
# 최종 결과 생성
|
749 |
final_summary = f"""## 🎯 최종 종합 보고서
|
750 |
|
751 |
### 📌 사용자 질문
|
752 |
{user_query}
|
753 |
|
754 |
-
### 📄 최종 보고서 (실행자 AI - 피드백 반영)
|
755 |
{final_executor_response}
|
756 |
|
757 |
---
|
@@ -759,38 +1184,41 @@ def process_query_streaming(user_query: str, history: List):
|
|
759 |
<details>
|
760 |
<summary>📋 전체 협력 과정 보기</summary>
|
761 |
|
762 |
-
####
|
763 |
{all_responses['supervisor'][0]}
|
764 |
|
765 |
-
####
|
766 |
-
{
|
767 |
|
768 |
-
####
|
769 |
{all_responses['supervisor'][1]}
|
770 |
|
771 |
-
####
|
772 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
773 |
|
774 |
-
####
|
775 |
-
{
|
776 |
|
777 |
</details>
|
778 |
|
779 |
---
|
780 |
-
*이 보고서는 웹
|
781 |
|
782 |
-
|
783 |
-
new_history = history + [(user_query, final_summary)]
|
784 |
-
|
785 |
-
yield new_history, supervisor_text, researcher_text, executor_text, final_summary, "✅ 최종 보고서 완성!"
|
786 |
|
787 |
except Exception as e:
|
788 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
789 |
-
yield
|
790 |
|
791 |
def clear_all():
|
792 |
"""모든 내용 초기화"""
|
793 |
-
return
|
794 |
|
795 |
# Gradio 인터페이스
|
796 |
css = """
|
@@ -800,109 +1228,106 @@ css = """
|
|
800 |
.supervisor-box textarea {
|
801 |
border-left: 4px solid #667eea !important;
|
802 |
padding-left: 10px !important;
|
|
|
803 |
}
|
804 |
.researcher-box textarea {
|
805 |
border-left: 4px solid #10b981 !important;
|
806 |
padding-left: 10px !important;
|
|
|
807 |
}
|
808 |
.executor-box textarea {
|
809 |
border-left: 4px solid #764ba2 !important;
|
810 |
padding-left: 10px !important;
|
|
|
811 |
}
|
812 |
"""
|
813 |
|
814 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
815 |
gr.Markdown(
|
816 |
f"""
|
817 |
-
# 🤝 협력적 LLM 시스템
|
818 |
|
819 |
-
> 감독자, 조사자, 실행자 AI가
|
820 |
|
821 |
**상태**:
|
822 |
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
823 |
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
824 |
|
825 |
-
**
|
826 |
-
1. 🧠
|
827 |
-
2. 🔍
|
828 |
-
3.
|
829 |
-
4.
|
830 |
-
5.
|
831 |
-
6.
|
832 |
-
7.
|
|
|
|
|
|
|
833 |
"""
|
834 |
)
|
835 |
|
|
|
836 |
with gr.Row():
|
837 |
-
|
838 |
-
with gr.Column(scale=1):
|
839 |
-
chatbot = gr.Chatbot(
|
840 |
-
label="💬 대화 기록",
|
841 |
-
height=600,
|
842 |
-
show_copy_button=True,
|
843 |
-
bubble_full_width=False
|
844 |
-
)
|
845 |
-
|
846 |
user_input = gr.Textbox(
|
847 |
label="질문 입력",
|
848 |
-
placeholder="예: 기계학습 모델의 성능을 향상시키는 방법은?",
|
849 |
-
lines=
|
850 |
)
|
851 |
-
|
852 |
-
|
853 |
-
|
854 |
-
|
855 |
-
|
856 |
-
|
857 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
858 |
interactive=False,
|
859 |
-
|
860 |
-
max_lines=1
|
861 |
)
|
862 |
|
863 |
-
#
|
864 |
-
with gr.Column(scale=
|
865 |
-
|
866 |
-
|
867 |
-
|
868 |
-
|
869 |
-
|
870 |
-
|
871 |
-
|
872 |
-
|
873 |
-
|
874 |
-
|
875 |
-
|
876 |
-
|
877 |
-
|
878 |
-
|
879 |
-
|
880 |
-
|
881 |
-
|
882 |
-
|
883 |
-
|
884 |
-
|
885 |
-
|
886 |
-
|
887 |
-
|
888 |
-
|
889 |
-
|
890 |
-
|
891 |
-
|
892 |
-
interactive=False,
|
893 |
-
elem_classes=["researcher-box"]
|
894 |
-
)
|
895 |
-
|
896 |
-
# 실행자 AI 출력
|
897 |
-
with gr.Column():
|
898 |
-
gr.Markdown("### 👁️ 실행자 AI (미시적 구현)")
|
899 |
-
executor_output = gr.Textbox(
|
900 |
-
label="",
|
901 |
-
lines=12,
|
902 |
-
max_lines=15,
|
903 |
-
interactive=False,
|
904 |
-
elem_classes=["executor-box"]
|
905 |
-
)
|
906 |
|
907 |
# 예제
|
908 |
gr.Examples(
|
@@ -920,8 +1345,8 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
920 |
# 이벤트 핸들러
|
921 |
submit_btn.click(
|
922 |
fn=process_query_streaming,
|
923 |
-
inputs=[user_input
|
924 |
-
outputs=[
|
925 |
).then(
|
926 |
fn=lambda: "",
|
927 |
outputs=[user_input]
|
@@ -929,8 +1354,8 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
929 |
|
930 |
user_input.submit(
|
931 |
fn=process_query_streaming,
|
932 |
-
inputs=[user_input
|
933 |
-
outputs=[
|
934 |
).then(
|
935 |
fn=lambda: "",
|
936 |
outputs=[user_input]
|
@@ -938,7 +1363,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
938 |
|
939 |
clear_btn.click(
|
940 |
fn=clear_all,
|
941 |
-
outputs=[
|
942 |
)
|
943 |
|
944 |
gr.Markdown(
|
@@ -946,24 +1371,20 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
946 |
---
|
947 |
### 📝 사용 방법
|
948 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
949 |
-
2.
|
950 |
-
-
|
951 |
-
|
952 |
-
|
953 |
|
954 |
### ⚙️ 환경 설정
|
955 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
956 |
- **Brave Search API**: `export BAPI_TOKEN="your_brave_api_token"`
|
957 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
958 |
|
959 |
-
### 🔗 API 키 획득
|
960 |
-
- Friendli API: [https://friendli.ai](https://friendli.ai)
|
961 |
-
- Brave Search API: [https://brave.com/search/api/](https://brave.com/search/api/)
|
962 |
-
|
963 |
### 💡 특징
|
964 |
-
-
|
965 |
-
-
|
966 |
-
-
|
967 |
"""
|
968 |
)
|
969 |
|
|
|
20 |
MODEL_ID = "dep89a2fld32mcm"
|
21 |
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
22 |
|
|
|
|
|
|
|
23 |
class LLMCollaborativeSystem:
|
24 |
def __init__(self):
|
25 |
self.token = FRIENDLI_TOKEN
|
|
|
63 |
키워드는 다음 형식으로 제시하세요:
|
64 |
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
|
65 |
|
66 |
+
def create_supervisor_research_review_prompt(self, user_query: str, research_summary: str) -> str:
|
67 |
+
"""감독자 AI의 조사 내용 검토 및 추가 지시 프롬프트"""
|
68 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
69 |
+
|
70 |
+
사용자 질문: {user_query}
|
71 |
+
|
72 |
+
조사자 AI의 1차 조사 결과:
|
73 |
+
{research_summary}
|
74 |
+
|
75 |
+
위 조사 결과를 검토하고:
|
76 |
+
1. 조사된 내용의 품질과 완전성을 평가하세요
|
77 |
+
2. 부족하거나 누락된 중요한 정보를 식별하세요
|
78 |
+
3. 추가로 조사가 필요한 3-5개의 구체적인 키워드나 주제를 제시하세요
|
79 |
+
4. 조사자에게 특별히 주의해야 할 사항이나 중점적으로 찾아야 할 정보를 지시하세요
|
80 |
+
|
81 |
+
추가 키워드는 다음 형식으로 제시하세요:
|
82 |
+
[추가 검색 키워드]: 키워드1, 키워드2, 키워드3"""
|
83 |
+
|
84 |
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
85 |
"""조사자 AI 프롬프트 생성"""
|
86 |
search_summary = ""
|
|
|
107 |
3. 실행자 AI가 활용할 수 있는 구체적인 데이터와 사실을 추출하세요
|
108 |
4. 최신 트렌드나 중요한 통계가 있다면 강조하세요"""
|
109 |
|
110 |
+
def create_researcher_additional_prompt(self, user_query: str, previous_research: str, supervisor_feedback: str, search_results: Dict[str, List[Dict]]) -> str:
|
111 |
+
"""조사자 AI 추가 조사 프롬프트"""
|
112 |
+
search_summary = ""
|
113 |
+
for keyword, results in search_results.items():
|
114 |
+
search_summary += f"\n\n**{keyword}에 대한 추가 검색 결과:**\n"
|
115 |
+
for i, result in enumerate(results[:3], 1):
|
116 |
+
search_summary += f"{i}. {result.get('title', 'N/A')}\n"
|
117 |
+
search_summary += f" - {result.get('description', 'N/A')}\n"
|
118 |
+
search_summary += f" - 출처: {result.get('url', 'N/A')}\n"
|
119 |
+
|
120 |
+
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.
|
121 |
+
|
122 |
+
사용자 질문: {user_query}
|
123 |
+
|
124 |
+
이전 조사 내용:
|
125 |
+
{previous_research}
|
126 |
+
|
127 |
+
감독자 AI의 피드백 및 추가 조사 지시:
|
128 |
+
{supervisor_feedback}
|
129 |
+
|
130 |
+
추가 검색 결과:
|
131 |
+
{search_summary}
|
132 |
+
|
133 |
+
위 정보를 바탕으로:
|
134 |
+
1. 감독자가 요청한 추가 정보를 중점적으로 조사하세요
|
135 |
+
2. 이전 조사와 중복되지 않는 새로운 정보를 제공하세요
|
136 |
+
3. 특히 감독자가 지적한 부족한 부분을 보완하세요
|
137 |
+
4. 최종적으로 종합된 조사 결과를 제시하세요"""
|
138 |
+
|
139 |
def create_supervisor_execution_prompt(self, user_query: str, research_summary: str) -> str:
|
140 |
"""감독자 AI의 실행 지시 프롬프트"""
|
141 |
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
142 |
|
143 |
사용자 질문: {user_query}
|
144 |
|
145 |
+
조사자 AI가 정리한 최종 조사 내용:
|
146 |
{research_summary}
|
147 |
|
148 |
위 조사 내용을 기반으로 실행자 AI에게 아주 구체적인 지시를 내려주세요:
|
|
|
191 |
4. 명확한 결론과 다음 단계를 제시하세요
|
192 |
5. 전문적이고 완성도 높은 최종 보고서 형식으로 작성하세요"""
|
193 |
|
194 |
+
def extract_keywords(self, text: str) -> List[str]:
|
195 |
+
"""텍스트에서 키워드 추출"""
|
196 |
keywords = []
|
197 |
|
198 |
+
# [검색 키워드]: 또는 [추가 검색 키워드]: 형식으로 키워드 찾기
|
199 |
+
keyword_match = re.search(r'\[(추가 )?검색 키워드\]:\s*(.+)', text, re.IGNORECASE)
|
200 |
if keyword_match:
|
201 |
+
keyword_str = keyword_match.group(2)
|
202 |
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
203 |
|
204 |
# 키워드가 없으면 기본 키워드 생성
|
|
|
296 |
|
297 |
[검색 키워드]: machine learning optimization, performance improvement strategies, model efficiency techniques, hyperparameter tuning best practices, latest ML trends 2024""",
|
298 |
|
299 |
+
"researcher_initial": """조사 결과를 종합하여 다음과 같이 정리했습니다.
|
300 |
|
301 |
**1. Machine Learning Optimization**
|
302 |
- 최신 연구에 따르면 모델 최적화의 핵심은 아키텍처 설계와 훈련 전략의 균형입니다
|
|
|
318 |
- Tesla: 실시간 객체 인식 속도 50% 개선
|
319 |
- OpenAI: GPT 모델 효율성 개선으로 비용 70% 절감""",
|
320 |
|
321 |
+
"supervisor_research_review": """1차 조사 결과를 검토한 결과, 다음과 같은 평가와 추가 조사 지시를 제시합니다.
|
322 |
+
|
323 |
+
**조사 내용 평가**
|
324 |
+
- 강점: 주요 기술적 접근법과 대표적인 성공 사례가 잘 정리됨
|
325 |
+
- 부족한 점:
|
326 |
+
* 구체적인 구현 도구와 프레임워크 정보 부족
|
327 |
+
* 실패 사례와 함정(pitfalls) 정보 누락
|
328 |
+
* 비용-효과 분석의 구체적인 수치 부족
|
329 |
+
* 최신 논문이나 연구 결과의 구체적 인용 부족
|
330 |
+
|
331 |
+
**추가 조사 필요 사항**
|
332 |
+
1. 실제 구현 시 사용되는 구체적인 도구와 라이브러리
|
333 |
+
2. 모델 최적화 실패 사례와 그 원인 분석
|
334 |
+
3. 산업별 ROI 수치와 투자 대비 효과
|
335 |
+
4. 2024년 최신 연구 논문과 breakthrough 기술
|
336 |
+
5. 오픈소스 프로젝트와 커뮤니티 리소스
|
337 |
+
|
338 |
+
[추가 검색 키워드]: ML optimization tools 2024, model optimization failure cases, ML ROI analysis industry, breakthrough ML papers 2024, open source ML optimization""",
|
339 |
+
|
340 |
+
"researcher_additional": """감독자의 피드백을 반영하여 추가 조사를 수행했습니다.
|
341 |
+
|
342 |
+
**추가 조사 결과**
|
343 |
+
|
344 |
+
**1. 구체적인 구현 도구 및 프레임워크**
|
345 |
+
- **PyTorch Optimization Toolkit**: torch.optim, torch.nn.utils.prune
|
346 |
+
- **TensorFlow Model Optimization**: TF-MOT for pruning, quantization
|
347 |
+
- **ONNX Runtime**: 크로스 플랫폼 최적화, 평균 3배 속도 향상
|
348 |
+
- **Apache TVM**: 자동 최적화 컴파일러, 하드웨어별 최적화
|
349 |
+
- 출처: PyTorch Documentation 2024, TensorFlow Official Guide
|
350 |
+
|
351 |
+
**2. 실패 사례 및 교훈**
|
352 |
+
- **Uber의 Michelangelo 플랫폼**: 과도한 최적화로 인한 유지보수 문제
|
353 |
+
* 교훈: 최적화와 유지보수성의 균형 필요
|
354 |
+
- **Twitter의 추천 시스템**: 실시간 성능 최적화 실패
|
355 |
+
* 원인: 캐싱 전략 부재, 데이터 파이프라인 병목
|
356 |
+
- 출처: Uber Engineering Blog, Twitter Tech Blog 2024
|
357 |
+
|
358 |
+
**3. ROI 분석 및 비용 효과**
|
359 |
+
- **금융 산업**: 평균 ROI 312%, 투자 회수 기간 4.2개월
|
360 |
+
* JP Morgan: 사기 탐지 모델 최적화로 연간 $150M 절감
|
361 |
+
- **리테일**: 평균 ROI 245%, 투자 회수 기간 6개월
|
362 |
+
* Amazon: 추천 시스템 최적화로 매출 23% 증가
|
363 |
+
- **제조업**: 평균 ROI 189%, 투자 회수 기간 8개월
|
364 |
+
- 출처: McKinsey AI Report 2024, Gartner Analysis
|
365 |
+
|
366 |
+
**4. 2024년 최신 연구 및 Breakthrough**
|
367 |
+
- **Sparse Mixture of Experts (SMoE)**: 모델 크기 95% 감소, 성능 유지
|
368 |
+
* 논문: "Efficient Scaling with Sparse MoE" - Google DeepMind
|
369 |
+
- **Flash Attention v3**: 메모리 사용량 80% 감소
|
370 |
+
* 논문: "FlashAttention-3: Fast and Memory-Efficient Exact Attention"
|
371 |
+
- **Quantization-Aware Training 2.0**: 2-bit 양자화에서도 성능 유지
|
372 |
+
- 출처: NeurIPS 2024, ICML 2024 Proceedings
|
373 |
+
|
374 |
+
**5. 오픈소스 리소스**
|
375 |
+
- **Hugging Face Optimum**: 원클릭 모델 최적화 라이브러리
|
376 |
+
- **Microsoft DeepSpeed**: 대규모 모델 훈련 및 추론 최적화
|
377 |
+
- **NVIDIA TensorRT**: GPU 최적화 추론 엔진
|
378 |
+
- **Intel OpenVINO**: CPU 최적화 툴킷
|
379 |
+
- 커뮤니티: r/MachineLearning, MLOps Community Slack
|
380 |
+
|
381 |
+
**종합 분석**
|
382 |
+
초기 조사와 추가 조사를 종합하면, 성공적인 ML 모델 최적화를 위해서는:
|
383 |
+
1. 적절한 도구 선택과 단계적 접근이 필수
|
384 |
+
2. 실패 사례에서 배운 교훈을 사전에 반영
|
385 |
+
3. 명확한 ROI 목표와 측정 지표 설정
|
386 |
+
4. 최신 연구 결과의 선별적 적용
|
387 |
+
5. 오픈소스 커뮤니티의 적극적 활용""",
|
388 |
+
|
389 |
+
"supervisor_execution": """종합된 조사 내용을 바탕으로 실행자 AI에게 다음과 같이 구체적으로 지시합니다.
|
390 |
+
|
391 |
+
**실행 전략 수립 지침**
|
392 |
|
393 |
+
**1단계: 현재 상태 진단 및 도구 선택 (1주차)**
|
394 |
+
- 조사된 도구 중 프로젝트에 적합한 것 선택:
|
395 |
+
* PyTorch 기반: PyTorch Optimization Toolkit 활용
|
396 |
+
* TensorFlow 기반: TF-MOT 활용
|
397 |
+
* 크로스 플랫폼: ONNX Runtime 고려
|
398 |
+
- Uber와 Twitter의 실패 사례를 참고하여 리스크 체크리스트 작성
|
399 |
+
- 금융업 ROI 312% 사례를 벤치마크로 목표 설정
|
400 |
|
401 |
+
**2단계: 데이터 품질 및 파이프라인 최적화 (2-3주차)**
|
402 |
+
- 조사 결과의 "80% 규칙" 적용
|
403 |
+
- Twitter 사례를 참고하여 캐싱 전략 수립
|
404 |
+
- 데이터 파이프라인 병목 지점 사전 제거
|
405 |
|
406 |
**3단계: 모델 최적화 구현 (4-6주차)**
|
407 |
+
- 최신 연구 적용:
|
408 |
+
* Sparse MoE로 모델 크기 95% 감소 시도
|
409 |
+
* Flash Attention v3로 메모리 효율성 개선
|
410 |
+
* Quantization-Aware Training 2.0 적용
|
411 |
+
- 오픈소스 활용:
|
412 |
+
* Hugging Face Optimum으로 빠른 프로토타이핑
|
413 |
+
* DeepSpeed로 대규모 모델 처리
|
414 |
+
* 하드웨어별 최적화 (TensorRT/OpenVINO)
|
415 |
+
|
416 |
+
**4단계: 검증 및 배포 (7-8주차)**
|
417 |
+
- JP Morgan 사례 참고하여 비용 절감 효과 측정
|
418 |
+
- Amazon 사례의 A/B 테스트 방법론 적용
|
419 |
+
- 투자 회수 기간 4-6개월 목표로 ROI 계산
|
420 |
+
|
421 |
+
**특별 지시사항**
|
422 |
+
1. 각 단계에서 실패 사례의 교훈 반영 필수
|
423 |
+
2. 오픈소스 커뮤니티와의 협업 계획 포함
|
424 |
+
3. 최신 논문의 기술을 단계적으로 적용
|
425 |
+
4. 구체적인 비용-효과 수치를 포함한 보고""",
|
426 |
|
427 |
+
"executor": """감독자의 지시와 종합 조사 내용을 기반으로 구체적인 실행 계획을 수립합니다.
|
428 |
+
|
429 |
+
**ML 모델 최적화 실행 계획**
|
430 |
+
|
431 |
+
**1단계: 현재 상태 진단 및 도구 선택 (1주차)**
|
432 |
+
|
433 |
+
*월요일-화요일: 현재 환경 분석 및 도구 선정*
|
434 |
+
- 현재 모델 스택 확인:
|
435 |
+
* PyTorch 2.0 기반 → PyTorch Optimization Toolkit 선택
|
436 |
+
* 모델 크기: 2.5GB, 추론 시간: 45ms, GPU 메모리: 8GB
|
437 |
+
- 리스크 체크리스트 (실패 사례 기반):
|
438 |
+
□ 유지보수성 vs 최적화 균형 계획
|
439 |
+
□ 캐싱 전략 사전 설계
|
440 |
+
□ 데이터 파이프라인 병목 분석
|
441 |
+
□ 롤백 계획 수립
|
442 |
+
|
443 |
+
*수요일-목요일: 벤치마크 설정 및 ROI 목표*
|
444 |
+
- 금융업 ROI 312% 사례 분석:
|
445 |
+
* 현재 추론 비용: $50,000/월
|
446 |
+
* 목표 절감액: $35,000/월 (70% 절감)
|
447 |
+
* 예상 투자: $60,000 (인건비 + 인프라)
|
448 |
+
* 목표 ROI: 250% (6개월 내)
|
449 |
+
|
450 |
+
*금요일: 도구 환경 구축*
|
451 |
+
```python
|
452 |
+
# environment_setup.py
|
453 |
+
pip install torch torchvision torchaudio
|
454 |
+
pip install transformers optimum
|
455 |
+
pip install onnx onnxruntime
|
456 |
+
pip install deepspeed
|
457 |
+
pip install tensorrt # NVIDIA GPU 환경
|
458 |
+
```
|
459 |
+
|
460 |
+
**2단계: 데이터 품질 및 파이프라인 최적화 (2-3주차)**
|
461 |
+
|
462 |
+
*2주차: 데이터 품질 개선 (80% 규칙 적용)*
|
463 |
+
```python
|
464 |
+
class DataQualityPipeline:
|
465 |
+
def __init__(self):
|
466 |
+
self.cache_strategy = RedisCacheStrategy() # Twitter 교훈 반영
|
467 |
+
self.quality_checks = [
|
468 |
+
MissingValueHandler(threshold=0.05),
|
469 |
+
OutlierDetector(method='isolation_forest'),
|
470 |
+
DataDriftMonitor(window_size=1000),
|
471 |
+
LabelQualityChecker()
|
472 |
+
]
|
473 |
+
|
474 |
+
def optimize_pipeline(self, data_loader):
|
475 |
+
# 병목 지점 프로파일링
|
476 |
+
profiler = DataPipelineProfiler()
|
477 |
+
bottlenecks = profiler.identify_bottlenecks(data_loader)
|
478 |
+
|
479 |
+
# 캐싱 적용
|
480 |
+
for bottleneck in bottlenecks:
|
481 |
+
self.cache_strategy.apply(bottleneck)
|
482 |
+
|
483 |
+
return self.quality_checks
|
484 |
+
```
|
485 |
+
|
486 |
+
*3주차: 파이프라인 병렬화 및 최적화*
|
487 |
+
- 데이터 로딩 병렬화: num_workers=8
|
488 |
+
- 프리페칭 버퍼 크기 최적화: prefetch_factor=4
|
489 |
+
- 메모리 매핑 활용으로 I/O 속도 3배 향상
|
490 |
|
491 |
**3단계: 모델 최적화 구현 (4-6주차)**
|
492 |
+
|
493 |
+
*4주차: Sparse MoE 적용 (95% 크기 감소)*
|
494 |
+
```python
|
495 |
+
from transformers import SwitchTransformersModel
|
496 |
+
import torch.nn.utils.prune as prune
|
497 |
+
|
498 |
+
class SparseMoEOptimizer:
|
499 |
+
def __init__(self, model):
|
500 |
+
self.model = model
|
501 |
+
self.sparsity_target = 0.95
|
502 |
+
|
503 |
+
def apply_sparse_moe(self):
|
504 |
+
# Google DeepMind 논문 기반 구현
|
505 |
+
moe_config = {
|
506 |
+
'num_experts': 8,
|
507 |
+
'expert_capacity': 128,
|
508 |
+
'router_z_loss_coef': 0.01
|
509 |
+
}
|
510 |
+
|
511 |
+
# 모델 변환
|
512 |
+
sparse_model = self.convert_to_moe(self.model, moe_config)
|
513 |
+
|
514 |
+
# 크기 검증: 2.5GB → 125MB (95% 감소)
|
515 |
+
return sparse_model
|
516 |
+
```
|
517 |
+
|
518 |
+
*5주차: Flash Attention v3 및 Quantization*
|
519 |
+
```python
|
520 |
+
from flash_attn import flash_attn_func
|
521 |
+
from transformers import BitsAndBytesConfig
|
522 |
+
|
523 |
+
# Flash Attention v3 적용
|
524 |
+
class FlashAttentionOptimizer:
|
525 |
+
def optimize_attention(self, model):
|
526 |
+
# 메모리 사용량 80% 감소
|
527 |
+
for layer in model.transformer.layers:
|
528 |
+
layer.attention = FlashAttentionV3(layer.attention)
|
529 |
+
return model
|
530 |
+
|
531 |
+
# 2-bit Quantization
|
532 |
+
quantization_config = BitsAndBytesConfig(
|
533 |
+
load_in_2bit=True,
|
534 |
+
bnb_2bit_compute_dtype=torch.float16,
|
535 |
+
bnb_2bit_use_double_quant=True,
|
536 |
+
bnb_2bit_quant_type="nf2" # NeurIPS 2024 논문 기법
|
537 |
+
)
|
538 |
+
```
|
539 |
+
|
540 |
+
*6주차: 하드웨어별 최적화 및 통합*
|
541 |
+
- NVIDIA GPU: TensorRT 최적화
|
542 |
+
* FP16 추론: 2배 속도 향상
|
543 |
+
* INT8 캘리브레이션: 추가 2배 속도 향상
|
544 |
+
- CPU: OpenVINO 최적화
|
545 |
+
* VNNI 명령어 활용
|
546 |
+
- 최종 통합 테스트
|
547 |
+
|
548 |
+
**4단계: 검증 및 배포 (7-8주차)**
|
549 |
+
|
550 |
+
*7주차: 성능 검증 및 ROI 분석*
|
551 |
+
- 성능 측정 결과:
|
552 |
+
* 모델 크기: 2.5GB → 125MB (95% 감소) ✓
|
553 |
+
* 추론 속도: 45ms → 3ms (15배 향상) ✓
|
554 |
+
* 정확도: 94.2% → 93.8% (0.4% 손실) ✓
|
555 |
+
* GPU 메모리: 8GB → 1GB (87.5% 감소) ✓
|
556 |
+
|
557 |
+
- 비용 분석 (JP Morgan 사례 참조):
|
558 |
+
* 인프라 비용: $50,000/월 → $12,500/월
|
559 |
+
* 절감액: $37,500/월
|
560 |
+
* 투자 회수 기간: 1.6개월
|
561 |
+
* 6개월 ROI: 275%
|
562 |
+
|
563 |
+
*8주차: 단계적 배포 (Amazon 사례 적용)*
|
564 |
+
```python
|
565 |
+
class CanaryDeployment:
|
566 |
+
def __init__(self):
|
567 |
+
self.stages = [
|
568 |
+
(0.01, 1), # 1% 트래픽, 1일
|
569 |
+
(0.05, 2), # 5% 트래픽, 2일
|
570 |
+
(0.20, 3), # 20% 트래픽, 3일
|
571 |
+
(0.50, 3), # 50% 트래픽, 3일
|
572 |
+
(1.00, None) # 100% 트래픽
|
573 |
+
]
|
574 |
+
|
575 |
+
def deploy(self, optimized_model):
|
576 |
+
for traffic_ratio, days in self.stages:
|
577 |
+
metrics = self.monitor_performance(traffic_ratio)
|
578 |
+
if not self.meets_sla(metrics):
|
579 |
+
self.rollback()
|
580 |
+
break
|
581 |
+
```
|
582 |
+
|
583 |
+
**산출물 및 문서화**
|
584 |
+
1. 최적화된 모델 아티팩트 (125MB)
|
585 |
+
2. 성능 벤치마크 보고서
|
586 |
+
3. ROI 분석 문서
|
587 |
+
4. 운영 가이드 및 모니터링 대시보드
|
588 |
+
5. 오픈소스 기여: Hugging Face Model Hub에 공개
|
589 |
+
|
590 |
+
**커뮤니티 협업 계획**
|
591 |
+
- MLOps Community Slack 채널 참여
|
592 |
+
- 월간 진행상황 블로그 포스팅
|
593 |
+
- 오픈소스 프로젝트에 최적화 도구 기여""",
|
594 |
|
595 |
+
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 매우 잘 반영되었습니다. 다음과 같은 개선사항을 제안합니다.
|
596 |
|
597 |
**강점**
|
598 |
+
- 조사된 모든 도구와 기법이 체계적으로 활용됨
|
599 |
+
- 실패 사례의 교훈이 리스크 관리에 잘 반영됨
|
600 |
+
- 구체적인 코드 예시와 측정 가능한 목표 설정
|
601 |
+
- ROI 분석이 산업 벤치마크와 잘 연계됨
|
602 |
|
603 |
**개선 필요사항**
|
604 |
+
|
605 |
+
1. **모니터링 및 알림 체계 강화**
|
606 |
+
- 실시간 성능 모니터링 대시보드 구축
|
607 |
+
- 이상 징후 자동 감지 및 알림 시스템
|
608 |
+
- Grafana + Prometheus 조합 권장
|
609 |
+
|
610 |
+
2. **팀 역량 개발 계획**
|
611 |
+
- Sparse MoE, Flash Attention 등 신기술 교육
|
612 |
+
- 내부 스터디 그룹 운영
|
613 |
+
- 외부 전문가 초청 세미나
|
614 |
+
|
615 |
+
3. **장기 유지보수 전략**
|
616 |
+
- 분기별 모델 재최적화 일정
|
617 |
+
- 새로운 최적화 기법 도입 프로세스
|
618 |
+
- 기술 부채 관리 계획
|
619 |
+
|
620 |
+
4. **리스크 대응 시나리오 구체화**
|
621 |
+
- 각 최적화 단계별 실패 시 Plan B
|
622 |
+
- 성능 저하 시 즉각 대응 매뉴얼
|
623 |
+
- 비즈니스 연속성 계획
|
624 |
|
625 |
**추가 권장사항**
|
626 |
+
- 성공 사례를 컨퍼런스에서 발표하여 브랜드 가치 향상
|
627 |
+
- 최적화 프레임워크를 내부 플랫폼으로 발전
|
628 |
+
- 다른 팀/프로젝트에도 적용 가능한 템플릿 제작""",
|
|
|
629 |
|
630 |
"executor_final": """감독자 AI의 피드백을 완전히 반영하여 최종 실행 보고서를 작성합니다.
|
631 |
|
632 |
+
# 🎯 ML 모델 최적화 프로젝트 최종 실행 보고서
|
633 |
|
634 |
## 📋 Executive Summary
|
635 |
+
8주간의 체계적인 접근을 통해 ML 모델의 크기를 95% 줄이고, 추론 속도를 15배 향상시키며, 운영 비용을 75% 절감하는 목표를 달성할 예정입니다. 최신 연구 결과와 실패 사례의 교훈을 반영하여 리스크를 최소화하고, 275%의 ROI를 6개월 내에 달성할 것으로 예상됩니다.
|
636 |
+
|
637 |
+
## 🏗️ 프로젝트 구조
|
638 |
+
|
639 |
+
### 1단계: 진단 및 준비 (1주차)
|
640 |
+
|
641 |
+
**현황 분석 및 도구 선정**
|
642 |
+
```yaml
|
643 |
+
현재 상태:
|
644 |
+
모델_크기: 2.5GB
|
645 |
+
추론_시간: 45ms
|
646 |
+
GPU_메모리: 8GB
|
647 |
+
월간_비용: $50,000
|
648 |
+
|
649 |
+
선택된 도구:
|
650 |
+
기본_프레임워크: PyTorch 2.0 + Optimization Toolkit
|
651 |
+
모델_최적화: Sparse MoE, Flash Attention v3
|
652 |
+
양자화: Quantization-Aware Training 2.0
|
653 |
+
배포_최적화: TensorRT (GPU), OpenVINO (CPU)
|
654 |
+
모니터링: Grafana + Prometheus + Custom Alerts
|
655 |
+
```
|
656 |
|
657 |
+
**리스크 관리 체크리스트**
|
658 |
+
- [ ] Uber 사례: 유지보수성 검증 프로세스
|
659 |
+
- [ ] Twitter 사례: 캐싱 전략 사전 검증
|
660 |
+
- [ ] 데이터 파이프라인 스트레스 테스트
|
661 |
+
- [ ] 각 단계별 롤백 계획 문서화
|
662 |
+
- [ ] Plan B 시나리오 준비
|
663 |
|
664 |
+
### 2단계: 데이터 최적화 (2-3주차)
|
|
|
|
|
|
|
|
|
665 |
|
666 |
+
**고급 데이터 파이프라인**
|
667 |
+
```python
|
668 |
+
class EnhancedDataPipeline:
|
669 |
+
def __init__(self):
|
670 |
+
self.cache = RedisCluster(
|
671 |
+
startup_nodes=[
|
672 |
+
{"host": "10.0.0.1", "port": "7000"},
|
673 |
+
{"host": "10.0.0.2", "port": "7000"}
|
674 |
+
],
|
675 |
+
decode_responses=True,
|
676 |
+
skip_full_coverage_check=True
|
677 |
+
)
|
678 |
+
|
679 |
+
# 실시간 모니터링 통합
|
680 |
+
self.monitor = DataPipelineMonitor(
|
681 |
+
prometheus_gateway="http://prometheus:9091",
|
682 |
+
alert_webhook="https://slack.webhook.url"
|
683 |
+
)
|
684 |
+
|
685 |
+
def optimize_with_monitoring(self, data_loader):
|
686 |
+
# 병목 지점 실시간 감지
|
687 |
+
with self.monitor.profile("data_loading"):
|
688 |
+
optimized_loader = self.apply_optimizations(data_loader)
|
689 |
+
|
690 |
+
# 성능 지표 자동 수집
|
691 |
+
self.monitor.record_metrics({
|
692 |
+
"throughput": self.calculate_throughput(),
|
693 |
+
"latency_p99": self.get_latency_percentile(99),
|
694 |
+
"cache_hit_rate": self.cache.get_hit_rate()
|
695 |
+
})
|
696 |
+
|
697 |
+
return optimized_loader
|
698 |
+
```
|
699 |
|
700 |
+
### 3단계: 모델 최적화 구현 (4-6주차)
|
701 |
+
|
702 |
+
**통합 최적화 프레임워크**
|
703 |
+
```python
|
704 |
+
class ModelOptimizationFramework:
|
705 |
+
def __init__(self, model, config):
|
706 |
+
self.model = model
|
707 |
+
self.config = config
|
708 |
+
self.optimization_history = []
|
709 |
+
|
710 |
+
def apply_optimizations(self):
|
711 |
+
# 1. Sparse MoE 적용 (95% 크기 감소)
|
712 |
+
self.model = self.apply_sparse_moe()
|
713 |
+
self.validate_performance("sparse_moe")
|
714 |
+
|
715 |
+
# 2. Flash Attention v3 (메모리 80% 감소)
|
716 |
+
self.model = self.apply_flash_attention()
|
717 |
+
self.validate_performance("flash_attention")
|
718 |
+
|
719 |
+
# 3. 2-bit Quantization (추가 크기 감소)
|
720 |
+
self.model = self.apply_quantization()
|
721 |
+
self.validate_performance("quantization")
|
722 |
+
|
723 |
+
# 4. 하드웨어별 최적화
|
724 |
+
if self.config.target_hardware == "gpu":
|
725 |
+
self.model = self.optimize_tensorrt()
|
726 |
+
else:
|
727 |
+
self.model = self.optimize_openvino()
|
728 |
+
|
729 |
+
return self.model
|
730 |
+
|
731 |
+
def validate_performance(self, stage):
|
732 |
+
"""각 최적화 단계 후 성능 검증"""
|
733 |
+
metrics = self.benchmark()
|
734 |
+
if not self.meets_requirements(metrics):
|
735 |
+
# Plan B 실행
|
736 |
+
self.execute_fallback_plan(stage)
|
737 |
+
self.optimization_history.append({
|
738 |
+
"stage": stage,
|
739 |
+
"metrics": metrics,
|
740 |
+
"timestamp": datetime.now()
|
741 |
+
})
|
742 |
+
```
|
743 |
|
744 |
+
### 4단계: 검증 및 배포 (7-8주차)
|
|
|
|
|
|
|
745 |
|
746 |
+
**고급 모니터링 대시보드**
|
747 |
+
```python
|
748 |
+
class MLOpsMonitoringDashboard:
|
749 |
+
def __init__(self):
|
750 |
+
self.grafana = GrafanaAPI(url="http://grafana:3000")
|
751 |
+
self.prometheus = PrometheusAPI(url="http://prometheus:9090")
|
752 |
+
|
753 |
+
def create_dashboards(self):
|
754 |
+
# 실시간 성능 대시보드
|
755 |
+
performance_dashboard = {
|
756 |
+
"title": "ML Model Performance",
|
757 |
+
"panels": [
|
758 |
+
self.create_latency_panel(),
|
759 |
+
self.create_throughput_panel(),
|
760 |
+
self.create_resource_usage_panel(),
|
761 |
+
self.create_cost_analysis_panel()
|
762 |
+
]
|
763 |
+
}
|
764 |
+
|
765 |
+
# 이상 징후 감지 대시보드
|
766 |
+
anomaly_dashboard = {
|
767 |
+
"title": "Anomaly Detection",
|
768 |
+
"panels": [
|
769 |
+
self.create_drift_detection_panel(),
|
770 |
+
self.create_error_rate_panel(),
|
771 |
+
self.create_sla_compliance_panel()
|
772 |
+
]
|
773 |
+
}
|
774 |
+
|
775 |
+
# 알림 규칙 설정
|
776 |
+
self.setup_alerts([
|
777 |
+
Alert("High Latency", "latency_p99 > 10ms", severity="warning"),
|
778 |
+
Alert("Model Drift", "accuracy_drop > 2%", severity="critical"),
|
779 |
+
Alert("High Error Rate", "error_rate > 0.1%", severity="critical")
|
780 |
+
])
|
781 |
+
```
|
782 |
|
783 |
+
**단계적 배포 전략**
|
|
|
784 |
```python
|
785 |
+
class EnhancedCanaryDeployment:
|
|
|
786 |
def __init__(self):
|
787 |
+
self.deployment_stages = [
|
788 |
+
{"traffic": 0.01, "duration": "1d", "rollback_threshold": 0.1},
|
789 |
+
{"traffic": 0.05, "duration": "2d", "rollback_threshold": 0.5},
|
790 |
+
{"traffic": 0.20, "duration": "3d", "rollback_threshold": 1.0},
|
791 |
+
{"traffic": 0.50, "duration": "3d", "rollback_threshold": 1.5},
|
792 |
+
{"traffic": 1.00, "duration": None, "rollback_threshold": 2.0}
|
793 |
]
|
794 |
+
|
795 |
+
def deploy_with_monitoring(self, model):
|
796 |
+
for stage in self.deployment_stages:
|
797 |
+
# 트래픽 라우팅
|
798 |
+
self.route_traffic(model, stage["traffic"])
|
799 |
+
|
800 |
+
# 실시간 모니터링
|
801 |
+
metrics = self.monitor_performance(duration=stage["duration"])
|
802 |
+
|
803 |
+
# 자동 롤백 검사
|
804 |
+
if self.should_rollback(metrics, stage["rollback_threshold"]):
|
805 |
+
self.automatic_rollback()
|
806 |
+
self.notify_team("Automatic rollback triggered")
|
807 |
+
return False
|
808 |
+
|
809 |
+
return True
|
810 |
```
|
811 |
|
812 |
+
## 📊 예상 성과 및 ROI
|
813 |
+
|
814 |
+
### 성능 개선
|
815 |
+
| 지표 | 현재 | 목표 | 달성 예상 |
|
816 |
+
|------|------|------|-----------|
|
817 |
+
| 모델 크기 | 2.5GB | 125MB | ✓ 95% 감소 |
|
818 |
+
| 추론 시간 | 45ms | 3ms | ✓ 15배 향상 |
|
819 |
+
| GPU 메모리 | 8GB | 1GB | ✓ 87.5% 감소 |
|
820 |
+
| 정확도 | 94.2% | >92% | ✓ 93.8% |
|
821 |
+
|
822 |
+
### 비용 절감 및 ROI
|
823 |
+
- **월간 인프라 비용**: $50,000 → $12,500 (75% 절감)
|
824 |
+
- **연간 절감액**: $450,000
|
825 |
+
- **프로젝트 투자**: $60,000
|
826 |
+
- **투자 회수 기간**: 1.6개월
|
827 |
+
- **6개월 ROI**: 275%
|
828 |
+
- **1년 ROI**: 650%
|
829 |
+
|
830 |
+
## 👥 팀 역량 개발 계획
|
831 |
+
|
832 |
+
### 교육 프로그램
|
833 |
+
1. **주간 기술 세미나** (매주 금요일 2시간)
|
834 |
+
- Week 1-2: Sparse MoE 아키텍처 이해
|
835 |
+
- Week 3-4: Flash Attention 구현 실습
|
836 |
+
- Week 5-6: 양자화 기법 심화
|
837 |
+
- Week 7-8: MLOps 모니터링 실무
|
838 |
+
|
839 |
+
2. **외부 전문가 초청 강연**
|
840 |
+
- Google DeepMind 엔지니어: Sparse MoE 실전 적용
|
841 |
+
- NVIDIA 전문가: TensorRT 최적화 팁
|
842 |
+
- MLOps 커뮤니티 리더: 프로덕션 모니터링
|
843 |
+
|
844 |
+
3. **핸즈온 워크샵**
|
845 |
+
- 매월 1회 전일 실습
|
846 |
+
- 실제 모델로 최적화 실습
|
847 |
+
- 페어 프로그래밍 세션
|
848 |
+
|
849 |
+
## 🔧 장기 유지보수 전략
|
850 |
+
|
851 |
+
### 분기별 최적화 사이클
|
852 |
+
```yaml
|
853 |
+
Q1:
|
854 |
+
- 새로운 데이터로 모델 재훈련
|
855 |
+
- 최신 최적화 기법 조사
|
856 |
+
- 성능 벤치마크 업데이트
|
857 |
+
|
858 |
+
Q2:
|
859 |
+
- 프로덕션 메트릭 분석
|
860 |
+
- 병목 지점 재식별
|
861 |
+
- 추가 최적화 적용
|
862 |
+
|
863 |
+
Q3:
|
864 |
+
- 하드웨어 업그레이드 검토
|
865 |
+
- 새로운 프레임워크 평가
|
866 |
+
- 비용-효과 재분석
|
867 |
+
|
868 |
+
Q4:
|
869 |
+
- 연간 성과 리뷰
|
870 |
+
- 차년도 계획 수립
|
871 |
+
- 기술 부채 해결
|
872 |
+
```
|
873 |
+
|
874 |
+
### 기술 부채 관리
|
875 |
+
- 월간 기술 부채 리뷰 미팅
|
876 |
+
- 우선순위 매트릭스 관리
|
877 |
+
- 20% 시간을 리팩토링에 할당
|
878 |
+
|
879 |
+
## 🚀 확장 계획
|
880 |
+
|
881 |
+
### 내부 플랫폼화
|
882 |
+
1. **ML 최적화 플랫폼 구축**
|
883 |
+
- 웹 기반 UI로 손쉬운 최적화
|
884 |
+
- 자동화된 벤치마킹
|
885 |
+
- 템플릿 기반 적용
|
886 |
+
|
887 |
+
2. **다른 팀 지원**
|
888 |
+
- 최적화 컨설팅 서비스
|
889 |
+
- 베스트 프랙티스 문서화
|
890 |
+
- 내부 교육 프로그램
|
891 |
+
|
892 |
+
### 외부 기여
|
893 |
+
1. **오픈소스 프로젝트**
|
894 |
+
- Hugging Face Optimum 기여
|
895 |
+
- 자체 최적화 도구 공개
|
896 |
+
- 커뮤니티 피드백 수렴
|
897 |
+
|
898 |
+
2. **컨퍼런스 발표**
|
899 |
+
- MLOps Summit 2024
|
900 |
+
- PyTorch Conference
|
901 |
+
- 기업 사례 공유
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
902 |
|
903 |
## 📝 결론
|
904 |
+
본 프로젝트는 최신 ML 최적화 기술과 실무 경험을 결합하여, 대규모 비용 절감과 성능 향상을 동시에 달성합니다. 체계적인 리스크 관리와 지속적인 개선 프로세스를 통해 장기적인 경쟁력을 확보하고, 조직 전체의 ML 역량을 한 단계 끌어올릴 것으로 기대됩니다.
|
905 |
|
906 |
---
|
907 |
*작성일: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
|
908 |
+
*작성자: 협력적 AI 시스템 (감독자, 조사자, 실행자 AI)*
|
909 |
+
*버전: 2.0 (피드백 완전 반영)*"""
|
910 |
}
|
911 |
|
912 |
# 프롬프트 내용에 따라 적절한 응답 선택
|
913 |
+
if role == "supervisor" and "조사자 AI의 1차 조사 결과" in messages[0]["content"]:
|
914 |
+
response = test_responses["supervisor_research_review"]
|
915 |
+
elif role == "supervisor" and "조사자 AI가 정리한 최종 조사 내용" in messages[0]["content"]:
|
916 |
response = test_responses["supervisor_execution"]
|
917 |
elif role == "supervisor" and messages[0]["content"].find("실행자 AI의 답변") > -1:
|
918 |
response = test_responses["supervisor_review"]
|
919 |
elif role == "supervisor":
|
920 |
response = test_responses["supervisor_initial"]
|
921 |
+
elif role == "researcher" and "추가 조사" in messages[0]["content"]:
|
922 |
+
response = test_responses["researcher_additional"]
|
923 |
elif role == "researcher":
|
924 |
+
response = test_responses["researcher_initial"]
|
925 |
elif role == "executor" and "최종 보고서" in messages[0]["content"]:
|
926 |
response = test_responses["executor_final"]
|
927 |
else:
|
|
|
930 |
yield from self.simulate_streaming(response, role)
|
931 |
return
|
932 |
|
933 |
+
# 실제 API 호출 (기존 코드와 동일)
|
934 |
try:
|
935 |
system_prompts = {
|
936 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
|
|
995 |
# 시스템 인스턴스 생성
|
996 |
llm_system = LLMCollaborativeSystem()
|
997 |
|
998 |
+
def process_query_streaming(user_query: str):
|
999 |
+
"""스트리밍을 지원하는 쿼리 처리 (대화 기록 제거)"""
|
1000 |
if not user_query:
|
1001 |
+
return "", "", "", "", "❌ 질문을 입력해주세요."
|
1002 |
|
|
|
1003 |
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
1004 |
|
1005 |
try:
|
|
|
1007 |
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
1008 |
supervisor_initial_response = ""
|
1009 |
|
1010 |
+
supervisor_text = "[1. 초기 분석] 🔄 생성 중...\n"
|
1011 |
for chunk in llm_system.call_llm_streaming(
|
1012 |
[{"role": "user", "content": supervisor_prompt}],
|
1013 |
"supervisor"
|
1014 |
):
|
1015 |
supervisor_initial_response += chunk
|
1016 |
+
supervisor_text = f"[1. 초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
1017 |
+
yield supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
1018 |
|
1019 |
all_responses["supervisor"].append(supervisor_initial_response)
|
|
|
|
|
1020 |
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
|
|
1021 |
|
1022 |
+
# 2단계: 1차 브레이브 검색
|
1023 |
+
researcher_text = "[2. 1차 웹 검색] 🔍 검색 중...\n"
|
1024 |
+
yield supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
1025 |
|
1026 |
search_results = {}
|
1027 |
for keyword in keywords:
|
|
|
1029 |
if results:
|
1030 |
search_results[keyword] = results
|
1031 |
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
1032 |
+
yield supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
1033 |
|
1034 |
+
# 3단계: 조사자 AI 1차 정리
|
1035 |
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
1036 |
researcher_response = ""
|
1037 |
|
1038 |
+
researcher_text = "[3. 1차 조사 정리] 🔄 생성 중...\n"
|
1039 |
for chunk in llm_system.call_llm_streaming(
|
1040 |
[{"role": "user", "content": researcher_prompt}],
|
1041 |
"researcher"
|
1042 |
):
|
1043 |
researcher_response += chunk
|
1044 |
+
researcher_text = f"[3. 1차 조사 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
1045 |
+
yield supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
1046 |
|
1047 |
all_responses["researcher"].append(researcher_response)
|
1048 |
|
1049 |
+
# 4단계: 감독자 AI가 조사 내용 검토 및 추가 지시
|
1050 |
+
supervisor_review_prompt = llm_system.create_supervisor_research_review_prompt(user_query, researcher_response)
|
1051 |
+
supervisor_review_response = ""
|
1052 |
+
|
1053 |
+
supervisor_text += "\n\n---\n\n[4. 조사 검토 및 추가 지시] 🔄 생성 중...\n"
|
1054 |
+
for chunk in llm_system.call_llm_streaming(
|
1055 |
+
[{"role": "user", "content": supervisor_review_prompt}],
|
1056 |
+
"supervisor"
|
1057 |
+
):
|
1058 |
+
supervisor_review_response += chunk
|
1059 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[4. 조사 검토 및 추가 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_review_response}"
|
1060 |
+
supervisor_text = f"[1. 초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
1061 |
+
yield supervisor_text, researcher_text, "", "", "🔍 감독자 AI가 추가 조사 지시 중..."
|
1062 |
+
|
1063 |
+
all_responses["supervisor"].append(supervisor_review_response)
|
1064 |
+
additional_keywords = llm_system.extract_keywords(supervisor_review_response)
|
1065 |
+
|
1066 |
+
# 5단계: 2차 브레이브 검색
|
1067 |
+
researcher_text += "\n\n---\n\n[5. 2차 웹 검색] 🔍 추가 검색 중...\n"
|
1068 |
+
yield supervisor_text, researcher_text, "", "", "🔍 추가 웹 검색 수행 중..."
|
1069 |
+
|
1070 |
+
additional_search_results = {}
|
1071 |
+
for keyword in additional_keywords:
|
1072 |
+
results = llm_system.brave_search(keyword)
|
1073 |
+
if results:
|
1074 |
+
additional_search_results[keyword] = results
|
1075 |
+
researcher_text += f"✓ '{keyword}' 추가 검색 완료\n"
|
1076 |
+
yield supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 추가 검색 중..."
|
1077 |
+
|
1078 |
+
# 6단계: 조사자 AI 최종 정리
|
1079 |
+
additional_researcher_prompt = llm_system.create_researcher_additional_prompt(
|
1080 |
+
user_query, researcher_response, supervisor_review_response, additional_search_results
|
1081 |
+
)
|
1082 |
+
final_researcher_response = ""
|
1083 |
+
|
1084 |
+
researcher_text += "\n\n---\n\n[6. 최종 조사 정리] 🔄 생성 중...\n"
|
1085 |
+
for chunk in llm_system.call_llm_streaming(
|
1086 |
+
[{"role": "user", "content": additional_researcher_prompt}],
|
1087 |
+
"researcher"
|
1088 |
+
):
|
1089 |
+
final_researcher_response += chunk
|
1090 |
+
temp_text = researcher_text.split("\n\n---\n\n")
|
1091 |
+
temp_text[-1] = f"[6. 최종 조사 정리] - {datetime.now().strftime('%H:%M:%S')}\n{final_researcher_response}"
|
1092 |
+
researcher_text = "\n\n---\n\n".join(temp_text)
|
1093 |
+
yield supervisor_text, researcher_text, "", "", "📝 조사자 AI가 최종 정리 중..."
|
1094 |
+
|
1095 |
+
all_responses["researcher"].append(final_researcher_response)
|
1096 |
+
|
1097 |
+
# 7단계: 감독자 AI가 최종 실행 지시
|
1098 |
+
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, final_researcher_response)
|
1099 |
supervisor_execution_response = ""
|
1100 |
|
1101 |
+
supervisor_text += "\n\n---\n\n[7. 실행 지시] 🔄 생성 중...\n"
|
1102 |
for chunk in llm_system.call_llm_streaming(
|
1103 |
[{"role": "user", "content": supervisor_execution_prompt}],
|
1104 |
"supervisor"
|
1105 |
):
|
1106 |
supervisor_execution_response += chunk
|
1107 |
+
parts = supervisor_text.split("\n\n---\n\n")
|
1108 |
+
parts[-1] = f"[7. 실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
|
1109 |
+
supervisor_text = "\n\n---\n\n".join(parts)
|
1110 |
+
yield supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 실행 지시 중..."
|
1111 |
|
1112 |
all_responses["supervisor"].append(supervisor_execution_response)
|
1113 |
|
1114 |
+
# 8단계: 실행자 AI 초기 구현
|
1115 |
+
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, final_researcher_response)
|
1116 |
executor_response = ""
|
1117 |
|
1118 |
+
executor_text = "[8. 초기 구현] 🔄 생성 중...\n"
|
1119 |
for chunk in llm_system.call_llm_streaming(
|
1120 |
[{"role": "user", "content": executor_prompt}],
|
1121 |
"executor"
|
1122 |
):
|
1123 |
executor_response += chunk
|
1124 |
+
executor_text = f"[8. 초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
1125 |
+
yield supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
1126 |
|
1127 |
all_responses["executor"].append(executor_response)
|
1128 |
|
1129 |
+
# 9단계: 감독자 AI 검토 및 피드백
|
1130 |
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
1131 |
|
1132 |
사용자 질문: {user_query}
|
|
|
1137 |
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요. 구체적이고 실행 가능한 개선 방안을 제시하세요."""
|
1138 |
|
1139 |
review_response = ""
|
1140 |
+
supervisor_text += "\n\n---\n\n[9. 검토 및 피드백] 🔄 생성 중...\n"
|
1141 |
|
1142 |
for chunk in llm_system.call_llm_streaming(
|
1143 |
[{"role": "user", "content": review_prompt}],
|
1144 |
"supervisor"
|
1145 |
):
|
1146 |
review_response += chunk
|
1147 |
+
parts = supervisor_text.split("\n\n---\n\n")
|
1148 |
+
parts[-1] = f"[9. 검토 및 피드백] - {datetime.now().strftime('%H:%M:%S')}\n{review_response}"
|
1149 |
+
supervisor_text = "\n\n---\n\n".join(parts)
|
1150 |
+
yield supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
1151 |
|
1152 |
all_responses["supervisor"].append(review_response)
|
1153 |
|
1154 |
+
# 10단계: 실행자 AI 최종 보고서
|
1155 |
final_executor_prompt = llm_system.create_executor_final_prompt(
|
1156 |
+
user_query, executor_response, review_response, final_researcher_response
|
|
|
|
|
|
|
1157 |
)
|
1158 |
final_executor_response = ""
|
1159 |
|
1160 |
+
executor_text += "\n\n---\n\n[10. 최종 보고서] 🔄 작성 중...\n"
|
1161 |
for chunk in llm_system.call_llm_streaming(
|
1162 |
[{"role": "user", "content": final_executor_prompt}],
|
1163 |
"executor"
|
1164 |
):
|
1165 |
final_executor_response += chunk
|
1166 |
+
parts = executor_text.split("\n\n---\n\n")
|
1167 |
+
parts[-1] = f"[10. 최종 보고서] - {datetime.now().strftime('%H:%M:%S')}\n{final_executor_response}"
|
1168 |
+
executor_text = "\n\n---\n\n".join(parts)
|
1169 |
+
yield supervisor_text, researcher_text, executor_text, "", "📄 최종 보고서 작성 중..."
|
1170 |
|
1171 |
all_responses["executor"].append(final_executor_response)
|
1172 |
|
1173 |
+
# 최종 결과 생성
|
1174 |
final_summary = f"""## 🎯 최종 종합 보고서
|
1175 |
|
1176 |
### 📌 사용자 질문
|
1177 |
{user_query}
|
1178 |
|
1179 |
+
### 📄 최종 보고서 (실행자 AI - 피드백 완전 반영)
|
1180 |
{final_executor_response}
|
1181 |
|
1182 |
---
|
|
|
1184 |
<details>
|
1185 |
<summary>📋 전체 협력 과정 보기</summary>
|
1186 |
|
1187 |
+
#### 1. 거시적 분석 (감독자 AI)
|
1188 |
{all_responses['supervisor'][0]}
|
1189 |
|
1190 |
+
#### 2. 1차 조사 결과 (조사자 AI)
|
1191 |
+
{all_responses['researcher'][0]}
|
1192 |
|
1193 |
+
#### 3. 조사 검토 및 추가 지시 (감독자 AI)
|
1194 |
{all_responses['supervisor'][1]}
|
1195 |
|
1196 |
+
#### 4. 최종 조사 결과 (조사자 AI)
|
1197 |
+
{all_responses['researcher'][1]}
|
1198 |
+
|
1199 |
+
#### 5. 실행 지시 (감독자 AI)
|
1200 |
+
{all_responses['supervisor'][2]}
|
1201 |
+
|
1202 |
+
#### 6. 초기 구현 (실행자 AI)
|
1203 |
+
{all_responses['executor'][0]}
|
1204 |
|
1205 |
+
#### 7. 검토 및 개선사항 (감독자 AI)
|
1206 |
+
{all_responses['supervisor'][3]}
|
1207 |
|
1208 |
</details>
|
1209 |
|
1210 |
---
|
1211 |
+
*이 보고서는 2차 웹 검색과 AI들의 완전한 협력을 통해 작성되었습니다.*"""
|
1212 |
|
1213 |
+
yield supervisor_text, researcher_text, executor_text, final_summary, "✅ 최종 보고서 완성!"
|
|
|
|
|
|
|
1214 |
|
1215 |
except Exception as e:
|
1216 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
1217 |
+
yield "", "", "", error_msg, error_msg
|
1218 |
|
1219 |
def clear_all():
|
1220 |
"""모든 내용 초기화"""
|
1221 |
+
return "", "", "", "", "🔄 초기화되었습니다."
|
1222 |
|
1223 |
# Gradio 인터페이스
|
1224 |
css = """
|
|
|
1228 |
.supervisor-box textarea {
|
1229 |
border-left: 4px solid #667eea !important;
|
1230 |
padding-left: 10px !important;
|
1231 |
+
font-size: 13px !important;
|
1232 |
}
|
1233 |
.researcher-box textarea {
|
1234 |
border-left: 4px solid #10b981 !important;
|
1235 |
padding-left: 10px !important;
|
1236 |
+
font-size: 13px !important;
|
1237 |
}
|
1238 |
.executor-box textarea {
|
1239 |
border-left: 4px solid #764ba2 !important;
|
1240 |
padding-left: 10px !important;
|
1241 |
+
font-size: 13px !important;
|
1242 |
}
|
1243 |
"""
|
1244 |
|
1245 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
1246 |
gr.Markdown(
|
1247 |
f"""
|
1248 |
+
# 🤝 강화된 협력적 LLM 시스템
|
1249 |
|
1250 |
+
> 감독자, 조사자, 실행자 AI가 10단계 협력 프로세스를 통해 완전한 보고서를 작성합니다.
|
1251 |
|
1252 |
**상태**:
|
1253 |
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
1254 |
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
1255 |
|
1256 |
+
**10단계 협력 프로세스:**
|
1257 |
+
1. 🧠 감독자: 초기 분석 및 키워드 추출
|
1258 |
+
2. 🔍 조사자: 1차 웹 검색
|
1259 |
+
3. 🔍 조사자: 1차 조사 정리
|
1260 |
+
4. 🧠 감독자: 조사 검토 및 추가 지시
|
1261 |
+
5. 🔍 조사자: 2차 웹 검색
|
1262 |
+
6. 🔍 조사자: 최종 조사 정리
|
1263 |
+
7. 🧠 감독자: 실행 지시
|
1264 |
+
8. 👁️ 실행자: 초기 구현
|
1265 |
+
9. 🧠 감독자: 검토 및 피드백
|
1266 |
+
10. 👁️ 실행자: 최종 보고서
|
1267 |
"""
|
1268 |
)
|
1269 |
|
1270 |
+
# 입력 섹션
|
1271 |
with gr.Row():
|
1272 |
+
with gr.Column(scale=4):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1273 |
user_input = gr.Textbox(
|
1274 |
label="질문 입력",
|
1275 |
+
placeholder="예: 기계학습 모델의 성능을 향상시키는 최신 방법은?",
|
1276 |
+
lines=2
|
1277 |
)
|
1278 |
+
with gr.Column(scale=1):
|
1279 |
+
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=1)
|
1280 |
+
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
1281 |
+
|
1282 |
+
status_text = gr.Textbox(
|
1283 |
+
label="상태",
|
1284 |
+
interactive=False,
|
1285 |
+
value="대기 중...",
|
1286 |
+
max_lines=1
|
1287 |
+
)
|
1288 |
+
|
1289 |
+
# AI 출력 섹션 (가로 3분할)
|
1290 |
+
with gr.Row():
|
1291 |
+
# 감독자 AI 출력
|
1292 |
+
with gr.Column(scale=1):
|
1293 |
+
gr.Markdown("### 🧠 감독자 AI")
|
1294 |
+
supervisor_output = gr.Textbox(
|
1295 |
+
label="거시적 분석 및 지시",
|
1296 |
+
lines=20,
|
1297 |
+
max_lines=25,
|
1298 |
interactive=False,
|
1299 |
+
elem_classes=["supervisor-box"]
|
|
|
1300 |
)
|
1301 |
|
1302 |
+
# 조사자 AI 출력
|
1303 |
+
with gr.Column(scale=1):
|
1304 |
+
gr.Markdown("### 🔍 조사자 AI")
|
1305 |
+
researcher_output = gr.Textbox(
|
1306 |
+
label="웹 검색 및 정리",
|
1307 |
+
lines=20,
|
1308 |
+
max_lines=25,
|
1309 |
+
interactive=False,
|
1310 |
+
elem_classes=["researcher-box"]
|
1311 |
+
)
|
1312 |
+
|
1313 |
+
# 실행자 AI 출력
|
1314 |
+
with gr.Column(scale=1):
|
1315 |
+
gr.Markdown("### 👁️ 실행자 AI")
|
1316 |
+
executor_output = gr.Textbox(
|
1317 |
+
label="구체적 구현",
|
1318 |
+
lines=20,
|
1319 |
+
max_lines=25,
|
1320 |
+
interactive=False,
|
1321 |
+
elem_classes=["executor-box"]
|
1322 |
+
)
|
1323 |
+
|
1324 |
+
# 최종 결과
|
1325 |
+
with gr.Row():
|
1326 |
+
with gr.Column():
|
1327 |
+
gr.Markdown("### 📊 최종 종합 결과")
|
1328 |
+
final_output = gr.Markdown(
|
1329 |
+
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
1330 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1331 |
|
1332 |
# 예제
|
1333 |
gr.Examples(
|
|
|
1345 |
# 이벤트 핸들러
|
1346 |
submit_btn.click(
|
1347 |
fn=process_query_streaming,
|
1348 |
+
inputs=[user_input],
|
1349 |
+
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1350 |
).then(
|
1351 |
fn=lambda: "",
|
1352 |
outputs=[user_input]
|
|
|
1354 |
|
1355 |
user_input.submit(
|
1356 |
fn=process_query_streaming,
|
1357 |
+
inputs=[user_input],
|
1358 |
+
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1359 |
).then(
|
1360 |
fn=lambda: "",
|
1361 |
outputs=[user_input]
|
|
|
1363 |
|
1364 |
clear_btn.click(
|
1365 |
fn=clear_all,
|
1366 |
+
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1367 |
)
|
1368 |
|
1369 |
gr.Markdown(
|
|
|
1371 |
---
|
1372 |
### 📝 사용 방법
|
1373 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
1374 |
+
2. 10단계 협력 프로세스가 진행됩니다:
|
1375 |
+
- 감독자의 2차 조사 검토로 더 완전한 정보 수집
|
1376 |
+
- 각 AI의 작업이 실시간으로 표시됩니다
|
1377 |
+
3. 최종 보고서가 하단에 표시됩니다.
|
1378 |
|
1379 |
### ⚙️ 환경 설정
|
1380 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
1381 |
- **Brave Search API**: `export BAPI_TOKEN="your_brave_api_token"`
|
1382 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
1383 |
|
|
|
|
|
|
|
|
|
1384 |
### 💡 특징
|
1385 |
+
- **강화된 조사**: 감독자가 조사 내용을 검토하고 추가 조사 지시
|
1386 |
+
- **가독성 개선**: 3개 AI 출력을 가로로 배치하여 동시 확인
|
1387 |
+
- **완전한 피드백 루프**: 모든 개선사항이 최종 보고서에 반영
|
1388 |
"""
|
1389 |
)
|
1390 |
|