Delete app-backup2.py
Browse files- app-backup2.py +0 -931
app-backup2.py
DELETED
@@ -1,931 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import os
|
3 |
-
import json
|
4 |
-
import requests
|
5 |
-
from datetime import datetime
|
6 |
-
import time
|
7 |
-
from typing import List, Dict, Any, Generator, Tuple
|
8 |
-
import logging
|
9 |
-
import re
|
10 |
-
|
11 |
-
# 로깅 설정
|
12 |
-
logging.basicConfig(level=logging.INFO)
|
13 |
-
logger = logging.getLogger(__name__)
|
14 |
-
|
15 |
-
# 환경 변수에서 토큰 가져오기
|
16 |
-
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
|
17 |
-
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN")
|
18 |
-
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
19 |
-
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
|
20 |
-
MODEL_ID = "dep89a2fld32mcm"
|
21 |
-
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
22 |
-
|
23 |
-
# 전역 변수
|
24 |
-
conversation_history = []
|
25 |
-
|
26 |
-
class LLMCollaborativeSystem:
|
27 |
-
def __init__(self):
|
28 |
-
self.token = FRIENDLI_TOKEN
|
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 |
-
# 내부 히스토리 관리 (UI에는 표시하지 않음)
|
618 |
-
internal_history = []
|
619 |
-
|
620 |
-
def process_query_streaming(user_query: str):
|
621 |
-
"""스트리밍을 지원하는 쿼리 처리"""
|
622 |
-
global internal_history
|
623 |
-
|
624 |
-
if not user_query:
|
625 |
-
return "", "", "", "", "❌ 질문을 입력해주세요."
|
626 |
-
|
627 |
-
conversation_log = []
|
628 |
-
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
629 |
-
|
630 |
-
try:
|
631 |
-
# 1단계: 감독자 AI 초기 분석 및 키워드 추출
|
632 |
-
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
633 |
-
supervisor_initial_response = ""
|
634 |
-
|
635 |
-
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
636 |
-
for chunk in llm_system.call_llm_streaming(
|
637 |
-
[{"role": "user", "content": supervisor_prompt}],
|
638 |
-
"supervisor"
|
639 |
-
):
|
640 |
-
supervisor_initial_response += chunk
|
641 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
642 |
-
yield supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
643 |
-
|
644 |
-
all_responses["supervisor"].append(supervisor_initial_response)
|
645 |
-
|
646 |
-
# 키워드 추출
|
647 |
-
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
648 |
-
logger.info(f"추출된 키워드: {keywords}")
|
649 |
-
|
650 |
-
# 2단계: 브레이브 검색 수행
|
651 |
-
researcher_text = "[웹 검색] 🔍 검색 중...\n"
|
652 |
-
yield supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
653 |
-
|
654 |
-
search_results = {}
|
655 |
-
for keyword in keywords:
|
656 |
-
results = llm_system.brave_search(keyword)
|
657 |
-
if results:
|
658 |
-
search_results[keyword] = results
|
659 |
-
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
660 |
-
yield supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
661 |
-
|
662 |
-
# 3단계: 조사자 AI가 검색 결과 정리
|
663 |
-
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
664 |
-
researcher_response = ""
|
665 |
-
|
666 |
-
researcher_text = "[조사 결과 정리] 🔄 생성 중...\n"
|
667 |
-
for chunk in llm_system.call_llm_streaming(
|
668 |
-
[{"role": "user", "content": researcher_prompt}],
|
669 |
-
"researcher"
|
670 |
-
):
|
671 |
-
researcher_response += chunk
|
672 |
-
researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
673 |
-
yield supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
674 |
-
|
675 |
-
all_responses["researcher"].append(researcher_response)
|
676 |
-
|
677 |
-
# 4단계: 감독자 AI가 조사 내용 기반으로 실행 지시
|
678 |
-
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, researcher_response)
|
679 |
-
supervisor_execution_response = ""
|
680 |
-
|
681 |
-
supervisor_text += "\n\n---\n\n[실행 지시] 🔄 생성 중...\n"
|
682 |
-
for chunk in llm_system.call_llm_streaming(
|
683 |
-
[{"role": "user", "content": supervisor_execution_prompt}],
|
684 |
-
"supervisor"
|
685 |
-
):
|
686 |
-
supervisor_execution_response += chunk
|
687 |
-
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
|
688 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
689 |
-
yield supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 지시 중..."
|
690 |
-
|
691 |
-
all_responses["supervisor"].append(supervisor_execution_response)
|
692 |
-
|
693 |
-
# 5단계: 실행자 AI가 조사 내용과 지시를 기반으로 초기 구현
|
694 |
-
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, researcher_response)
|
695 |
-
executor_response = ""
|
696 |
-
|
697 |
-
executor_text = "[초기 구현] 🔄 생성 중...\n"
|
698 |
-
for chunk in llm_system.call_llm_streaming(
|
699 |
-
[{"role": "user", "content": executor_prompt}],
|
700 |
-
"executor"
|
701 |
-
):
|
702 |
-
executor_response += chunk
|
703 |
-
executor_text = f"[초기 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
704 |
-
yield supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
705 |
-
|
706 |
-
all_responses["executor"].append(executor_response)
|
707 |
-
|
708 |
-
# 6단계: 감독자 AI 검토 및 피드백
|
709 |
-
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
710 |
-
|
711 |
-
사용자 질문: {user_query}
|
712 |
-
|
713 |
-
실행자 AI의 답변:
|
714 |
-
{executor_response}
|
715 |
-
|
716 |
-
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요. 구체적이고 실행 가능한 개선 방안을 제시하세요."""
|
717 |
-
|
718 |
-
review_response = ""
|
719 |
-
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"
|
720 |
-
|
721 |
-
for chunk in llm_system.call_llm_streaming(
|
722 |
-
[{"role": "user", "content": review_prompt}],
|
723 |
-
"supervisor"
|
724 |
-
):
|
725 |
-
review_response += chunk
|
726 |
-
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}"
|
727 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
728 |
-
yield supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
729 |
-
|
730 |
-
all_responses["supervisor"].append(review_response)
|
731 |
-
|
732 |
-
# 7단계: 실행자 AI 최종 보고서 (피드백 반영)
|
733 |
-
final_executor_prompt = llm_system.create_executor_final_prompt(
|
734 |
-
user_query,
|
735 |
-
executor_response,
|
736 |
-
review_response,
|
737 |
-
researcher_response
|
738 |
-
)
|
739 |
-
final_executor_response = ""
|
740 |
-
|
741 |
-
executor_text += "\n\n---\n\n[최종 보고서] 🔄 작성 중...\n"
|
742 |
-
for chunk in llm_system.call_llm_streaming(
|
743 |
-
[{"role": "user", "content": final_executor_prompt}],
|
744 |
-
"executor"
|
745 |
-
):
|
746 |
-
final_executor_response += chunk
|
747 |
-
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}"
|
748 |
-
executor_text = temp_text
|
749 |
-
yield supervisor_text, researcher_text, executor_text, "", "📄 최종 보고서 작성 중..."
|
750 |
-
|
751 |
-
all_responses["executor"].append(final_executor_response)
|
752 |
-
|
753 |
-
# 최종 결과 생성 (최종 보고서를 메인으로)
|
754 |
-
final_summary = f"""## 🎯 최종 종합 보고서
|
755 |
-
|
756 |
-
### 📌 사용자 질문
|
757 |
-
{user_query}
|
758 |
-
|
759 |
-
### 📄 최종 보고서 (실행자 AI - 피드백 반영)
|
760 |
-
{final_executor_response}
|
761 |
-
|
762 |
-
---
|
763 |
-
|
764 |
-
<details>
|
765 |
-
<summary>📋 전체 협력 과정 보기</summary>
|
766 |
-
|
767 |
-
#### 🔍 거시적 분석 (감독자 AI)
|
768 |
-
{all_responses['supervisor'][0]}
|
769 |
-
|
770 |
-
#### 📚 조사 결과 (조사자 AI)
|
771 |
-
{researcher_response}
|
772 |
-
|
773 |
-
#### 🎯 실행 지시 (감독자 AI)
|
774 |
-
{all_responses['supervisor'][1]}
|
775 |
-
|
776 |
-
#### 💡 초기 구현 (실행자 AI)
|
777 |
-
{executor_response}
|
778 |
-
|
779 |
-
#### ✨ 검토 및 개선사항 (감독자 AI)
|
780 |
-
{review_response}
|
781 |
-
|
782 |
-
</details>
|
783 |
-
|
784 |
-
---
|
785 |
-
*이 보고서는 웹 검색을 통한 최신 정보와 AI들의 협력, 그리고 피드백 반영을 통해 작성되었습니다.*"""
|
786 |
-
|
787 |
-
# 내부 히스토리 업데이트 (UI에는 표시하지 않음)
|
788 |
-
internal_history.append((user_query, final_summary))
|
789 |
-
|
790 |
-
yield supervisor_text, researcher_text, executor_text, final_summary, "✅ 최종 보고서 완성!"
|
791 |
-
|
792 |
-
except Exception as e:
|
793 |
-
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
794 |
-
yield "", "", "", error_msg, error_msg
|
795 |
-
|
796 |
-
def clear_all():
|
797 |
-
"""모든 내용 초기화"""
|
798 |
-
global internal_history
|
799 |
-
internal_history = []
|
800 |
-
return "", "", "", "", "🔄 초기화되었습니다."
|
801 |
-
|
802 |
-
# Gradio 인터페이스
|
803 |
-
css = """
|
804 |
-
.gradio-container {
|
805 |
-
font-family: 'Arial', sans-serif;
|
806 |
-
}
|
807 |
-
.supervisor-box textarea {
|
808 |
-
border-left: 4px solid #667eea !important;
|
809 |
-
padding-left: 10px !important;
|
810 |
-
}
|
811 |
-
.researcher-box textarea {
|
812 |
-
border-left: 4px solid #10b981 !important;
|
813 |
-
padding-left: 10px !important;
|
814 |
-
}
|
815 |
-
.executor-box textarea {
|
816 |
-
border-left: 4px solid #764ba2 !important;
|
817 |
-
padding-left: 10px !important;
|
818 |
-
}
|
819 |
-
"""
|
820 |
-
|
821 |
-
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
822 |
-
|
823 |
-
# 입력 섹션
|
824 |
-
with gr.Row():
|
825 |
-
with gr.Column():
|
826 |
-
user_input = gr.Textbox(
|
827 |
-
label="질문 입력",
|
828 |
-
placeholder="예: 기계학습 모델의 성능을 향상시키는 방법은?",
|
829 |
-
lines=3
|
830 |
-
)
|
831 |
-
|
832 |
-
with gr.Row():
|
833 |
-
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2)
|
834 |
-
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
835 |
-
|
836 |
-
status_text = gr.Textbox(
|
837 |
-
label="상태",
|
838 |
-
interactive=False,
|
839 |
-
value="대기 중...",
|
840 |
-
max_lines=1
|
841 |
-
)
|
842 |
-
|
843 |
-
# 최종 결과
|
844 |
-
with gr.Row():
|
845 |
-
with gr.Column():
|
846 |
-
with gr.Accordion("📊 최종 종합 결과", open=True):
|
847 |
-
final_output = gr.Markdown(
|
848 |
-
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
849 |
-
)
|
850 |
-
|
851 |
-
# AI 출력들 - 한 줄에 나란히 배치
|
852 |
-
with gr.Row():
|
853 |
-
# 감독자 AI 출력
|
854 |
-
with gr.Column():
|
855 |
-
gr.Markdown("### 🧠 감독자 AI (거시적 분석)")
|
856 |
-
supervisor_output = gr.Textbox(
|
857 |
-
label="",
|
858 |
-
lines=20,
|
859 |
-
max_lines=25,
|
860 |
-
interactive=False,
|
861 |
-
elem_classes=["supervisor-box"]
|
862 |
-
)
|
863 |
-
|
864 |
-
# 조사자 AI 출력
|
865 |
-
with gr.Column():
|
866 |
-
gr.Markdown("### 🔍 조사자 AI (웹 검색 & 정리)")
|
867 |
-
researcher_output = gr.Textbox(
|
868 |
-
label="",
|
869 |
-
lines=20,
|
870 |
-
max_lines=25,
|
871 |
-
interactive=False,
|
872 |
-
elem_classes=["researcher-box"]
|
873 |
-
)
|
874 |
-
|
875 |
-
# 실행자 AI 출력
|
876 |
-
with gr.Column():
|
877 |
-
gr.Markdown("### 👁️ 실행자 AI (미시적 구현)")
|
878 |
-
executor_output = gr.Textbox(
|
879 |
-
label="",
|
880 |
-
lines=20,
|
881 |
-
max_lines=25,
|
882 |
-
interactive=False,
|
883 |
-
elem_classes=["executor-box"]
|
884 |
-
)
|
885 |
-
|
886 |
-
# 예제
|
887 |
-
gr.Examples(
|
888 |
-
examples=[
|
889 |
-
"기계학습 모델의 성능을 향상시키는 최신 방법은?",
|
890 |
-
"2024년 효과적인 프로젝트 관리 도구와 전략은?",
|
891 |
-
"지속 가능한 비즈니스 모델의 최신 트렌드는?",
|
892 |
-
"최신 데이터 시각화 도구와 기법은?",
|
893 |
-
"원격 팀의 생산성을 높이는 검증된 방법은?"
|
894 |
-
],
|
895 |
-
inputs=user_input,
|
896 |
-
label="💡 예제 질문"
|
897 |
-
)
|
898 |
-
|
899 |
-
# 이벤트 핸들러
|
900 |
-
submit_btn.click(
|
901 |
-
fn=process_query_streaming,
|
902 |
-
inputs=[user_input],
|
903 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
904 |
-
).then(
|
905 |
-
fn=lambda: "",
|
906 |
-
outputs=[user_input]
|
907 |
-
)
|
908 |
-
|
909 |
-
user_input.submit(
|
910 |
-
fn=process_query_streaming,
|
911 |
-
inputs=[user_input],
|
912 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
913 |
-
).then(
|
914 |
-
fn=lambda: "",
|
915 |
-
outputs=[user_input]
|
916 |
-
)
|
917 |
-
|
918 |
-
clear_btn.click(
|
919 |
-
fn=clear_all,
|
920 |
-
outputs=[supervisor_output, researcher_output, executor_output, final_output, status_text]
|
921 |
-
)
|
922 |
-
|
923 |
-
|
924 |
-
if __name__ == "__main__":
|
925 |
-
app.queue() # 스트리밍을 위한 큐 활성화
|
926 |
-
app.launch(
|
927 |
-
server_name="0.0.0.0",
|
928 |
-
server_port=7860,
|
929 |
-
share=True,
|
930 |
-
show_error=True
|
931 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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