Update app.py
Browse files
app.py
CHANGED
@@ -20,6 +20,985 @@ 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 |
class LLMCollaborativeSystem:
|
24 |
def __init__(self):
|
25 |
self.token = FRIENDLI_TOKEN
|
@@ -51,121 +1030,107 @@ class LLMCollaborativeSystem:
|
|
51 |
|
52 |
def create_supervisor_initial_prompt(self, user_query: str) -> str:
|
53 |
"""감독자 AI 초기 프롬프트 생성"""
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
"""감독자 AI의 조사 내용 검토 및 추가 지시 프롬프트"""
|
66 |
-
prompt = f"당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.\n\n"
|
67 |
-
prompt += f"사용자 질문: {user_query}\n\n"
|
68 |
-
prompt += f"조사자 AI의 1차 조사 결과:\n{research_summary}\n\n"
|
69 |
-
prompt += "위 조사 결과를 검토하고:\n"
|
70 |
-
prompt += "1. 조사된 내용의 품질과 완전성을 평가하세요\n"
|
71 |
-
prompt += "2. 부족하거나 누락된 중요한 정보를 식별하세요\n"
|
72 |
-
prompt += "3. 추가로 조사가 필요한 3-5개의 구체적인 키워드나 주제를 제시하세요\n"
|
73 |
-
prompt += "4. 조사자에게 특별히 주의해야 할 사항이나 중점적으로 찾아야 할 정보를 지시하세요\n\n"
|
74 |
-
prompt += "추가 키워드는 다음 형식으로 제시하세요:\n"
|
75 |
-
prompt += "[추가 검색 키워드]: 키워드1, 키워드2, 키워드3"
|
76 |
-
return prompt
|
77 |
|
78 |
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
79 |
"""조사자 AI 프롬프트 생성"""
|
80 |
-
|
81 |
-
prompt += f"사용자 질문: {user_query}\n\n"
|
82 |
-
prompt += f"감독자 AI의 지침:\n{supervisor_guidance}\n\n"
|
83 |
-
prompt += "브레이브 검색 결과:\n"
|
84 |
-
|
85 |
-
for keyword, results in search_results.items():
|
86 |
-
prompt += f"\n**{keyword}에 대한 검색 결과:**\n"
|
87 |
-
for i, result in enumerate(results[:3], 1):
|
88 |
-
prompt += f"{i}. {result.get('title', 'N/A')}\n"
|
89 |
-
prompt += f" - {result.get('description', 'N/A')}\n"
|
90 |
-
prompt += f" - 출처: {result.get('url', 'N/A')}\n"
|
91 |
-
|
92 |
-
prompt += "\n위 검색 결과를 바탕으로:\n"
|
93 |
-
prompt += "1. 각 키워드별로 중요한 정보를 정리하세요\n"
|
94 |
-
prompt += "2. 신뢰할 수 있는 출처를 명시하세요\n"
|
95 |
-
prompt += "3. 실행자 AI가 활용할 수 있는 구체적인 데이터와 사실을 추출하세요\n"
|
96 |
-
prompt += "4. 최신 트렌드나 중요한 통계가 있다면 강조하세요"
|
97 |
-
return prompt
|
98 |
-
|
99 |
-
def create_researcher_additional_prompt(self, user_query: str, previous_research: str, supervisor_feedback: str, search_results: Dict[str, List[Dict]]) -> str:
|
100 |
-
"""조사자 AI 추가 조사 프롬프트"""
|
101 |
-
prompt = f"당신은 정보를 조사하고 정리하는 조사자 AI입니다.\n\n"
|
102 |
-
prompt += f"사용자 질문: {user_query}\n\n"
|
103 |
-
prompt += f"이전 조사 내용:\n{previous_research}\n\n"
|
104 |
-
prompt += f"감독자 AI의 피드백 및 추가 조사 지시:\n{supervisor_feedback}\n\n"
|
105 |
-
prompt += "추가 검색 결과:\n"
|
106 |
-
|
107 |
for keyword, results in search_results.items():
|
108 |
-
|
109 |
for i, result in enumerate(results[:3], 1):
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
def create_supervisor_execution_prompt(self, user_query: str, research_summary: str) -> str:
|
122 |
"""감독자 AI의 실행 지시 프롬프트"""
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
|
|
|
|
|
|
132 |
|
133 |
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, research_summary: str) -> str:
|
134 |
"""실행자 AI 프롬프트 생성"""
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
|
|
|
|
|
|
|
|
145 |
|
146 |
def create_executor_final_prompt(self, user_query: str, initial_response: str, supervisor_feedback: str, research_summary: str) -> str:
|
147 |
"""실행자 AI 최종 보고서 프롬프트"""
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
keywords = []
|
164 |
|
165 |
-
# [검색 키워드]:
|
166 |
-
keyword_match = re.search(r'\[
|
167 |
if keyword_match:
|
168 |
-
keyword_str = keyword_match.group(
|
169 |
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
170 |
|
171 |
# 키워드가 없으면 기본 키워드 생성
|
@@ -243,34 +1208,324 @@ class LLMCollaborativeSystem:
|
|
243 |
# 테스트 모드
|
244 |
if self.test_mode:
|
245 |
logger.info(f"테스트 모드 스트리밍 - Role: {role}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
|
247 |
-
#
|
248 |
-
if role == "supervisor":
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
response = "실행 계획을 검토했습니다. 모니터링 체계와 팀 역량 개발이 필요합니다."
|
255 |
-
else:
|
256 |
-
response = "거시적 분석을 시작합니다. [검색 키워드]: 모범 사례, 구현 가이드, 사례 연구"
|
257 |
elif role == "researcher":
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
response = "웹 검색을 통해 최신 정보를 수집했습니다. 주요 트렌드와 사례를 정리했습니다."
|
262 |
-
elif role == "executor":
|
263 |
-
if "최종 보고서" in messages[0]["content"]:
|
264 |
-
response = "피드백을 반영한 최종 보고서입니다. 전체 프로젝트 계획과 예상 성과를 포함합니다."
|
265 |
-
else:
|
266 |
-
response = "구체적인 실행 계획을 수립했습니다. 주차별 상세 일정과 도구 선택을 포함합니다."
|
267 |
else:
|
268 |
-
response = "
|
269 |
|
270 |
yield from self.simulate_streaming(response, role)
|
271 |
return
|
272 |
|
273 |
-
# 실제 API 호출
|
274 |
try:
|
275 |
system_prompts = {
|
276 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
@@ -335,11 +1590,12 @@ class LLMCollaborativeSystem:
|
|
335 |
# 시스템 인스턴스 생성
|
336 |
llm_system = LLMCollaborativeSystem()
|
337 |
|
338 |
-
def process_query_streaming(user_query: str):
|
339 |
-
"""스트리밍을 지원하는 쿼리 처리
|
340 |
if not user_query:
|
341 |
-
return "", "", "", "", "❌ 질문을 입력해주세요."
|
342 |
|
|
|
343 |
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
344 |
|
345 |
try:
|
@@ -347,21 +1603,24 @@ def process_query_streaming(user_query: str):
|
|
347 |
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
348 |
supervisor_initial_response = ""
|
349 |
|
350 |
-
supervisor_text = "[
|
351 |
for chunk in llm_system.call_llm_streaming(
|
352 |
[{"role": "user", "content": supervisor_prompt}],
|
353 |
"supervisor"
|
354 |
):
|
355 |
supervisor_initial_response += chunk
|
356 |
-
supervisor_text = f"[
|
357 |
-
yield supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
358 |
|
359 |
all_responses["supervisor"].append(supervisor_initial_response)
|
|
|
|
|
360 |
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
|
|
361 |
|
362 |
-
# 2단계:
|
363 |
-
researcher_text = "[
|
364 |
-
yield supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
365 |
|
366 |
search_results = {}
|
367 |
for keyword in keywords:
|
@@ -369,166 +1628,145 @@ def process_query_streaming(user_query: str):
|
|
369 |
if results:
|
370 |
search_results[keyword] = results
|
371 |
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
372 |
-
yield supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
373 |
|
374 |
-
# 3단계: 조사자 AI
|
375 |
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
376 |
researcher_response = ""
|
377 |
|
378 |
-
researcher_text = "[
|
379 |
for chunk in llm_system.call_llm_streaming(
|
380 |
[{"role": "user", "content": researcher_prompt}],
|
381 |
"researcher"
|
382 |
):
|
383 |
researcher_response += chunk
|
384 |
-
researcher_text = f"[
|
385 |
-
yield supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
386 |
|
387 |
all_responses["researcher"].append(researcher_response)
|
388 |
|
389 |
-
# 4단계: 감독자 AI가 조사 내용
|
390 |
-
|
391 |
-
supervisor_review_response = ""
|
392 |
-
|
393 |
-
supervisor_text += "\n\n---\n\n[4. 조사 검토 및 추가 지시] 🔄 생성 중...\n"
|
394 |
-
for chunk in llm_system.call_llm_streaming(
|
395 |
-
[{"role": "user", "content": supervisor_review_prompt}],
|
396 |
-
"supervisor"
|
397 |
-
):
|
398 |
-
supervisor_review_response += chunk
|
399 |
-
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[4. 조사 검토 및 추가 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_review_response}"
|
400 |
-
supervisor_text = f"[1. 초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
401 |
-
yield supervisor_text, researcher_text, "", "", "🔍 감독자 AI가 추가 조사 지시 중..."
|
402 |
-
|
403 |
-
all_responses["supervisor"].append(supervisor_review_response)
|
404 |
-
additional_keywords = llm_system.extract_keywords(supervisor_review_response)
|
405 |
-
|
406 |
-
# 5단계: 2차 브레이브 검색
|
407 |
-
researcher_text += "\n\n---\n\n[5. 2차 웹 검색] 🔍 추가 검색 중...\n"
|
408 |
-
yield supervisor_text, researcher_text, "", "", "🔍 추가 웹 검색 수행 중..."
|
409 |
-
|
410 |
-
additional_search_results = {}
|
411 |
-
for keyword in additional_keywords:
|
412 |
-
results = llm_system.brave_search(keyword)
|
413 |
-
if results:
|
414 |
-
additional_search_results[keyword] = results
|
415 |
-
researcher_text += f"✓ '{keyword}' 추가 검색 완료\n"
|
416 |
-
yield supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 추가 검색 중..."
|
417 |
-
|
418 |
-
# 6단계: 조사자 AI 최종 정리
|
419 |
-
additional_researcher_prompt = llm_system.create_researcher_additional_prompt(
|
420 |
-
user_query, researcher_response, supervisor_review_response, additional_search_results
|
421 |
-
)
|
422 |
-
final_researcher_response = ""
|
423 |
-
|
424 |
-
researcher_text += "\n\n---\n\n[6. 최종 조사 정리] 🔄 생성 중...\n"
|
425 |
-
for chunk in llm_system.call_llm_streaming(
|
426 |
-
[{"role": "user", "content": additional_researcher_prompt}],
|
427 |
-
"researcher"
|
428 |
-
):
|
429 |
-
final_researcher_response += chunk
|
430 |
-
temp_text = researcher_text.split("\n\n---\n\n")
|
431 |
-
temp_text[-1] = f"[6. 최종 조사 정리] - {datetime.now().strftime('%H:%M:%S')}\n{final_researcher_response}"
|
432 |
-
researcher_text = "\n\n---\n\n".join(temp_text)
|
433 |
-
yield supervisor_text, researcher_text, "", "", "📝 조사자 AI가 최종 정리 중..."
|
434 |
-
|
435 |
-
all_responses["researcher"].append(final_researcher_response)
|
436 |
-
|
437 |
-
# 7단계: 감독자 AI가 최종 실행 지시
|
438 |
-
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, final_researcher_response)
|
439 |
supervisor_execution_response = ""
|
440 |
|
441 |
-
supervisor_text += "\n\n---\n\n[
|
442 |
for chunk in llm_system.call_llm_streaming(
|
443 |
[{"role": "user", "content": supervisor_execution_prompt}],
|
444 |
"supervisor"
|
445 |
):
|
446 |
supervisor_execution_response += chunk
|
447 |
-
|
448 |
-
|
449 |
-
supervisor_text
|
450 |
-
yield supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 실행 지시 중..."
|
451 |
|
452 |
all_responses["supervisor"].append(supervisor_execution_response)
|
453 |
|
454 |
-
#
|
455 |
-
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response,
|
456 |
executor_response = ""
|
457 |
|
458 |
-
executor_text = "[
|
459 |
for chunk in llm_system.call_llm_streaming(
|
460 |
[{"role": "user", "content": executor_prompt}],
|
461 |
"executor"
|
462 |
):
|
463 |
executor_response += chunk
|
464 |
-
executor_text = f"[
|
465 |
-
yield supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
466 |
|
467 |
all_responses["executor"].append(executor_response)
|
468 |
|
469 |
-
#
|
470 |
-
review_prompt = f"당신은 거시적 관점에서 분석하고 지도하는 감독자 AI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
471 |
|
472 |
review_response = ""
|
473 |
-
supervisor_text
|
474 |
|
475 |
for chunk in llm_system.call_llm_streaming(
|
476 |
[{"role": "user", "content": review_prompt}],
|
477 |
"supervisor"
|
478 |
):
|
479 |
review_response += chunk
|
480 |
-
|
481 |
-
|
482 |
-
supervisor_text
|
483 |
-
yield supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
484 |
|
485 |
all_responses["supervisor"].append(review_response)
|
486 |
|
487 |
-
#
|
488 |
final_executor_prompt = llm_system.create_executor_final_prompt(
|
489 |
-
user_query,
|
|
|
|
|
|
|
490 |
)
|
491 |
final_executor_response = ""
|
492 |
|
493 |
-
executor_text += "\n\n---\n\n[
|
494 |
for chunk in llm_system.call_llm_streaming(
|
495 |
[{"role": "user", "content": final_executor_prompt}],
|
496 |
"executor"
|
497 |
):
|
498 |
final_executor_response += chunk
|
499 |
-
|
500 |
-
|
501 |
-
executor_text
|
502 |
-
yield supervisor_text, researcher_text, executor_text, "", "📄 최종 보고서 작성 중..."
|
503 |
|
504 |
all_responses["executor"].append(final_executor_response)
|
505 |
|
506 |
-
# 최종 결과 생성
|
507 |
-
final_summary = "## 최종 종합
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
524 |
|
525 |
except Exception as e:
|
526 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
527 |
-
yield "", "", "", error_msg, error_msg
|
528 |
|
529 |
def clear_all():
|
530 |
"""모든 내용 초기화"""
|
531 |
-
return "", "", "", "", "🔄 초기화되었습니다."
|
532 |
|
533 |
# Gradio 인터페이스
|
534 |
css = """
|
@@ -538,106 +1776,109 @@ css = """
|
|
538 |
.supervisor-box textarea {
|
539 |
border-left: 4px solid #667eea !important;
|
540 |
padding-left: 10px !important;
|
541 |
-
font-size: 13px !important;
|
542 |
}
|
543 |
.researcher-box textarea {
|
544 |
border-left: 4px solid #10b981 !important;
|
545 |
padding-left: 10px !important;
|
546 |
-
font-size: 13px !important;
|
547 |
}
|
548 |
.executor-box textarea {
|
549 |
border-left: 4px solid #764ba2 !important;
|
550 |
padding-left: 10px !important;
|
551 |
-
font-size: 13px !important;
|
552 |
}
|
553 |
"""
|
554 |
|
555 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
556 |
gr.Markdown(
|
557 |
f"""
|
558 |
-
# 🤝
|
559 |
|
560 |
-
> 감독자, 조사자, 실행자 AI가
|
561 |
|
562 |
**상태**:
|
563 |
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
564 |
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
565 |
|
566 |
-
**
|
567 |
-
1. 🧠
|
568 |
-
2. 🔍
|
569 |
-
3.
|
570 |
-
4.
|
571 |
-
5.
|
572 |
-
6.
|
573 |
-
7.
|
574 |
-
8. 👁️ 실행자: 초기 구현
|
575 |
-
9. 🧠 감독자: 검토 및 피드백
|
576 |
-
10. 👁️ 실행자: 최종 보고서
|
577 |
"""
|
578 |
)
|
579 |
|
580 |
-
# 입력 섹션
|
581 |
with gr.Row():
|
582 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
583 |
user_input = gr.Textbox(
|
584 |
label="질문 입력",
|
585 |
-
placeholder="예: 기계학습 모델의 성능을 향상시키는
|
586 |
-
lines=
|
587 |
-
)
|
588 |
-
with gr.Column(scale=1):
|
589 |
-
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=1)
|
590 |
-
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
591 |
-
|
592 |
-
status_text = gr.Textbox(
|
593 |
-
label="상태",
|
594 |
-
interactive=False,
|
595 |
-
value="대기 중...",
|
596 |
-
max_lines=1
|
597 |
-
)
|
598 |
-
|
599 |
-
# AI 출력 섹션 (가로 3분할)
|
600 |
-
with gr.Row():
|
601 |
-
# 감독자 AI 출력
|
602 |
-
with gr.Column(scale=1):
|
603 |
-
gr.Markdown("### 🧠 감독자 AI")
|
604 |
-
supervisor_output = gr.Textbox(
|
605 |
-
label="거시적 분석 및 지시",
|
606 |
-
lines=20,
|
607 |
-
max_lines=25,
|
608 |
-
interactive=False,
|
609 |
-
elem_classes=["supervisor-box"]
|
610 |
)
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
max_lines=25,
|
619 |
interactive=False,
|
620 |
-
|
|
|
621 |
)
|
622 |
|
623 |
-
#
|
624 |
-
with gr.Column(scale=
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
)
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
641 |
|
642 |
# 예제
|
643 |
gr.Examples(
|
@@ -655,8 +1896,8 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
655 |
# 이벤트 핸들러
|
656 |
submit_btn.click(
|
657 |
fn=process_query_streaming,
|
658 |
-
inputs=[user_input],
|
659 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
660 |
).then(
|
661 |
fn=lambda: "",
|
662 |
outputs=[user_input]
|
@@ -664,8 +1905,8 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
664 |
|
665 |
user_input.submit(
|
666 |
fn=process_query_streaming,
|
667 |
-
inputs=[user_input],
|
668 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
669 |
).then(
|
670 |
fn=lambda: "",
|
671 |
outputs=[user_input]
|
@@ -673,7 +1914,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
673 |
|
674 |
clear_btn.click(
|
675 |
fn=clear_all,
|
676 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
677 |
)
|
678 |
|
679 |
gr.Markdown(
|
@@ -681,20 +1922,24 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
681 |
---
|
682 |
### 📝 사용 방법
|
683 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
684 |
-
2.
|
685 |
-
-
|
686 |
-
|
687 |
-
|
688 |
|
689 |
### ⚙️ 환경 설정
|
690 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
691 |
- **Brave Search API**: `export BAPI_TOKEN="your_brave_api_token"`
|
692 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
693 |
|
|
|
|
|
|
|
|
|
694 |
### 💡 특징
|
695 |
-
-
|
696 |
-
-
|
697 |
-
-
|
698 |
"""
|
699 |
)
|
700 |
|
|
|
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
|
29 |
+
self.bapi_token = BAPI_TOKEN
|
30 |
+
self.api_url = API_URL
|
31 |
+
self.brave_url = BRAVE_SEARCH_URL
|
32 |
+
self.model_id = MODEL_ID
|
33 |
+
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
|
34 |
+
|
35 |
+
if self.test_mode:
|
36 |
+
logger.warning("테스트 모드로 실행됩니다.")
|
37 |
+
if self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
38 |
+
logger.warning("Brave API 토큰이 설정되지 않았습니다.")
|
39 |
+
|
40 |
+
def create_headers(self):
|
41 |
+
"""API 헤더 생성"""
|
42 |
+
return {
|
43 |
+
"Authorization": f"Bearer {self.token}",
|
44 |
+
"Content-Type": "application/json"
|
45 |
+
}
|
46 |
+
|
47 |
+
def create_brave_headers(self):
|
48 |
+
"""Brave API 헤더 생성"""
|
49 |
+
return {
|
50 |
+
"Accept": "application/json",
|
51 |
+
"Accept-Encoding": "gzip",
|
52 |
+
"X-Subscription-Token": self.bapi_token
|
53 |
+
}
|
54 |
+
|
55 |
+
def create_supervisor_initial_prompt(self, user_query: str) -> str:
|
56 |
+
"""감독자 AI 초기 프롬프트 생성"""
|
57 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
58 |
+
|
59 |
+
사용자 질문: {user_query}
|
60 |
+
|
61 |
+
이 질문에 대해:
|
62 |
+
1. 전체적인 접근 방향과 프레임워크를 제시하세요
|
63 |
+
2. 핵심 요소와 고려사항을 구조화하여 설명하세요
|
64 |
+
3. 이 주제에 대해 조사가 필요한 5-7개의 구체적인 키워드나 검색어를 제시하세요
|
65 |
+
|
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 = ""
|
72 |
+
for keyword, results in search_results.items():
|
73 |
+
search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n"
|
74 |
+
for i, result in enumerate(results[:3], 1):
|
75 |
+
search_summary += f"{i}. {result.get('title', 'N/A')}\n"
|
76 |
+
search_summary += f" - {result.get('description', 'N/A')}\n"
|
77 |
+
search_summary += f" - 출처: {result.get('url', 'N/A')}\n"
|
78 |
+
|
79 |
+
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.
|
80 |
+
|
81 |
+
사용자 질문: {user_query}
|
82 |
+
|
83 |
+
감독자 AI의 지침:
|
84 |
+
{supervisor_guidance}
|
85 |
+
|
86 |
+
브레이브 검색 결과:
|
87 |
+
{search_summary}
|
88 |
+
|
89 |
+
위 검색 결과를 바탕으로:
|
90 |
+
1. 각 키워드별로 중요한 정보를 정리하세요
|
91 |
+
2. 신뢰할 수 있는 출처를 명시하세요
|
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에게 아주 구체적인 지시를 내려주세요:
|
105 |
+
1. 조사된 정보를 어떻게 활용할지 명확히 지시하세요
|
106 |
+
2. 실행 가능한 단계별 작업을 구체적으로 제시하세요
|
107 |
+
3. 각 단계에서 참고해야 할 조사 내용을 명시하세요
|
108 |
+
4. 예상되는 결과물의 형태를 구체적으로 설명하세요"""
|
109 |
+
|
110 |
+
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, research_summary: str) -> str:
|
111 |
+
"""실행자 AI 프롬프트 생성"""
|
112 |
+
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
113 |
+
|
114 |
+
사용자 질문: {user_query}
|
115 |
+
|
116 |
+
조사자 AI가 정리한 조사 내용:
|
117 |
+
{research_summary}
|
118 |
+
|
119 |
+
감독자 AI의 구체적인 지시:
|
120 |
+
{supervisor_guidance}
|
121 |
+
|
122 |
+
위 조사 내용과 지시사항을 바탕으로:
|
123 |
+
1. 조사된 정보를 적극 활용하여 구체적인 실행 계획을 작성하세요
|
124 |
+
2. 각 단계별로 참고한 조사 내용을 명시하세요
|
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
|
|
|
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 = []
|
1129 |
|
1130 |
+
# [검색 키워드]: 형식으로 키워드 찾기
|
1131 |
+
keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE)
|
1132 |
if keyword_match:
|
1133 |
+
keyword_str = keyword_match.group(1)
|
1134 |
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
1135 |
|
1136 |
# 키워드가 없으면 기본 키워드 생성
|
|
|
1208 |
# 테스트 모드
|
1209 |
if self.test_mode:
|
1210 |
logger.info(f"테스트 모드 스트리밍 - Role: {role}")
|
1211 |
+
test_responses = {
|
1212 |
+
"supervisor_initial": """이 질문에 대한 거시적 분석을 제시하겠습니다.
|
1213 |
+
|
1214 |
+
1. **핵심 개념 파악**
|
1215 |
+
- 질문의 본질적 요소를 심층 분석합니다
|
1216 |
+
- 관련된 주요 이론과 원칙을 검토합니다
|
1217 |
+
- 다양한 관점에서의 접근 방법을 고려합니다
|
1218 |
+
|
1219 |
+
2. **전략적 접근 방향**
|
1220 |
+
- 체계적이고 단계별 해결 방안을 수립합니다
|
1221 |
+
- 장단기 목표를 명확히 설정합니다
|
1222 |
+
- 리스크 요인과 대응 방안을 마련합니다
|
1223 |
+
|
1224 |
+
3. **기대 효과와 과제**
|
1225 |
+
- 예상되는 긍정적 성과를 분석합니다
|
1226 |
+
- 잠재적 도전 과제를 식별합니다
|
1227 |
+
- 지속가능한 발전 방향을 제시합니다
|
1228 |
+
|
1229 |
+
[검색 키워드]: machine learning optimization, performance improvement strategies, model efficiency techniques, hyperparameter tuning best practices, latest ML trends 2024""",
|
1230 |
+
|
1231 |
+
"researcher": """조사 결과를 종합하여 다음과 같이 정리했습니다.
|
1232 |
+
|
1233 |
+
**1. Machine Learning Optimization**
|
1234 |
+
- 최신 연구에 따르면 모델 최적화의 핵심은 아키텍처 설계와 훈련 전략의 균형입니다
|
1235 |
+
- AutoML 도구들이 하이퍼파라미터 튜닝을 자동화하여 효율성을 크게 향상시킵니다
|
1236 |
+
- 출처: ML Conference 2024, Google Research
|
1237 |
+
|
1238 |
+
**2. Performance Improvement Strategies**
|
1239 |
+
- 데이터 품질 개선이 모델 성능 향상의 80%를 차지한다는 연구 결과
|
1240 |
+
- 앙상블 기법과 전이학습이 주요 성능 개선 방법으로 입증됨
|
1241 |
+
- 벤치마크: ImageNet에서 95% 이상의 정확도 달성 사례
|
1242 |
+
|
1243 |
+
**3. Model Efficiency Techniques**
|
1244 |
+
- 모델 경량화(Pruning, Quantization)로 추론 속도 10배 향상 가능
|
1245 |
+
- Knowledge Distillation으로 모델 크기 90% 감소, 성능 유지
|
1246 |
+
- 최신 트렌드: Efficient Transformers, Neural Architecture Search
|
1247 |
+
|
1248 |
+
**4. 실제 적용 사례**
|
1249 |
+
- Netflix: 추천 시스템 개선으로 사용자 만족도 35% 향상
|
1250 |
+
- Tesla: 실시간 객체 인식 속도 50% 개선
|
1251 |
+
- OpenAI: GPT 모델 효율성 개선으로 비용 70% 절감""",
|
1252 |
+
|
1253 |
+
"supervisor_execution": """조사 내용을 바탕으로 실행자 AI에게 다음과 같이 구체적으로 지시합니다.
|
1254 |
+
|
1255 |
+
**1단계: 현재 모델 진단 (1주차)**
|
1256 |
+
- 조사된 벤치마크 기준으로 현재 모델 성능 평가
|
1257 |
+
- Netflix 사례를 참고하여 주요 병목 지점 식별
|
1258 |
+
- AutoML 도구를 활용한 초기 최적화 가능성 탐색
|
1259 |
+
|
1260 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
1261 |
+
- 조사 결과의 "80% 규칙"에 따라 데이터 정제 우선 실행
|
1262 |
+
- 데이터 증강 기법 적용 (조사된 최신 기법 활용)
|
1263 |
+
- A/B 테스트로 개선 효과 측정
|
1264 |
+
|
1265 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
1266 |
+
- Knowledge Distillation 적용하여 모델 경량화
|
1267 |
+
- 조사된 Pruning 기법으로 추론 속도 개선
|
1268 |
+
- Tesla 사례의 실시간 처리 최적화 기법 벤치마킹
|
1269 |
+
|
1270 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
1271 |
+
- OpenAI 사례의 비용 절감 지표 적용
|
1272 |
+
- 조사된 성능 지표로 개선율 측정
|
1273 |
+
- 단계적 배포 전략 수립""",
|
1274 |
+
|
1275 |
+
"executor": """감독자의 지시와 조사 내용을 기반으로 구체적인 실행 계획을 수립합니다.
|
1276 |
+
|
1277 |
+
**1단계: 현재 모델 진단 (1주차)**
|
1278 |
+
- 월요일-화요일: MLflow를 사용한 현재 모델 메트릭 수집
|
1279 |
+
* 조사 결과 참고: Netflix가 사용한 핵심 지표 (정확도, 지연시간, 처리량)
|
1280 |
+
- 수요일-목요일: AutoML 도구 (Optuna, Ray Tune) 설정 및 초기 실행
|
1281 |
+
* 조사된 best practice에 따라 search space 정의
|
1282 |
+
- 금요일: 진단 보고서 작성 및 개선 우선순위 결정
|
1283 |
+
|
1284 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
1285 |
+
- 데이터 정제 파이프라인 구축
|
1286 |
+
* 조사 결과의 "80% 규칙" 적용: 누락값, 이상치, 레이블 오류 처리
|
1287 |
+
* 코드 예시: `data_quality_pipeline.py` 구현
|
1288 |
+
- 데이터 증강 구현
|
1289 |
+
* 최신 기법 적용: MixUp, CutMix, AutoAugment
|
1290 |
+
* 검증 데이터셋으로 효과 측정 (목표: 15% 성능 향상)
|
1291 |
+
|
1292 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
1293 |
+
- Knowledge Distillation 구현
|
1294 |
+
* Teacher 모델: 현재 대규모 모델
|
1295 |
+
* Student 모델: 90% 작은 크기 목표 (조사 결과 기반)
|
1296 |
+
* 구현 프레임워크: PyTorch/TensorFlow
|
1297 |
+
- Pruning 및 Quantization 적용
|
1298 |
+
* 구조적 pruning으로 50% 파라미터 제거
|
1299 |
+
* INT8 quantization으로 추가 4배 속도 향상
|
1300 |
+
* Tesla 사례 참고: TensorRT 최적화 적용
|
1301 |
+
|
1302 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
1303 |
+
- 성과 지표 측정
|
1304 |
+
* 추론 속도: 목표 10배 향상 (조사 결과 기반)
|
1305 |
+
* 정확도 손실: 최대 2% 이내 유지
|
1306 |
+
* 비용 절감: 70% 목표 (OpenAI 사례 참고)
|
1307 |
+
- 배포 전략
|
1308 |
+
* A/B 테스트: 10% 트래픽으로 시작
|
1309 |
+
* 모니터링: Prometheus + Grafana 대시보드
|
1310 |
+
* 롤백 계획: 성능 저하 시 자동 롤백
|
1311 |
+
|
1312 |
+
**예상 결과물**
|
1313 |
+
- 최적화된 모델 (크기 90% 감소, 속도 10배 향상)
|
1314 |
+
- 상세 성능 벤치마크 보고서
|
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:
|
1515 |
+
response = test_responses["supervisor_review"]
|
1516 |
+
elif role == "supervisor":
|
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 |
|
1525 |
yield from self.simulate_streaming(response, role)
|
1526 |
return
|
1527 |
|
1528 |
+
# 실제 API 호출
|
1529 |
try:
|
1530 |
system_prompts = {
|
1531 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
|
|
1590 |
# 시스템 인스턴스 생성
|
1591 |
llm_system = LLMCollaborativeSystem()
|
1592 |
|
1593 |
+
def process_query_streaming(user_query: str, history: List):
|
1594 |
+
"""스트리밍을 지원하는 쿼리 처리"""
|
1595 |
if not user_query:
|
1596 |
+
return history, "", "", "", "", "❌ 질문을 입력해주세요."
|
1597 |
|
1598 |
+
conversation_log = []
|
1599 |
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
1600 |
|
1601 |
try:
|
|
|
1603 |
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
1604 |
supervisor_initial_response = ""
|
1605 |
|
1606 |
+
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
1607 |
for chunk in llm_system.call_llm_streaming(
|
1608 |
[{"role": "user", "content": supervisor_prompt}],
|
1609 |
"supervisor"
|
1610 |
):
|
1611 |
supervisor_initial_response += chunk
|
1612 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
1613 |
+
yield history, supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
1614 |
|
1615 |
all_responses["supervisor"].append(supervisor_initial_response)
|
1616 |
+
|
1617 |
+
# 키워드 추출
|
1618 |
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
1619 |
+
logger.info(f"추출된 키워드: {keywords}")
|
1620 |
|
1621 |
+
# 2단계: 브레이브 검색 수행
|
1622 |
+
researcher_text = "[웹 검색] 🔍 검색 중...\n"
|
1623 |
+
yield history, supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
1624 |
|
1625 |
search_results = {}
|
1626 |
for keyword in keywords:
|
|
|
1628 |
if results:
|
1629 |
search_results[keyword] = results
|
1630 |
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
1631 |
+
yield history, supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
1632 |
|
1633 |
+
# 3단계: 조사자 AI가 검색 결과 정리
|
1634 |
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
1635 |
researcher_response = ""
|
1636 |
|
1637 |
+
researcher_text = "[조사 결과 정리] 🔄 생성 중...\n"
|
1638 |
for chunk in llm_system.call_llm_streaming(
|
1639 |
[{"role": "user", "content": researcher_prompt}],
|
1640 |
"researcher"
|
1641 |
):
|
1642 |
researcher_response += chunk
|
1643 |
+
researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
1644 |
+
yield history, supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
1645 |
|
1646 |
all_responses["researcher"].append(researcher_response)
|
1647 |
|
1648 |
+
# 4단계: 감독자 AI가 조사 내용 기반으로 실행 지시
|
1649 |
+
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, researcher_response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1650 |
supervisor_execution_response = ""
|
1651 |
|
1652 |
+
supervisor_text += "\n\n---\n\n[실행 지시] 🔄 생성 중...\n"
|
1653 |
for chunk in llm_system.call_llm_streaming(
|
1654 |
[{"role": "user", "content": supervisor_execution_prompt}],
|
1655 |
"supervisor"
|
1656 |
):
|
1657 |
supervisor_execution_response += chunk
|
1658 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
|
1659 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
1660 |
+
yield history, supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 지시 중..."
|
|
|
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}
|
1683 |
+
|
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)}"
|
1765 |
+
yield history, "", "", "", error_msg, error_msg
|
1766 |
|
1767 |
def clear_all():
|
1768 |
"""모든 내용 초기화"""
|
1769 |
+
return [], "", "", "", "", "🔄 초기화되었습니다."
|
1770 |
|
1771 |
# Gradio 인터페이스
|
1772 |
css = """
|
|
|
1776 |
.supervisor-box textarea {
|
1777 |
border-left: 4px solid #667eea !important;
|
1778 |
padding-left: 10px !important;
|
|
|
1779 |
}
|
1780 |
.researcher-box textarea {
|
1781 |
border-left: 4px solid #10b981 !important;
|
1782 |
padding-left: 10px !important;
|
|
|
1783 |
}
|
1784 |
.executor-box textarea {
|
1785 |
border-left: 4px solid #764ba2 !important;
|
1786 |
padding-left: 10px !important;
|
|
|
1787 |
}
|
1788 |
"""
|
1789 |
|
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 |
|
|
|
1812 |
with gr.Row():
|
1813 |
+
# 왼쪽: 입력 및 채팅 기록
|
1814 |
+
with gr.Column(scale=1):
|
1815 |
+
chatbot = gr.Chatbot(
|
1816 |
+
label="💬 대화 기록",
|
1817 |
+
height=600,
|
1818 |
+
show_copy_button=True,
|
1819 |
+
bubble_full_width=False
|
1820 |
+
)
|
1821 |
+
|
1822 |
user_input = gr.Textbox(
|
1823 |
label="질문 입력",
|
1824 |
+
placeholder="예: 기계학습 모델의 성능을 향상시키는 방법은?",
|
1825 |
+
lines=3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1826 |
)
|
1827 |
+
|
1828 |
+
with gr.Row():
|
1829 |
+
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2)
|
1830 |
+
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
1831 |
+
|
1832 |
+
status_text = gr.Textbox(
|
1833 |
+
label="상태",
|
|
|
1834 |
interactive=False,
|
1835 |
+
value="대기 중...",
|
1836 |
+
max_lines=1
|
1837 |
)
|
1838 |
|
1839 |
+
# 오른쪽: AI 출력
|
1840 |
+
with gr.Column(scale=2):
|
1841 |
+
# 최종 결과
|
1842 |
+
with gr.Accordion("📊 최종 종합 결과", open=True):
|
1843 |
+
final_output = gr.Markdown(
|
1844 |
+
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
1845 |
+
)
|
1846 |
+
|
1847 |
+
# AI 출력들
|
1848 |
+
with gr.Row():
|
1849 |
+
# 감독자 AI 출력
|
1850 |
+
with gr.Column():
|
1851 |
+
gr.Markdown("### 🧠 감독자 AI (거시적 분석)")
|
1852 |
+
supervisor_output = gr.Textbox(
|
1853 |
+
label="",
|
1854 |
+
lines=12,
|
1855 |
+
max_lines=15,
|
1856 |
+
interactive=False,
|
1857 |
+
elem_classes=["supervisor-box"]
|
1858 |
+
)
|
1859 |
+
|
1860 |
+
with gr.Row():
|
1861 |
+
# 조사자 AI 출력
|
1862 |
+
with gr.Column():
|
1863 |
+
gr.Markdown("### 🔍 조사자 AI (웹 검색 & 정리)")
|
1864 |
+
researcher_output = gr.Textbox(
|
1865 |
+
label="",
|
1866 |
+
lines=12,
|
1867 |
+
max_lines=15,
|
1868 |
+
interactive=False,
|
1869 |
+
elem_classes=["researcher-box"]
|
1870 |
+
)
|
1871 |
+
|
1872 |
+
# 실행자 AI 출력
|
1873 |
+
with gr.Column():
|
1874 |
+
gr.Markdown("### 👁️ 실행자 AI (미시적 구현)")
|
1875 |
+
executor_output = gr.Textbox(
|
1876 |
+
label="",
|
1877 |
+
lines=12,
|
1878 |
+
max_lines=15,
|
1879 |
+
interactive=False,
|
1880 |
+
elem_classes=["executor-box"]
|
1881 |
+
)
|
1882 |
|
1883 |
# 예제
|
1884 |
gr.Examples(
|
|
|
1896 |
# 이벤트 핸들러
|
1897 |
submit_btn.click(
|
1898 |
fn=process_query_streaming,
|
1899 |
+
inputs=[user_input, chatbot],
|
1900 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1901 |
).then(
|
1902 |
fn=lambda: "",
|
1903 |
outputs=[user_input]
|
|
|
1905 |
|
1906 |
user_input.submit(
|
1907 |
fn=process_query_streaming,
|
1908 |
+
inputs=[user_input, chatbot],
|
1909 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1910 |
).then(
|
1911 |
fn=lambda: "",
|
1912 |
outputs=[user_input]
|
|
|
1914 |
|
1915 |
clear_btn.click(
|
1916 |
fn=clear_all,
|
1917 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
1918 |
)
|
1919 |
|
1920 |
gr.Markdown(
|
|
|
1922 |
---
|
1923 |
### 📝 사용 방법
|
1924 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
1925 |
+
2. 7단계 협력 프로세스가 진행됩니다:
|
1926 |
+
- 감독자 초기 분석 → 웹 검색 → 조사 정리 → 실행 지시 → 초기 구현 → 피드백 → 최종 보고서
|
1927 |
+
3. 각 AI의 작업 과정을 실시간으로 확인할 수 있습니다.
|
1928 |
+
4. 최종 보고서가 상단에 표시되며, 전체 협력 과정은 접을 수 있는 형태로 제공됩니다.
|
1929 |
|
1930 |
### ⚙️ 환경 설정
|
1931 |
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
1932 |
- **Brave Search API**: `export BAPI_TOKEN="your_brave_api_token"`
|
1933 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
1934 |
|
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 |
|