Spaces:
Running
Running
Update app-BACKUP.py
Browse files- app-BACKUP.py +1250 -33
app-BACKUP.py
CHANGED
@@ -125,6 +125,1004 @@ class LLMCollaborativeSystem:
|
|
125 |
3. 실제로 적용 가능한 구체적인 방법론을 제시하세요
|
126 |
4. 예상되는 성과와 측정 방법을 포함하세요"""
|
127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
def extract_keywords(self, supervisor_response: str) -> List[str]:
|
129 |
"""감독자 응답에서 키워드 추출"""
|
130 |
keywords = []
|
@@ -317,24 +1315,200 @@ class LLMCollaborativeSystem:
|
|
317 |
- 프로덕션 배포 가이드 및 모니터링 대시보드
|
318 |
- 재현 가능한 최적화 파이프라인 코드""",
|
319 |
|
320 |
-
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 잘 반영되었습니다.
|
321 |
|
322 |
**강점**
|
323 |
- 조사된 사례들(Netflix, Tesla, OpenAI)이 각 단계에 적절히 활용됨
|
324 |
- 구체적인 도구와 기법이 명시되어 실행 가능성이 높음
|
325 |
- 측정 가능한 목표가 조사 결과를 기반으로 설정됨
|
326 |
|
327 |
-
|
328 |
-
1.
|
329 |
-
|
330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
|
332 |
**추가 권장사항**
|
333 |
- 최신 연구 동향 모니터링 체계 구축
|
334 |
- 경쟁사 벤치마킹을 위한 정기적인 조사 프로세스
|
335 |
-
- 내부 지식 공유를 위한 문서화 및 세미나 계획
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
336 |
}
|
337 |
|
|
|
338 |
if role == "supervisor" and "조사자 AI가 정리한" in messages[0]["content"]:
|
339 |
response = test_responses["supervisor_execution"]
|
340 |
elif role == "supervisor" and messages[0]["content"].find("실행자 AI의 답변") > -1:
|
@@ -343,6 +1517,8 @@ class LLMCollaborativeSystem:
|
|
343 |
response = test_responses["supervisor_initial"]
|
344 |
elif role == "researcher":
|
345 |
response = test_responses["researcher"]
|
|
|
|
|
346 |
else:
|
347 |
response = test_responses["executor"]
|
348 |
|
@@ -485,23 +1661,22 @@ def process_query_streaming(user_query: str, history: List):
|
|
485 |
|
486 |
all_responses["supervisor"].append(supervisor_execution_response)
|
487 |
|
488 |
-
# 5단계: 실행자 AI가 조사 내용과 지시를 기반으로
|
489 |
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, researcher_response)
|
490 |
executor_response = ""
|
491 |
|
492 |
-
executor_text = "[
|
493 |
for chunk in llm_system.call_llm_streaming(
|
494 |
[{"role": "user", "content": executor_prompt}],
|
495 |
"executor"
|
496 |
):
|
497 |
executor_response += chunk
|
498 |
-
executor_text = f"[
|
499 |
yield history, supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
500 |
|
501 |
all_responses["executor"].append(executor_response)
|
502 |
|
503 |
-
# 6단계: 감독자 AI
|
504 |
-
review_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
505 |
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
506 |
|
507 |
사용자 질문: {user_query}
|
@@ -509,48 +1684,81 @@ def process_query_streaming(user_query: str, history: List):
|
|
509 |
실행자 AI의 답변:
|
510 |
{executor_response}
|
511 |
|
512 |
-
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요."""
|
513 |
|
514 |
review_response = ""
|
515 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[
|
516 |
|
517 |
for chunk in llm_system.call_llm_streaming(
|
518 |
[{"role": "user", "content": review_prompt}],
|
519 |
"supervisor"
|
520 |
):
|
521 |
review_response += chunk
|
522 |
-
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[
|
523 |
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
524 |
yield history, supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
525 |
|
526 |
-
|
527 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
528 |
|
529 |
### 📌 사용자 질문
|
530 |
{user_query}
|
531 |
|
532 |
-
###
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
533 |
{all_responses['supervisor'][0]}
|
534 |
|
535 |
-
|
536 |
{researcher_response}
|
537 |
|
538 |
-
|
539 |
{all_responses['supervisor'][1]}
|
540 |
|
541 |
-
|
542 |
{executor_response}
|
543 |
|
544 |
-
|
545 |
{review_response}
|
546 |
|
|
|
|
|
547 |
---
|
548 |
-
*이
|
549 |
|
550 |
# 히스토리 업데이트
|
551 |
new_history = history + [(user_query, final_summary)]
|
552 |
|
553 |
-
yield new_history, supervisor_text, researcher_text, executor_text, final_summary, "✅
|
554 |
|
555 |
except Exception as e:
|
556 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
@@ -582,19 +1790,22 @@ css = """
|
|
582 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
583 |
gr.Markdown(
|
584 |
f"""
|
585 |
-
# 🤝 협력적 LLM 시스템 (조사자 포함)
|
586 |
|
587 |
-
> 감독자, 조사자, 실행자 AI가 협력하여
|
588 |
|
589 |
**상태**:
|
590 |
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
591 |
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
592 |
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
|
|
|
|
|
|
598 |
"""
|
599 |
)
|
600 |
|
@@ -711,9 +1922,10 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
711 |
---
|
712 |
### 📝 사용 방법
|
713 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
714 |
-
2.
|
715 |
-
|
716 |
-
|
|
|
717 |
|
718 |
### ⚙️ 환경 설정
|
719 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
@@ -723,6 +1935,11 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
723 |
### 🔗 API 키 획득
|
724 |
- Friendli API: [https://friendli.ai](https://friendli.ai)
|
725 |
- Brave Search API: [https://brave.com/search/api/](https://brave.com/search/api/)
|
|
|
|
|
|
|
|
|
|
|
726 |
"""
|
727 |
)
|
728 |
|
|
|
125 |
3. 실제로 적용 가능한 구체적인 방법론을 제시하세요
|
126 |
4. 예상되는 성과와 측정 방법을 포함하세요"""
|
127 |
|
128 |
+
def create_executor_final_prompt(self, user_query: str, initial_response: str, supervisor_feedback: str, research_summary: str) -> str:
|
129 |
+
"""실행자 AI 최종 보고서 프롬프트"""
|
130 |
+
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
131 |
+
|
132 |
+
사용자 질문: {user_query}
|
133 |
+
|
134 |
+
조사자 AI의 조사 내용:
|
135 |
+
{research_summary}
|
136 |
+
|
137 |
+
당신의 초기 답변:
|
138 |
+
{initial_response}
|
139 |
+
|
140 |
+
감독자 AI의 피드백 및 개선사항:
|
141 |
+
{supervisor_feedback}
|
142 |
+
|
143 |
+
위 피드백을 완전히 반영하여 최종 보고서를 작성하세요:
|
144 |
+
1. 감독자의 모든 개선사항을 반영하세요
|
145 |
+
2. 조사 내용을 더욱 구체적으로 활용하세요
|
146 |
+
3. 실행 가능성을 높이는 세부 계획을 포함하세요
|
147 |
+
4. 명확한 결론과 다음 단계를 제시하세요
|
148 |
+
5. 전문적이고 완성도 높은 최종 보고서 형식으로 작성하세요"""
|
149 |
+
|
150 |
+
def extract_keywords(self, supervisor_response: str) -> List[str]:
|
151 |
+
"""감독자 응답에서 키워드 추출"""
|
152 |
+
keywords = []
|
153 |
+
|
154 |
+
# [검색 키워드]: 형식으로 키워드 찾기
|
155 |
+
keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE)
|
156 |
+
if keyword_match:
|
157 |
+
keyword_str = keyword_match.group(1)
|
158 |
+
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
159 |
+
|
160 |
+
# 키워드가 없으면 기본 키워드 생성
|
161 |
+
if not keywords:
|
162 |
+
keywords = ["best practices", "implementation guide", "case studies", "latest trends", "success factors"]
|
163 |
+
|
164 |
+
return keywords[:7] # 최대 7개로 제한
|
165 |
+
|
166 |
+
def brave_search(self, query: str) -> List[Dict]:
|
167 |
+
"""Brave Search API 호출"""
|
168 |
+
if self.test_mode or self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
169 |
+
# 테스트 모드에서는 시뮬레이션된 결과 반환
|
170 |
+
return [
|
171 |
+
{
|
172 |
+
"title": f"Best Practices for {query}",
|
173 |
+
"description": f"Comprehensive guide on implementing {query} with proven methodologies and real-world examples.",
|
174 |
+
"url": f"https://example.com/{query.replace(' ', '-')}"
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"title": f"Latest Trends in {query}",
|
178 |
+
"description": f"Analysis of current trends and future directions in {query}, including market insights and expert opinions.",
|
179 |
+
"url": f"https://trends.example.com/{query.replace(' ', '-')}"
|
180 |
+
},
|
181 |
+
{
|
182 |
+
"title": f"{query}: Case Studies and Success Stories",
|
183 |
+
"description": f"Real-world implementations of {query} across various industries with measurable results.",
|
184 |
+
"url": f"https://casestudies.example.com/{query.replace(' ', '-')}"
|
185 |
+
}
|
186 |
+
]
|
187 |
+
|
188 |
+
try:
|
189 |
+
params = {
|
190 |
+
"q": query,
|
191 |
+
"count": 5,
|
192 |
+
"safesearch": "moderate",
|
193 |
+
"freshness": "pw" # Past week for recent results
|
194 |
+
}
|
195 |
+
|
196 |
+
response = requests.get(
|
197 |
+
self.brave_url,
|
198 |
+
headers=self.create_brave_headers(),
|
199 |
+
params=params,
|
200 |
+
timeout=10
|
201 |
+
)
|
202 |
+
|
203 |
+
if response.status_code == 200:
|
204 |
+
data = response.json()
|
205 |
+
results = []
|
206 |
+
for item in data.get("web", {}).get("results", [])[:5]:
|
207 |
+
results.append({
|
208 |
+
"title": item.get("title", ""),
|
209 |
+
"description": item.get("description", ""),
|
210 |
+
"url": item.get("url", "")
|
211 |
+
})
|
212 |
+
return results
|
213 |
+
else:
|
214 |
+
logger.error(f"Brave API 오류: {response.status_code}")
|
215 |
+
return []
|
216 |
+
|
217 |
+
except Exception as e:
|
218 |
+
logger.error(f"Brave 검색 중 오류: {str(e)}")
|
219 |
+
return []
|
220 |
+
|
221 |
+
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
|
222 |
+
"""테스트 모드에서 스트리밍 시뮬레이션"""
|
223 |
+
words = text.split()
|
224 |
+
for i in range(0, len(words), 3):
|
225 |
+
chunk = " ".join(words[i:i+3])
|
226 |
+
yield chunk + " "
|
227 |
+
time.sleep(0.05)
|
228 |
+
|
229 |
+
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]:
|
230 |
+
"""스트리밍 LLM API 호출"""
|
231 |
+
|
232 |
+
# 테스트 모드
|
233 |
+
if self.test_mode:
|
234 |
+
logger.info(f"테스트 모드 스트리밍 - Role: {role}")
|
235 |
+
test_responses = {
|
236 |
+
"supervisor_initial": """이 질문에 대한 거시적 분석을 제시하겠습니다.
|
237 |
+
|
238 |
+
1. **핵심 개념 파악**
|
239 |
+
- 질문의 본���적 요소를 심층 분석합니다
|
240 |
+
- 관련된 주요 이론과 원칙을 검토합니다
|
241 |
+
- 다양한 관점에서의 접근 방법을 고려합니다
|
242 |
+
|
243 |
+
2. **전략적 접근 방향**
|
244 |
+
- 체계적이고 단계별 해결 방안을 수립합니다
|
245 |
+
- 장단기 목표를 명확히 설정합니다
|
246 |
+
- 리스크 요인과 대응 방안을 마련합니다
|
247 |
+
|
248 |
+
3. **기대 효과와 과제**
|
249 |
+
- 예상되는 긍정적 성과를 분석합니다
|
250 |
+
- 잠재적 도전 과제를 식별합니다
|
251 |
+
- 지속가능한 발전 방향을 제시합니다
|
252 |
+
|
253 |
+
[검색 키워드]: machine learning optimization, performance improvement strategies, model efficiency techniques, hyperparameter tuning best practices, latest ML trends 2024""",
|
254 |
+
|
255 |
+
"researcher": """조사 결과를 종합하여 다음과 같이 정리했습니다.
|
256 |
+
|
257 |
+
**1. Machine Learning Optimization**
|
258 |
+
- 최신 연구에 따르면 모델 최적화의 핵심은 아키텍처 설계와 훈련 전략의 균형입니다
|
259 |
+
- AutoML 도구들이 하이퍼파라미터 튜닝을 자동화하여 효율성을 크게 향상시킵니다
|
260 |
+
- 출처: ML Conference 2024, Google Research
|
261 |
+
|
262 |
+
**2. Performance Improvement Strategies**
|
263 |
+
- 데이터 품질 개선이 모델 성능 향상의 80%를 차지한다는 연구 결과
|
264 |
+
- 앙상블 기법과 전이학습이 주요 성능 개선 방법으로 입증됨
|
265 |
+
- 벤치마크: ImageNet에서 95% 이상의 정확도 달성 사례
|
266 |
+
|
267 |
+
**3. Model Efficiency Techniques**
|
268 |
+
- 모델 경량화(Pruning, Quantization)로 추론 속도 10배 향상 가능
|
269 |
+
- Knowledge Distillation으로 모델 크기 90% 감소, 성능 유지
|
270 |
+
- 최신 트렌드: Efficient Transformers, Neural Architecture Search
|
271 |
+
|
272 |
+
**4. 실제 적용 사례**
|
273 |
+
- Netflix: 추천 시스템 개선으로 사용자 만족도 35% 향상
|
274 |
+
- Tesla: 실시간 객체 인식 속도 50% 개선
|
275 |
+
- OpenAI: GPT 모델 효율성 개선으로 비용 70% 절감""",
|
276 |
+
|
277 |
+
"supervisor_execution": """조사 내용을 바탕으로 실행자 AI에게 다음과 같이 구체적으로 지시합니다.
|
278 |
+
|
279 |
+
**1단계: 현재 모델 진단 (1주차)**
|
280 |
+
- 조사된 벤치마크 기준으로 현재 모델 성능 평가
|
281 |
+
- Netflix 사례를 참고하여 주요 병목 지점 식별
|
282 |
+
- AutoML 도구를 활용한 초기 최적화 가능성 탐색
|
283 |
+
|
284 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
285 |
+
- 조사 결과의 "80% 규칙"에 따라 데이터 정제 우선 실행
|
286 |
+
- 데이터 증강 기법 적용 (조사된 최신 기법 활용)
|
287 |
+
- A/B 테스트로 개선 효과 측정
|
288 |
+
|
289 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
290 |
+
- Knowledge Distillation 적용하여 모델 경량화
|
291 |
+
- 조사된 Pruning 기법으로 추론 속도 개선
|
292 |
+
- Tesla 사례의 실시간 처리 최적화 기법 벤치마킹
|
293 |
+
|
294 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
295 |
+
- OpenAI 사례의 비용 절감 지표 적용
|
296 |
+
- 조사된 성능 지표로 개선율 측정
|
297 |
+
- 단계적 배포 전략 수립""",
|
298 |
+
|
299 |
+
"executor": """감독자의 지시와 조사 내용을 기반으로 구체적인 실행 계획을 수립합니다.
|
300 |
+
|
301 |
+
**1단계: 현재 모델 진단 (1주차)**
|
302 |
+
- 월요일-화요일: MLflow를 사용한 현재 모델 메트릭 수집
|
303 |
+
* 조사 결과 참고: Netflix가 사용한 핵심 지표 (정확도, 지연시간, 처리량)
|
304 |
+
- 수요일-목요일: AutoML 도구 (Optuna, Ray Tune) 설정 및 초기 실행
|
305 |
+
* 조사된 best practice에 따라 search space 정의
|
306 |
+
- 금요일: 진단 보고서 작성 및 개선 우선순위 결정
|
307 |
+
|
308 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
309 |
+
- 데이터 정제 파이프라인 구축
|
310 |
+
* 조사 결과의 "80% 규칙" 적용: 누락값, 이상치, 레이블 오류 처리
|
311 |
+
* 코드 예시: `data_quality_pipeline.py` 구현
|
312 |
+
- 데이터 증강 구현
|
313 |
+
* 최신 기법 적용: MixUp, CutMix, AutoAugment
|
314 |
+
* 검증 데이터셋으로 효과 측정 (목표: 15% 성능 향상)
|
315 |
+
|
316 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
317 |
+
- Knowledge Distillation 구현
|
318 |
+
* Teacher 모델: 현재 대규모 모델
|
319 |
+
* Student 모델: 90% 작은 크기 목표 (조사 결과 기반)
|
320 |
+
* 구현 프레임워크: PyTorch/TensorFlow
|
321 |
+
- Pruning 및 Quantization 적용
|
322 |
+
* 구조적 pruning으로 50% 파라미터 제거
|
323 |
+
* INT8 quantization으로 추가 4배 속도 향상
|
324 |
+
* Tesla 사례 참고: TensorRT 최적화 적용
|
325 |
+
|
326 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
327 |
+
- 성과 지표 측정
|
328 |
+
* 추론 속도: 목표 10배 향상 (조사 결과 기반)
|
329 |
+
* 정확도 손실: 최대 2% 이내 유지
|
330 |
+
* 비용 절감: 70% 목표 (OpenAI 사례 참고)
|
331 |
+
- 배포 전략
|
332 |
+
* A/B 테스트: 10% 트래픽으로 시작
|
333 |
+
* 모니터링: Prometheus + Grafana 대시보드
|
334 |
+
* 롤백 계획: 성능 저하 시 자동 롤백
|
335 |
+
|
336 |
+
**예상 결과물**
|
337 |
+
- 최적화된 모델 (크기 90% 감소, 속도 10배 향상)
|
338 |
+
- 상세 성능 벤치마크 보고서
|
339 |
+
- 프로덕션 배포 가이드 및 모니터링 대시보드
|
340 |
+
- 재현 가능한 최적화 파이프라인 코드""",
|
341 |
+
|
342 |
+
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 잘 반영되었습니다. 다음과 같은 개선사항을 제안합니다.
|
343 |
+
|
344 |
+
**강점**
|
345 |
+
- 조사된 사례들(Netflix, Tesla, OpenAI)이 각 단계에 적절히 활용됨
|
346 |
+
- 구체적인 도구와 기법이 명시되어 실행 가능성이 높음
|
347 |
+
- 측정 가능한 목표가 조사 결과를 기반으로 설정됨
|
348 |
+
|
349 |
+
**개선 필요사항**
|
350 |
+
1. **리스크 관리 강화**
|
351 |
+
- 각 단계별 실패 시나리오와 대응 방안 추가 필요
|
352 |
+
- 기술적 문제 발생 시 백업 계획 수립
|
353 |
+
|
354 |
+
2. **비용 분석 구체화**
|
355 |
+
- OpenAI 사례의 70% 절감을 위한 구체적인 비용 계산
|
356 |
+
- ROI 분석 및 투자 대비 효과 측정 방법
|
357 |
+
|
358 |
+
3. **팀 협업 체계화**
|
359 |
+
- 데이터 과학자, ML 엔지니어, DevOps 간 역할 분담 명확화
|
360 |
+
- 주간 진행 상황 공유 및 이슈 트래킹 프로세스
|
361 |
+
|
362 |
+
**추가 권장사항**
|
363 |
+
- 최신 연구 동향 모니터링 체계 구축
|
364 |
+
- 경쟁사 벤치마킹을 위한 정기적인 조사 프로세스
|
365 |
+
- 내부 지식 공유를 위한 문서화 및 세미나 계획
|
366 |
+
- 실패 사례에서 배운 교훈을 축적하는 시스템 구축""",
|
367 |
+
|
368 |
+
"executor_final": """감독자 AI의 피드백을 완전히 반영하여 최종 실행 보고서를 작성합니다.
|
369 |
+
|
370 |
+
# 🎯 기계학습 모델 성능 향상 최종 실행 보고서
|
371 |
+
|
372 |
+
## 📋 Executive Summary
|
373 |
+
본 보고서는 웹 검색을 통해 수집된 최신 사례와 감독자 AI의 전략적 지침을 바탕으로, 8주간의 체계적인 모델 최적화 프로젝트를 제시합니다. 목표는 모델 크기 90% 감소, 추론 속도 10배 향상, 운영 비용 70% 절감입니다.
|
374 |
+
|
375 |
+
## 📊 1단계: 현재 모델 진단 및 베이스라인 설정 (1주차)
|
376 |
+
|
377 |
+
### 실행 계획
|
378 |
+
**월-화요일: 성능 메트릭 수집**
|
379 |
+
- MLflow를 통한 현재 모델 전체 분석
|
380 |
+
- Netflix 사례 기반 핵심 지표: 정확도(92%), 지연시간(45ms), 처리량(1,000 req/s)
|
381 |
+
- 리소스 사용량: GPU 메모리 8GB, 추론 시 CPU 사용률 85%
|
382 |
+
|
383 |
+
**수-목요일: AutoML 초기 탐색**
|
384 |
+
- Optuna로 하이퍼파라미터 최적화 (200회 시도)
|
385 |
+
- Ray Tune으로 분산 학습 환경 구축
|
386 |
+
- 초기 개선 가능성: 15-20% 성능 향상 예상
|
387 |
+
|
388 |
+
**금요일: 진단 보고서 및 리스크 분석**
|
389 |
+
- 주요 병목: 모델 크기(2.5GB), 배치 처리 비효율성
|
390 |
+
- 리스크: 데이터 드리프트, 하드웨어 제약
|
391 |
+
- 백업 계획: 클라우드 GPU 인스턴스 확보
|
392 |
+
|
393 |
+
### 예상 산출물
|
394 |
+
- 상세 성능 베이스라인 문서
|
395 |
+
- 개선 기회 우선순위 매트릭스
|
396 |
+
- 리스크 레지스터 및 대응 계획
|
397 |
+
|
398 |
+
## 📊 2단계: 데이터 품질 개선 (2-3주차)
|
399 |
+
|
400 |
+
### 실행 계획
|
401 |
+
**2주차: 데이터 정제 파이프라인**
|
402 |
+
```python
|
403 |
+
# data_quality_pipeline.py 주요 구성
|
404 |
+
class DataQualityPipeline:
|
405 |
+
def __init__(self):
|
406 |
+
self.validators = [
|
407 |
+
MissingValueHandler(threshold=0.05),
|
408 |
+
OutlierDetector(method='isolation_forest'),
|
409 |
+
LabelConsistencyChecker(),
|
410 |
+
DataDriftMonitor()
|
411 |
+
]
|
412 |
+
|
413 |
+
def process(self, data):
|
414 |
+
# 80% 규칙 적용: 데이터 품질이 성능의 80% 결정
|
415 |
+
for validator in self.validators:
|
416 |
+
data = validator.transform(data)
|
417 |
+
self.log_metrics(validator.get_stats())
|
418 |
+
return data
|
419 |
+
```
|
420 |
+
|
421 |
+
**3주차: 고급 데이터 증강**
|
422 |
+
- MixUp: 15% 정확도 향상 예상
|
423 |
+
- CutMix: 경계 검출 성능 20% 개선
|
424 |
+
- AutoAugment: 자동 최적 증강 정책 탐색
|
425 |
+
- A/B 테스트: 각 기법별 효과 측정
|
426 |
+
|
427 |
+
### 리스크 대응
|
428 |
+
- 데이터 품질 저하 시: 롤백 메커니즘 구현
|
429 |
+
- 증강 과적합 방지: 검증셋 분리 및 교차 검증
|
430 |
+
|
431 |
+
### 예상 산출물
|
432 |
+
- 자동화된 데이터 품질 파이프라인
|
433 |
+
- 데이터 품질 대시보드 (Grafana)
|
434 |
+
- 15% 이상 성능 향상 검증 보고서
|
435 |
+
|
436 |
+
## 📊 3단계: 모델 최적화 구현 (4-6주차)
|
437 |
+
|
438 |
+
### 실행 계획
|
439 |
+
**4-5주차: Knowledge Distillation**
|
440 |
+
- Teacher 모델: 현재 2.5GB 모델
|
441 |
+
- Student 모델 아키텍처:
|
442 |
+
* 파라미터 수: 250M → 25M (90% 감소)
|
443 |
+
* 레이어 수: 24 → 6
|
444 |
+
* Hidden dimension: 1024 → 256
|
445 |
+
- 훈련 전략:
|
446 |
+
* Temperature: 5.0
|
447 |
+
* Alpha (KD loss weight): 0.7
|
448 |
+
* 훈련 에폭: 50
|
449 |
+
|
450 |
+
**6주차: Pruning & Quantization**
|
451 |
+
- 구조적 Pruning:
|
452 |
+
* Magnitude 기반 50% 채널 제거
|
453 |
+
* Fine-tuning: 10 에폭
|
454 |
+
- INT8 Quantization:
|
455 |
+
* Post-training quantization
|
456 |
+
* Calibration dataset: 1,000 샘플
|
457 |
+
- TensorRT 최적화 (Tesla 사례 적용):
|
458 |
+
* FP16 추론 활성화
|
459 |
+
* 동적 배치 최적화
|
460 |
+
|
461 |
+
### 팀 협업 체계
|
462 |
+
- ML 엔지니어: 모델 아키텍처 및 훈련
|
463 |
+
- DevOps: 인프라 및 배포 파이프라인
|
464 |
+
- 데이터 과학자: 성능 분석 및 검증
|
465 |
+
- 주간 스탠드업 미팅 및 Jira 이슈 트래킹
|
466 |
+
|
467 |
+
### 예상 산출물
|
468 |
+
- 최적화된 모델 체크포인트
|
469 |
+
- 성능 벤치마크 상세 보고서
|
470 |
+
- 모델 변환 자동화 스크립트
|
471 |
+
|
472 |
+
## 📊 4단계: 성과 검증 및 프로덕션 배포 (7-8주차)
|
473 |
+
|
474 |
+
### 실행 계획
|
475 |
+
**7주차: 종합 성능 검증**
|
476 |
+
- 성능 지표 달성도:
|
477 |
+
* 추론 속도: 45ms → 4.5ms (10배 향상) ✓
|
478 |
+
* 모델 크기: 2.5GB → 250MB (90% 감소) ✓
|
479 |
+
* 정확도 손실: 92% → 90.5% (1.5% 손실) ✓
|
480 |
+
- 비용 분석:
|
481 |
+
* GPU 인스턴스: $2,000/월 → $600/월
|
482 |
+
* 처리량 증가로 인한 서버 수 감소: 10대 → 3대
|
483 |
+
* 총 비용 절감: 70% 달성 ✓
|
484 |
+
|
485 |
+
**8주차: 단계적 배포**
|
486 |
+
- Canary 배포:
|
487 |
+
* 1일차: 1% 트래픽
|
488 |
+
* 3일차: 10% 트래픽
|
489 |
+
* 7일차: 50% 트래픽
|
490 |
+
* 14일차: 100% 전환
|
491 |
+
- 모니터링 설정:
|
492 |
+
* Prometheus + Grafana 대시보드
|
493 |
+
* 알림 임계값: 지연시간 >10ms, 오류율 >0.1%
|
494 |
+
- 롤백 계획:
|
495 |
+
* 자동 롤백 트리거 설정
|
496 |
+
* Blue-Green 배포로 즉시 전환 가능
|
497 |
+
|
498 |
+
### ROI 분석
|
499 |
+
- 초기 투자: $50,000 (인건비 + 인프라)
|
500 |
+
- 월간 절감액: $14,000
|
501 |
+
- 투자 회수 기간: 3.6개월
|
502 |
+
- 1년 순이익: $118,000
|
503 |
+
|
504 |
+
### 예상 산출물
|
505 |
+
- 프로덕션 배포 완료
|
506 |
+
- 실시간 모니터링 대시보드
|
507 |
+
- ROI 분석 보고서
|
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 |
+
본 프로젝트는 최신 연구 결과와 업계 베스트 프랙티스를 적용하여, 8주 만에 모델 성능을 획기적으로 개선하고 운영 비용을 70% 절감하는 성과를 달성할 것으로 예상됩니다. 체계적인 접근과 리스크 관리, 그리고 지속적인 개선 계획을 통해 장기적인 경쟁력을 확보할 수 있습니다.
|
529 |
+
|
530 |
+
---
|
531 |
+
*작성일: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
|
532 |
+
*작성자: 협력적 AI 시스템 (감독자, 조사자, 실행자 AI)*"""
|
533 |
+
}
|
534 |
+
|
535 |
+
# 프롬프트 내용에 따라 적절한 응답 선택
|
536 |
+
if role == "supervisor" and "조사자 AI가 정리한" in messages[0]["content"]:
|
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["researcher"]
|
544 |
+
elif role == "executor" and "최종 보고서" in messages[0]["content"]:
|
545 |
+
response = test_responses["executor_final"]
|
546 |
+
else:
|
547 |
+
response = test_responses["executor"]
|
548 |
+
|
549 |
+
yield from self.simulate_streaming(response, role)
|
550 |
+
return
|
551 |
+
|
552 |
+
# 실제 API 호출
|
553 |
+
try:
|
554 |
+
system_prompts = {
|
555 |
+
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
556 |
+
"researcher": "당신은 정보를 조사하고 체계적으로 정리하는 조사자 AI입니다.",
|
557 |
+
"executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다."
|
558 |
+
}
|
559 |
+
|
560 |
+
full_messages = [
|
561 |
+
{"role": "system", "content": system_prompts.get(role, "")},
|
562 |
+
*messages
|
563 |
+
]
|
564 |
+
|
565 |
+
payload = {
|
566 |
+
"model": self.model_id,
|
567 |
+
"messages": full_messages,
|
568 |
+
"max_tokens": 2048,
|
569 |
+
"temperature": 0.7,
|
570 |
+
"top_p": 0.8,
|
571 |
+
"stream": True,
|
572 |
+
"stream_options": {"include_usage": True}
|
573 |
+
}
|
574 |
+
|
575 |
+
logger.info(f"API 스트리밍 호출 시작 - Role: {role}")
|
576 |
+
|
577 |
+
response = requests.post(
|
578 |
+
self.api_url,
|
579 |
+
headers=self.create_headers(),
|
580 |
+
json=payload,
|
581 |
+
stream=True,
|
582 |
+
timeout=10
|
583 |
+
)
|
584 |
+
|
585 |
+
if response.status_code != 200:
|
586 |
+
logger.error(f"API 오류: {response.status_code}")
|
587 |
+
yield f"❌ API 오류 ({response.status_code}): {response.text[:200]}"
|
588 |
+
return
|
589 |
+
|
590 |
+
for line in response.iter_lines():
|
591 |
+
if line:
|
592 |
+
line = line.decode('utf-8')
|
593 |
+
if line.startswith("data: "):
|
594 |
+
data = line[6:]
|
595 |
+
if data == "[DONE]":
|
596 |
+
break
|
597 |
+
try:
|
598 |
+
chunk = json.loads(data)
|
599 |
+
if "choices" in chunk and chunk["choices"]:
|
600 |
+
content = chunk["choices"][0].get("delta", {}).get("content", "")
|
601 |
+
if content:
|
602 |
+
yield content
|
603 |
+
except json.JSONDecodeError:
|
604 |
+
continue
|
605 |
+
|
606 |
+
except requests.exceptions.Timeout:
|
607 |
+
yield "⏱️ API 호출 시간이 초과되었습니다. 다시 시도해주세요."
|
608 |
+
except requests.exceptions.ConnectionError:
|
609 |
+
yield "🔌 API 서버에 연결할 수 없습니다. 인터넷 연결을 확인해주세요."
|
610 |
+
except Exception as e:
|
611 |
+
logger.error(f"스트리밍 중 오류: {str(e)}")
|
612 |
+
yield f"❌ 오류 발생: {str(e)}"
|
613 |
+
|
614 |
+
# 시스템 인스턴스 생성
|
615 |
+
llm_system = LLMCollaborativeSystem()
|
616 |
+
|
617 |
+
def process_query_streaming(user_query: str, history: List):
|
618 |
+
"""스트리밍을 지원하는 쿼리 처리"""
|
619 |
+
if not user_query:
|
620 |
+
return history, "", "", "", "", "❌ 질문을 입력해주세요."
|
621 |
+
|
622 |
+
conversation_log = []
|
623 |
+
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
624 |
+
|
625 |
+
try:
|
626 |
+
# 1단계: 감독자 AI 초기 분석 및 키워드 추출
|
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 history, supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
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 history, supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
648 |
+
|
649 |
+
search_results = {}
|
650 |
+
for keyword in keywords:
|
651 |
+
results = llm_system.brave_search(keyword)
|
652 |
+
if results:
|
653 |
+
search_results[keyword] = results
|
654 |
+
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
655 |
+
yield history, supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
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 = "[조사 결과 정리] 🔄 생성 중...\n"
|
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"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
668 |
+
yield history, supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
669 |
+
|
670 |
+
all_responses["researcher"].append(researcher_response)
|
671 |
+
|
672 |
+
# 4단계: 감독자 AI가 조사 내용 기반으로 실행 지시
|
673 |
+
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, researcher_response)
|
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 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
|
683 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
684 |
+
yield history, supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 지시 중..."
|
685 |
+
|
686 |
+
all_responses["supervisor"].append(supervisor_execution_response)
|
687 |
+
|
688 |
+
# 5단계: 실행자 AI가 조사 내용과 지시를 기반으로 초기 구현
|
689 |
+
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, researcher_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 history, supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
700 |
+
|
701 |
+
all_responses["executor"].append(executor_response)
|
702 |
+
|
703 |
+
# 6단계: 감독자 AI 검토 및 피드백
|
704 |
+
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
705 |
+
|
706 |
+
사용자 질문: {user_query}
|
707 |
+
|
708 |
+
실행자 AI의 답변:
|
709 |
+
{executor_response}
|
710 |
+
|
711 |
+
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요. 구체적이고 실행 가능한 개선 방안을 제시하세요."""
|
712 |
+
|
713 |
+
review_response = ""
|
714 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[검토 및 피드백] 🔄 생성 중...\n"
|
715 |
+
|
716 |
+
for chunk in llm_system.call_llm_streaming(
|
717 |
+
[{"role": "user", "content": review_prompt}],
|
718 |
+
"supervisor"
|
719 |
+
):
|
720 |
+
review_response += chunk
|
721 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[검토 및 피드백] - {datetime.now().strftime('%H:%M:%S')}\n{review_response}"
|
722 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
723 |
+
yield history, supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
724 |
+
|
725 |
+
all_responses["supervisor"].append(review_response)
|
726 |
+
|
727 |
+
# 7단계: 실행자 AI 최종 보고서 (피드백 반영)
|
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 |
+
temp_text = f"[초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['executor'][0]}\n\n---\n\n[최종 보고서] - {datetime.now().strftime('%H:%M:%S')}\n{final_executor_response}"
|
743 |
+
executor_text = temp_text
|
744 |
+
yield history, supervisor_text, researcher_text, executor_text, "", "📄 최종 보고서 작성 중..."
|
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 |
+
---
|
758 |
+
|
759 |
+
<details>
|
760 |
+
<summary>📋 전체 협력 과정 보기</summary>
|
761 |
+
|
762 |
+
#### 🔍 거시적 분석 (감독자 AI)
|
763 |
+
{all_responses['supervisor'][0]}
|
764 |
+
|
765 |
+
#### 📚 조사 결과 (조사자 AI)
|
766 |
+
{researcher_response}
|
767 |
+
|
768 |
+
#### 🎯 실행 지시 (감독자 AI)
|
769 |
+
{all_responses['supervisor'][1]}
|
770 |
+
|
771 |
+
#### 💡 초기 구현 (실행자 AI)
|
772 |
+
{executor_response}
|
773 |
+
|
774 |
+
#### ✨ 검토 및 개선사항 (감독자 AI)
|
775 |
+
{review_response}
|
776 |
+
|
777 |
+
</details>
|
778 |
+
|
779 |
+
---
|
780 |
+
*이 보고서는 웹 검색을 통한 최신 정보와 AI들의 협력, 그리고 피드백 반영을 통해 작성되었습니다.*"""
|
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 history, "", "", "", error_msg, error_msg
|
790 |
+
|
791 |
+
def clear_all():
|
792 |
+
"""모든 내용 초기화"""
|
793 |
+
return [], "", "", "", "", "🔄 초기화되었습니다."
|
794 |
+
|
795 |
+
# Gradio 인터페이스
|
796 |
+
css = """
|
797 |
+
.gradio-container {
|
798 |
+
font-family: 'Arial', sans-serif;
|
799 |
+
}
|
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 |
+
**7단계 협력 프로세��:**
|
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=3
|
850 |
+
)
|
851 |
+
|
852 |
+
with gr.Row():
|
853 |
+
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2)
|
854 |
+
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
855 |
+
|
856 |
+
status_text = gr.Textbox(
|
857 |
+
label="상태",
|
858 |
+
interactive=False,
|
859 |
+
value="대기 중...",
|
860 |
+
max_lines=1
|
861 |
+
)
|
862 |
+
|
863 |
+
# 오른쪽: AI 출력
|
864 |
+
with gr.Column(scale=2):
|
865 |
+
# 최종 결과
|
866 |
+
with gr.Accordion("📊 최종 종합 결과", open=True):
|
867 |
+
final_output = gr.Markdown(
|
868 |
+
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
869 |
+
)
|
870 |
+
|
871 |
+
# AI 출력들
|
872 |
+
with gr.Row():
|
873 |
+
# 감독자 AI 출력
|
874 |
+
with gr.Column():
|
875 |
+
gr.Markdown("### 🧠 감독자 AI (거시적 분석)")
|
876 |
+
supervisor_output = gr.Textbox(
|
877 |
+
label="",
|
878 |
+
lines=12,
|
879 |
+
max_lines=15,
|
880 |
+
interactive=False,
|
881 |
+
elem_classes=["supervisor-box"]
|
882 |
+
)
|
883 |
+
|
884 |
+
with gr.Row():
|
885 |
+
# 조사자 AI 출력
|
886 |
+
with gr.Column():
|
887 |
+
gr.Markdown("### 🔍 조사자 AI (웹 검색 & 정리)")
|
888 |
+
researcher_output = gr.Textbox(
|
889 |
+
label="",
|
890 |
+
lines=12,
|
891 |
+
max_lines=15,
|
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(
|
909 |
+
examples=[
|
910 |
+
"기계학습 모델의 성능을 향상시키는 최신 방법은?",
|
911 |
+
"2024년 효과적인 프로젝트 관리 도구와 전략은?",
|
912 |
+
"지속 가능한 비즈니스 모델의 최신 트렌드는?",
|
913 |
+
"최신 데이터 시각화 도구와 기법은?",
|
914 |
+
"원격 팀의 생산성을 높이는 검증된 방법은?"
|
915 |
+
],
|
916 |
+
inputs=user_input,
|
917 |
+
label="💡 예제 질문"
|
918 |
+
)
|
919 |
+
|
920 |
+
# 이벤트 핸들러
|
921 |
+
submit_btn.click(
|
922 |
+
fn=process_query_streaming,
|
923 |
+
inputs=[user_input, chatbot],
|
924 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
925 |
+
).then(
|
926 |
+
fn=lambda: "",
|
927 |
+
outputs=[user_input]
|
928 |
+
)
|
929 |
+
|
930 |
+
user_input.submit(
|
931 |
+
fn=process_query_streaming,
|
932 |
+
inputs=[user_input, chatbot],
|
933 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
934 |
+
).then(
|
935 |
+
fn=lambda: "",
|
936 |
+
outputs=[user_input]
|
937 |
+
)
|
938 |
+
|
939 |
+
clear_btn.click(
|
940 |
+
fn=clear_all,
|
941 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
942 |
+
)
|
943 |
+
|
944 |
+
gr.Markdown(
|
945 |
+
"""
|
946 |
+
---
|
947 |
+
### 📝 사용 방법
|
948 |
+
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
949 |
+
2. 7단계 협력 프로세스가 진행됩니다:
|
950 |
+
- 감독자 초기 분석 → 웹 검색 → 조사 정리 → 실행 지시 → 초기 구현 → 피드백 → 최종 보고서
|
951 |
+
3. 각 AI의 작업 과정을 실시간으로 확인할 수 있습니다.
|
952 |
+
4. 최종 보고서가 상단에 표시되며, 전체 협력 과정은 접을 수 있는 형태로 제공됩니다.
|
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 |
+
|
970 |
+
if __name__ == "__main__":
|
971 |
+
app.queue() # 스트리밍을 위한 큐 활성화
|
972 |
+
app.launch(
|
973 |
+
server_name="0.0.0.0",
|
974 |
+
server_port=7860,
|
975 |
+
share=True,
|
976 |
+
show_error=True
|
977 |
+
)import gradio as gr
|
978 |
+
import os
|
979 |
+
import json
|
980 |
+
import requests
|
981 |
+
from datetime import datetime
|
982 |
+
import time
|
983 |
+
from typing import List, Dict, Any, Generator, Tuple
|
984 |
+
import logging
|
985 |
+
import re
|
986 |
+
|
987 |
+
# 로깅 설정
|
988 |
+
logging.basicConfig(level=logging.INFO)
|
989 |
+
logger = logging.getLogger(__name__)
|
990 |
+
|
991 |
+
# 환경 변수에서 토큰 가져오기
|
992 |
+
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
|
993 |
+
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN")
|
994 |
+
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
995 |
+
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
|
996 |
+
MODEL_ID = "dep89a2fld32mcm"
|
997 |
+
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
998 |
+
|
999 |
+
# 전역 변수
|
1000 |
+
conversation_history = []
|
1001 |
+
|
1002 |
+
class LLMCollaborativeSystem:
|
1003 |
+
def __init__(self):
|
1004 |
+
self.token = FRIENDLI_TOKEN
|
1005 |
+
self.bapi_token = BAPI_TOKEN
|
1006 |
+
self.api_url = API_URL
|
1007 |
+
self.brave_url = BRAVE_SEARCH_URL
|
1008 |
+
self.model_id = MODEL_ID
|
1009 |
+
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
|
1010 |
+
|
1011 |
+
if self.test_mode:
|
1012 |
+
logger.warning("테스트 모드로 실행됩니다.")
|
1013 |
+
if self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
1014 |
+
logger.warning("Brave API 토큰이 설정되지 않았습니다.")
|
1015 |
+
|
1016 |
+
def create_headers(self):
|
1017 |
+
"""API 헤더 생성"""
|
1018 |
+
return {
|
1019 |
+
"Authorization": f"Bearer {self.token}",
|
1020 |
+
"Content-Type": "application/json"
|
1021 |
+
}
|
1022 |
+
|
1023 |
+
def create_brave_headers(self):
|
1024 |
+
"""Brave API 헤더 생성"""
|
1025 |
+
return {
|
1026 |
+
"Accept": "application/json",
|
1027 |
+
"Accept-Encoding": "gzip",
|
1028 |
+
"X-Subscription-Token": self.bapi_token
|
1029 |
+
}
|
1030 |
+
|
1031 |
+
def create_supervisor_initial_prompt(self, user_query: str) -> str:
|
1032 |
+
"""감독자 AI 초기 프롬프트 생성"""
|
1033 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
1034 |
+
|
1035 |
+
사용자 질문: {user_query}
|
1036 |
+
|
1037 |
+
이 질문에 대해:
|
1038 |
+
1. 전체적인 접근 방향과 프레임워크를 제시하세요
|
1039 |
+
2. 핵심 요소와 고려사항을 구조화하여 설명하세요
|
1040 |
+
3. 이 주제에 대해 조사가 필요한 5-7개의 구체적인 키워드나 검색어를 제시하세요
|
1041 |
+
|
1042 |
+
키워드는 다음 형식으로 제시하세요:
|
1043 |
+
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
|
1044 |
+
|
1045 |
+
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
1046 |
+
"""조사자 AI 프롬프트 생성"""
|
1047 |
+
search_summary = ""
|
1048 |
+
for keyword, results in search_results.items():
|
1049 |
+
search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n"
|
1050 |
+
for i, result in enumerate(results[:3], 1):
|
1051 |
+
search_summary += f"{i}. {result.get('title', 'N/A')}\n"
|
1052 |
+
search_summary += f" - {result.get('description', 'N/A')}\n"
|
1053 |
+
search_summary += f" - 출처: {result.get('url', 'N/A')}\n"
|
1054 |
+
|
1055 |
+
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.
|
1056 |
+
|
1057 |
+
사용자 질문: {user_query}
|
1058 |
+
|
1059 |
+
감독자 AI의 지침:
|
1060 |
+
{supervisor_guidance}
|
1061 |
+
|
1062 |
+
브레이브 검색 결과:
|
1063 |
+
{search_summary}
|
1064 |
+
|
1065 |
+
위 검색 결과를 바탕으로:
|
1066 |
+
1. 각 키워드별로 중요한 정보를 정리하세요
|
1067 |
+
2. 신뢰할 수 있는 출처를 명시하세요
|
1068 |
+
3. 실행자 AI가 활용할 수 있는 구체적인 데이터와 사실을 추출하세요
|
1069 |
+
4. 최신 트렌드나 중요한 통계가 있다면 강조하세요"""
|
1070 |
+
|
1071 |
+
def create_supervisor_execution_prompt(self, user_query: str, research_summary: str) -> str:
|
1072 |
+
"""감독자 AI의 실행 지시 프롬프트"""
|
1073 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
1074 |
+
|
1075 |
+
사용자 질문: {user_query}
|
1076 |
+
|
1077 |
+
조사자 AI가 정리한 조사 내용:
|
1078 |
+
{research_summary}
|
1079 |
+
|
1080 |
+
위 조사 내용을 기반으로 실행자 AI에게 아주 구체적인 지시를 내려주세요:
|
1081 |
+
1. 조사된 정보를 어떻게 활용할지 명확히 지시하세요
|
1082 |
+
2. 실행 가능한 단계별 작업을 구체적으로 제시하세요
|
1083 |
+
3. 각 단계에서 참고해야 할 조사 내용을 명시하세요
|
1084 |
+
4. 예상되는 결과물의 형태를 구체적으로 설명하세요"""
|
1085 |
+
|
1086 |
+
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, research_summary: str) -> str:
|
1087 |
+
"""실행자 AI 프롬프트 생성"""
|
1088 |
+
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
1089 |
+
|
1090 |
+
사용자 질문: {user_query}
|
1091 |
+
|
1092 |
+
조사자 AI가 정리한 조사 내용:
|
1093 |
+
{research_summary}
|
1094 |
+
|
1095 |
+
감독자 AI의 구체적인 지시:
|
1096 |
+
{supervisor_guidance}
|
1097 |
+
|
1098 |
+
위 조사 내용과 지시사항을 바탕으로:
|
1099 |
+
1. 조사된 정보를 적극 활용하여 구체적인 실행 계획을 작성하세요
|
1100 |
+
2. 각 단계별로 참고한 조사 내용을 명시하세요
|
1101 |
+
3. 실제로 적용 가능한 구체적인 방법론을 제시하세요
|
1102 |
+
4. 예상되는 성과와 측정 방법을 포함하세요"""
|
1103 |
+
|
1104 |
+
def create_executor_final_prompt(self, user_query: str, initial_response: str, supervisor_feedback: str, research_summary: str) -> str:
|
1105 |
+
"""실행자 AI 최종 보고서 프롬프트"""
|
1106 |
+
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
1107 |
+
|
1108 |
+
사용자 질문: {user_query}
|
1109 |
+
|
1110 |
+
조사자 AI의 조사 내용:
|
1111 |
+
{research_summary}
|
1112 |
+
|
1113 |
+
당신의 초기 답변:
|
1114 |
+
{initial_response}
|
1115 |
+
|
1116 |
+
감독자 AI의 피드백 및 개선사항:
|
1117 |
+
{supervisor_feedback}
|
1118 |
+
|
1119 |
+
위 피드백을 완전히 반영하여 최종 보고서를 작성하세요:
|
1120 |
+
1. 감독자의 모든 개선사항을 반영하세요
|
1121 |
+
2. 조사 내용을 더욱 구체적으로 활용하세요
|
1122 |
+
3. 실행 가능성을 높이는 세부 계획을 포함하세요
|
1123 |
+
4. 명확한 결론과 다음 단계를 제시하세요
|
1124 |
+
5. 전문적이고 완성도 높은 최종 보고서 형식으로 작성하세요"""
|
1125 |
+
|
1126 |
def extract_keywords(self, supervisor_response: str) -> List[str]:
|
1127 |
"""감독자 응답에서 키워드 추출"""
|
1128 |
keywords = []
|
|
|
1315 |
- 프로덕션 배포 가이드 및 모니터링 대시보드
|
1316 |
- 재현 가능한 최적화 파이프라인 코드""",
|
1317 |
|
1318 |
+
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 잘 반영되었습니다. 다음과 같은 개선사항을 제안합니다.
|
1319 |
|
1320 |
**강점**
|
1321 |
- 조사된 사례들(Netflix, Tesla, OpenAI)이 각 단계에 적절히 활용됨
|
1322 |
- 구체적인 도구와 기법이 명시되어 실행 가능성이 높음
|
1323 |
- 측정 가능한 목표가 조사 결과를 기반으로 설정됨
|
1324 |
|
1325 |
+
**개선 필요사항**
|
1326 |
+
1. **리스크 관리 강화**
|
1327 |
+
- 각 단계별 실패 시나리오와 대응 방안 추가 필요
|
1328 |
+
- 기술적 문제 발생 시 백업 계획 수립
|
1329 |
+
|
1330 |
+
2. **비용 분석 구체화**
|
1331 |
+
- OpenAI 사례의 70% 절감을 위한 구체적인 비용 계산
|
1332 |
+
- ROI 분석 및 투자 대비 효과 측정 방법
|
1333 |
+
|
1334 |
+
3. **팀 협업 체계화**
|
1335 |
+
- 데이터 과학자, ML 엔지니어, DevOps 간 역할 분담 명확화
|
1336 |
+
- 주간 진행 상황 공유 및 이슈 트래킹 프로세스
|
1337 |
|
1338 |
**추가 권장사항**
|
1339 |
- 최신 연구 동향 모니터링 체계 구축
|
1340 |
- 경쟁사 벤치마킹을 위한 정기적인 조사 프로세스
|
1341 |
+
- 내부 지식 공유를 위한 문서화 및 세미나 계획
|
1342 |
+
- 실패 사례에서 배운 교훈을 축적하는 시스템 구축""",
|
1343 |
+
|
1344 |
+
"executor_final": """감독자 AI의 피드백을 완전히 반영하여 최종 실행 보고서를 작성합니다.
|
1345 |
+
|
1346 |
+
# 🎯 기계학습 모델 성능 향상 최종 실행 보고서
|
1347 |
+
|
1348 |
+
## 📋 Executive Summary
|
1349 |
+
본 보고서는 웹 검색을 통해 수집된 최신 사례와 감독자 AI의 전략적 지침을 바탕으로, 8주간의 체계적인 모델 최적화 프로젝트를 제시합니다. 목표는 모델 크기 90% 감소, 추론 속도 10배 향상, 운영 비용 70% 절감입니다.
|
1350 |
+
|
1351 |
+
## 📊 1단계: 현재 모델 진단 및 베이스라인 설정 (1주차)
|
1352 |
+
|
1353 |
+
### 실행 계획
|
1354 |
+
**월-화요일: 성능 메트릭 수집**
|
1355 |
+
- MLflow를 통한 현재 모델 전체 분석
|
1356 |
+
- Netflix 사례 기반 핵심 지표: 정확도(92%), 지연시간(45ms), 처리량(1,000 req/s)
|
1357 |
+
- 리소스 사용량: GPU 메모리 8GB, 추론 시 CPU 사용률 85%
|
1358 |
+
|
1359 |
+
**수-목요일: AutoML 초기 탐색**
|
1360 |
+
- Optuna로 하이퍼파라미터 최적화 (200회 시도)
|
1361 |
+
- Ray Tune으로 분산 학습 환경 구축
|
1362 |
+
- 초기 개선 가능성: 15-20% 성능 향상 예상
|
1363 |
+
|
1364 |
+
**금요일: 진단 보고서 및 리스크 분석**
|
1365 |
+
- 주요 병목: 모델 크기(2.5GB), 배치 처리 비효율성
|
1366 |
+
- 리스크: 데이터 드리프트, 하드웨어 제약
|
1367 |
+
- 백업 계획: 클라우드 GPU 인스턴스 확보
|
1368 |
+
|
1369 |
+
### 예상 산출물
|
1370 |
+
- 상세 성능 베이스라인 문서
|
1371 |
+
- 개선 기회 우선순위 매트릭스
|
1372 |
+
- 리스크 레지스터 및 대응 계획
|
1373 |
+
|
1374 |
+
## 📊 2단계: 데이터 품질 개선 (2-3주차)
|
1375 |
+
|
1376 |
+
### 실행 계획
|
1377 |
+
**2주차: 데이터 정제 파이프라인**
|
1378 |
+
```python
|
1379 |
+
# data_quality_pipeline.py 주요 구성
|
1380 |
+
class DataQualityPipeline:
|
1381 |
+
def __init__(self):
|
1382 |
+
self.validators = [
|
1383 |
+
MissingValueHandler(threshold=0.05),
|
1384 |
+
OutlierDetector(method='isolation_forest'),
|
1385 |
+
LabelConsistencyChecker(),
|
1386 |
+
DataDriftMonitor()
|
1387 |
+
]
|
1388 |
+
|
1389 |
+
def process(self, data):
|
1390 |
+
# 80% 규칙 적용: 데이터 품질이 성능의 80% 결정
|
1391 |
+
for validator in self.validators:
|
1392 |
+
data = validator.transform(data)
|
1393 |
+
self.log_metrics(validator.get_stats())
|
1394 |
+
return data
|
1395 |
+
```
|
1396 |
+
|
1397 |
+
**3주차: 고급 데이터 증강**
|
1398 |
+
- MixUp: 15% 정확도 향상 예상
|
1399 |
+
- CutMix: 경계 검출 성능 20% 개선
|
1400 |
+
- AutoAugment: 자동 최적 증강 정책 탐색
|
1401 |
+
- A/B 테스트: 각 기법별 효과 측정
|
1402 |
+
|
1403 |
+
### 리스크 대응
|
1404 |
+
- 데이터 품질 저하 시: 롤백 메커니즘 구현
|
1405 |
+
- 증강 과적합 방지: 검증셋 분리 및 교차 검증
|
1406 |
+
|
1407 |
+
### 예상 산출물
|
1408 |
+
- 자동화된 데이터 품질 파이프라인
|
1409 |
+
- 데이터 품질 대시보드 (Grafana)
|
1410 |
+
- 15% 이상 성능 향상 검증 보고서
|
1411 |
+
|
1412 |
+
## 📊 3단계: 모델 최적화 구현 (4-6주차)
|
1413 |
+
|
1414 |
+
### 실행 계획
|
1415 |
+
**4-5주차: Knowledge Distillation**
|
1416 |
+
- Teacher 모델: 현재 2.5GB 모델
|
1417 |
+
- Student 모델 아키텍처:
|
1418 |
+
* 파라미터 수: 250M → 25M (90% 감소)
|
1419 |
+
* 레이어 수: 24 → 6
|
1420 |
+
* Hidden dimension: 1024 → 256
|
1421 |
+
- 훈련 전략:
|
1422 |
+
* Temperature: 5.0
|
1423 |
+
* Alpha (KD loss weight): 0.7
|
1424 |
+
* 훈련 에폭: 50
|
1425 |
+
|
1426 |
+
**6주차: Pruning & Quantization**
|
1427 |
+
- 구조적 Pruning:
|
1428 |
+
* Magnitude 기반 50% 채널 제거
|
1429 |
+
* Fine-tuning: 10 에폭
|
1430 |
+
- INT8 Quantization:
|
1431 |
+
* Post-training quantization
|
1432 |
+
* Calibration dataset: 1,000 샘플
|
1433 |
+
- TensorRT 최적화 (Tesla 사례 적용):
|
1434 |
+
* FP16 추론 활성화
|
1435 |
+
* 동적 배치 최적화
|
1436 |
+
|
1437 |
+
### 팀 협업 체계
|
1438 |
+
- ML 엔지니어: 모델 아키텍처 및 훈련
|
1439 |
+
- DevOps: 인프라 및 배포 파이프라인
|
1440 |
+
- 데이터 과학자: 성능 분석 및 검증
|
1441 |
+
- 주간 스탠드업 미팅 및 Jira 이슈 트래킹
|
1442 |
+
|
1443 |
+
### 예상 산출물
|
1444 |
+
- 최적화된 모델 체크포인트
|
1445 |
+
- 성능 벤치마크 상세 보고서
|
1446 |
+
- 모델 변환 자동화 스크립트
|
1447 |
+
|
1448 |
+
## 📊 4단계: 성과 검증 및 프로덕션 배포 (7-8주차)
|
1449 |
+
|
1450 |
+
### 실행 계획
|
1451 |
+
**7주차: 종합 성능 검증**
|
1452 |
+
- 성능 지표 달성도:
|
1453 |
+
* 추론 속도: 45ms → 4.5ms (10배 향상) ✓
|
1454 |
+
* 모델 크기: 2.5GB → 250MB (90% 감소) ✓
|
1455 |
+
* 정확도 손실: 92% → 90.5% (1.5% 손실) ✓
|
1456 |
+
- 비용 분석:
|
1457 |
+
* GPU 인스턴스: $2,000/월 → $600/월
|
1458 |
+
* 처리량 증가로 인한 서버 수 감소: 10대 → 3대
|
1459 |
+
* 총 비용 절감: 70% 달성 ✓
|
1460 |
+
|
1461 |
+
**8주차: 단계적 배포**
|
1462 |
+
- Canary 배포:
|
1463 |
+
* 1일차: 1% 트래픽
|
1464 |
+
* 3일차: 10% 트래픽
|
1465 |
+
* 7일차: 50% 트래픽
|
1466 |
+
* 14일차: 100% 전환
|
1467 |
+
- 모니터링 설정:
|
1468 |
+
* Prometheus + Grafana 대시보드
|
1469 |
+
* 알림 임계값: 지연시간 >10ms, 오류율 >0.1%
|
1470 |
+
- 롤백 계획:
|
1471 |
+
* 자동 롤백 트리거 설정
|
1472 |
+
* Blue-Green 배포로 즉시 전환 가능
|
1473 |
+
|
1474 |
+
### ROI 분석
|
1475 |
+
- 초기 투자: $50,000 (인건비 + 인프라)
|
1476 |
+
- 월간 절감액: $14,000
|
1477 |
+
- 투자 회수 기간: 3.6개월
|
1478 |
+
- 1년 순이익: $118,000
|
1479 |
+
|
1480 |
+
### 예상 산출물
|
1481 |
+
- 프로덕션 배포 완료
|
1482 |
+
- 실시간 모니터링 대시보드
|
1483 |
+
- ROI 분석 보고서
|
1484 |
+
- 운영 가이드 문서
|
1485 |
+
|
1486 |
+
## 📈 지속적 개선 계획
|
1487 |
+
|
1488 |
+
### 모니터링 및 유지보수
|
1489 |
+
- 월간 성능 리뷰 미팅
|
1490 |
+
- 분기별 재훈련 계획
|
1491 |
+
- 신기술 도입 검토 (Sparse Models, MoE)
|
1492 |
+
|
1493 |
+
### 지식 공유
|
1494 |
+
- 내부 기술 세미나 (월 1회)
|
1495 |
+
- 외부 컨퍼런스 발표 준비
|
1496 |
+
- 오픈소스 기여 계획
|
1497 |
+
|
1498 |
+
### 차기 프로젝트
|
1499 |
+
- 엣지 디바이스 배포 최적화
|
1500 |
+
- 연합 학습(Federated Learning) 도입
|
1501 |
+
- AutoML 플랫폼 구축
|
1502 |
+
|
1503 |
+
## 📝 결론
|
1504 |
+
본 프로젝트는 최신 연구 결과와 업계 베스트 프랙티스를 적용하여, 8주 만에 모델 성능을 획기적으로 개선하고 운영 비용을 70% 절감하는 성과를 달성할 것으로 예상됩니다. 체계적인 접근과 리스크 관리, 그리고 지속적인 개선 계획을 통해 장기적인 경쟁력을 확보할 수 있습니다.
|
1505 |
+
|
1506 |
+
---
|
1507 |
+
*작성일: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
|
1508 |
+
*작성자: 협력적 AI 시스템 (감독자, 조사자, 실행자 AI)*"""
|
1509 |
}
|
1510 |
|
1511 |
+
# 프롬프트 내용에 따라 적절한 응답 선택
|
1512 |
if role == "supervisor" and "조사자 AI가 정리한" in messages[0]["content"]:
|
1513 |
response = test_responses["supervisor_execution"]
|
1514 |
elif role == "supervisor" and messages[0]["content"].find("실행자 AI의 답변") > -1:
|
|
|
1517 |
response = test_responses["supervisor_initial"]
|
1518 |
elif role == "researcher":
|
1519 |
response = test_responses["researcher"]
|
1520 |
+
elif role == "executor" and "최종 보고서" in messages[0]["content"]:
|
1521 |
+
response = test_responses["executor_final"]
|
1522 |
else:
|
1523 |
response = test_responses["executor"]
|
1524 |
|
|
|
1661 |
|
1662 |
all_responses["supervisor"].append(supervisor_execution_response)
|
1663 |
|
1664 |
+
# 5단계: 실행자 AI가 조사 내용과 지시를 기반으로 초기 구현
|
1665 |
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, researcher_response)
|
1666 |
executor_response = ""
|
1667 |
|
1668 |
+
executor_text = "[초기 구현] 🔄 생성 중...\n"
|
1669 |
for chunk in llm_system.call_llm_streaming(
|
1670 |
[{"role": "user", "content": executor_prompt}],
|
1671 |
"executor"
|
1672 |
):
|
1673 |
executor_response += chunk
|
1674 |
+
executor_text = f"[초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
1675 |
yield history, supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
1676 |
|
1677 |
all_responses["executor"].append(executor_response)
|
1678 |
|
1679 |
+
# 6단계: 감독자 AI 검토 및 피드백
|
|
|
1680 |
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
1681 |
|
1682 |
사용자 질문: {user_query}
|
|
|
1684 |
실행자 AI의 답변:
|
1685 |
{executor_response}
|
1686 |
|
1687 |
+
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요. 구체적이고 실행 가능한 개선 방안을 제시하세요."""
|
1688 |
|
1689 |
review_response = ""
|
1690 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[검토 및 피드백] 🔄 생성 중...\n"
|
1691 |
|
1692 |
for chunk in llm_system.call_llm_streaming(
|
1693 |
[{"role": "user", "content": review_prompt}],
|
1694 |
"supervisor"
|
1695 |
):
|
1696 |
review_response += chunk
|
1697 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[검토 및 피드백] - {datetime.now().strftime('%H:%M:%S')}\n{review_response}"
|
1698 |
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
1699 |
yield history, supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
1700 |
|
1701 |
+
all_responses["supervisor"].append(review_response)
|
1702 |
+
|
1703 |
+
# 7단계: 실행자 AI 최종 보고서 (피드백 반영)
|
1704 |
+
final_executor_prompt = llm_system.create_executor_final_prompt(
|
1705 |
+
user_query,
|
1706 |
+
executor_response,
|
1707 |
+
review_response,
|
1708 |
+
researcher_response
|
1709 |
+
)
|
1710 |
+
final_executor_response = ""
|
1711 |
+
|
1712 |
+
executor_text += "\n\n---\n\n[최종 보고서] 🔄 작성 중...\n"
|
1713 |
+
for chunk in llm_system.call_llm_streaming(
|
1714 |
+
[{"role": "user", "content": final_executor_prompt}],
|
1715 |
+
"executor"
|
1716 |
+
):
|
1717 |
+
final_executor_response += chunk
|
1718 |
+
temp_text = f"[초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['executor'][0]}\n\n---\n\n[최종 보고서] - {datetime.now().strftime('%H:%M:%S')}\n{final_executor_response}"
|
1719 |
+
executor_text = temp_text
|
1720 |
+
yield history, supervisor_text, researcher_text, executor_text, "", "📄 최종 보고서 작성 중..."
|
1721 |
+
|
1722 |
+
all_responses["executor"].append(final_executor_response)
|
1723 |
+
|
1724 |
+
# 최종 결과 생성 (최종 보고서를 메인으로)
|
1725 |
+
final_summary = f"""## 🎯 최종 종합 보고서
|
1726 |
|
1727 |
### 📌 사용자 질문
|
1728 |
{user_query}
|
1729 |
|
1730 |
+
### 📄 최종 보고서 (실행자 AI - 피드백 반영)
|
1731 |
+
{final_executor_response}
|
1732 |
+
|
1733 |
+
---
|
1734 |
+
|
1735 |
+
<details>
|
1736 |
+
<summary>📋 전체 협력 과정 보기</summary>
|
1737 |
+
|
1738 |
+
#### 🔍 거시적 분석 (감독자 AI)
|
1739 |
{all_responses['supervisor'][0]}
|
1740 |
|
1741 |
+
#### 📚 조사 결과 (조사자 AI)
|
1742 |
{researcher_response}
|
1743 |
|
1744 |
+
#### 🎯 실행 지시 (감독자 AI)
|
1745 |
{all_responses['supervisor'][1]}
|
1746 |
|
1747 |
+
#### 💡 초기 구현 (실행자 AI)
|
1748 |
{executor_response}
|
1749 |
|
1750 |
+
#### ✨ 검토 및 개선사항 (감독자 AI)
|
1751 |
{review_response}
|
1752 |
|
1753 |
+
</details>
|
1754 |
+
|
1755 |
---
|
1756 |
+
*이 보고서는 웹 검색을 통한 최신 정보와 AI들의 협력, 그리고 피드백 반영을 통해 작성되었습니다.*"""
|
1757 |
|
1758 |
# 히스토리 업데이트
|
1759 |
new_history = history + [(user_query, final_summary)]
|
1760 |
|
1761 |
+
yield new_history, supervisor_text, researcher_text, executor_text, final_summary, "✅ 최종 보고서 완성!"
|
1762 |
|
1763 |
except Exception as e:
|
1764 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
|
|
1790 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
1791 |
gr.Markdown(
|
1792 |
f"""
|
1793 |
+
# 🤝 협력적 LLM 시스템 (조사자 포함 + 피드백 반영)
|
1794 |
|
1795 |
+
> 감독자, 조사자, 실행자 AI가 협력하여 피드백을 반영한 완전한 보고서를 작성합니다.
|
1796 |
|
1797 |
**상태**:
|
1798 |
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
1799 |
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
1800 |
|
1801 |
+
**7단계 협력 프로세스:**
|
1802 |
+
1. 🧠 **감독자**: 거시적 분석 및 검색 키워드 추출
|
1803 |
+
2. 🔍 **조사자**: 브레이브 검색으로 최신 정보 수집
|
1804 |
+
3. 🧠 **감독자**: 조사 내용 기반 구체적 실행 지시
|
1805 |
+
4. 👁️ **실행자**: 초기 실행 계획 작성
|
1806 |
+
5. 🧠 **감독자**: 검토 및 개선사항 피드백
|
1807 |
+
6. 👁️ **실행자**: 피드백 반영한 최종 보고서 작성
|
1808 |
+
7. 📄 **최종 산출물**: 완전한 실행 보고서
|
1809 |
"""
|
1810 |
)
|
1811 |
|
|
|
1922 |
---
|
1923 |
### 📝 사용 방법
|
1924 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
1925 |
+
2. 7단계 협력 프로세스가 진행됩니다:
|
1926 |
+
- 감독자 초기 분석 → 웹 검색 → 조사 정리 → 실행 지시 → 초기 구현 → 피드백 → 최종 보고서
|
1927 |
+
3. 각 AI의 작업 과정을 실시간으로 확인할 수 있습니다.
|
1928 |
+
4. 최종 보고서가 상단에 표시되며, 전체 협력 과정은 접을 수 있는 형태로 제공됩니다.
|
1929 |
|
1930 |
### ⚙️ 환경 설정
|
1931 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
|
|
1935 |
### 🔗 API 키 획득
|
1936 |
- Friendli API: [https://friendli.ai](https://friendli.ai)
|
1937 |
- Brave Search API: [https://brave.com/search/api/](https://brave.com/search/api/)
|
1938 |
+
|
1939 |
+
### 💡 특징
|
1940 |
+
- 완전한 피드백 루프: 감독자의 피드백이 실행자에게 전달되어 최종 개선
|
1941 |
+
- 웹 검색 기반: 최신 정보와 사례를 활용한 실용적 답변
|
1942 |
+
- 전문 보고서 ���식: 실무에서 바로 활용 가능한 구조화된 결과물
|
1943 |
"""
|
1944 |
)
|
1945 |
|