Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1754 +1,35 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
from
|
| 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 |
-
from bs4 import BeautifulSoup
|
| 17 |
-
from urllib.parse import urlparse
|
| 18 |
-
import urllib.request
|
| 19 |
-
|
| 20 |
-
# 환경 변수에서 토큰 가져오기
|
| 21 |
-
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
|
| 22 |
-
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN")
|
| 23 |
-
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
| 24 |
-
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
|
| 25 |
-
MODEL_ID = "dep89a2fld32mcm"
|
| 26 |
-
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
| 27 |
-
|
| 28 |
-
# 전역 변수
|
| 29 |
-
conversation_history = []
|
| 30 |
-
|
| 31 |
-
class LLMCollaborativeSystem:
|
| 32 |
-
def __init__(self):
|
| 33 |
-
self.token = FRIENDLI_TOKEN
|
| 34 |
-
self.bapi_token = BAPI_TOKEN
|
| 35 |
-
self.api_url = API_URL
|
| 36 |
-
self.brave_url = BRAVE_SEARCH_URL
|
| 37 |
-
self.model_id = MODEL_ID
|
| 38 |
-
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
|
| 39 |
-
|
| 40 |
-
if self.test_mode:
|
| 41 |
-
logger.warning("테스트 모드로 실행됩니다.")
|
| 42 |
-
if self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
| 43 |
-
logger.warning("Brave API 토큰이 설정되지 않았습니다.")
|
| 44 |
-
|
| 45 |
-
def create_headers(self):
|
| 46 |
-
"""API 헤더 생성"""
|
| 47 |
-
return {
|
| 48 |
-
"Authorization": f"Bearer {self.token}",
|
| 49 |
-
"Content-Type": "application/json"
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
def create_brave_headers(self):
|
| 53 |
-
"""Brave API 헤더 생성"""
|
| 54 |
-
return {
|
| 55 |
-
"Accept": "application/json",
|
| 56 |
-
"Accept-Encoding": "gzip",
|
| 57 |
-
"X-Subscription-Token": self.bapi_token
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
def create_supervisor_initial_prompt(self, user_query: str) -> str:
|
| 61 |
-
"""감독자 AI 초기 프롬프트 생성"""
|
| 62 |
-
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
| 63 |
-
|
| 64 |
-
사용자 질문: {user_query}
|
| 65 |
-
|
| 66 |
-
이 질문에 대해:
|
| 67 |
-
1. 문제의 본질과 핵심 요구사항을 파악하세요
|
| 68 |
-
2. 해결을 위한 전략적 프레임워크를 수립하세요
|
| 69 |
-
3. 창조자 AI가 혁신적인 아이디어를 낼 수 있도록 문제의 맥락과 제약사항을 명확히 정의하세요
|
| 70 |
-
4. 성공 기준과 목표를 구체적으로 제시하세요"""
|
| 71 |
-
|
| 72 |
-
def create_creator_prompt(self, user_query: str, supervisor_guidance: str) -> str:
|
| 73 |
-
"""창조자 AI 프롬프트 생성"""
|
| 74 |
-
return f"""당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다.
|
| 75 |
-
|
| 76 |
-
사용자 질문: {user_query}
|
| 77 |
-
|
| 78 |
-
감독자 AI의 분석:
|
| 79 |
-
{supervisor_guidance}
|
| 80 |
-
|
| 81 |
-
위 분석을 바탕으로:
|
| 82 |
-
1. 기존 방식을 뛰어넘는 혁신적인 해결 방안 5-7개를 제시하세요
|
| 83 |
-
2. 각 아이디어의 독창성과 잠재적 영향력을 설명하세요
|
| 84 |
-
3. 실현 가능성과 함께 필요한 리소스를 개략적으로 제시하세요
|
| 85 |
-
4. 아이디어 간의 시너지 효과나 결합 가능성을 탐색하세요
|
| 86 |
-
5. 미래 지향적이고 파괴적인 혁신 요소를 포함하세요"""
|
| 87 |
-
|
| 88 |
-
def create_supervisor_ideation_review_prompt(self, user_query: str, creator_ideas: str) -> str:
|
| 89 |
-
"""감독자 AI의 아이디어 검토 및 조사 지시 프롬프트"""
|
| 90 |
-
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
| 91 |
-
|
| 92 |
-
사용자 질문: {user_query}
|
| 93 |
-
|
| 94 |
-
창조자 AI가 제시한 혁신적 아이디어들:
|
| 95 |
-
{creator_ideas}
|
| 96 |
-
|
| 97 |
-
이 아이디어들을 검토하고:
|
| 98 |
-
1. 각 아이디어의 전략적 가치와 실현 가능성을 평가하세요
|
| 99 |
-
2. 가장 유망한 3-4개 아이디어를 선별하고 그 이유를 설명하세요
|
| 100 |
-
3. 선별된 아이디어에 대해 조사가 필요한 구체적인 키워드나 검색어를 제시하세요
|
| 101 |
-
4. 조사 시 중점적으로 확인해야 할 사항들을 명시하세요
|
| 102 |
-
|
| 103 |
-
키워드는 다음 형식으로 제시하세요:
|
| 104 |
-
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
|
| 105 |
-
|
| 106 |
-
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
| 107 |
-
"""조사자 AI 프롬프트 생성 (기존 코드 재사용)"""
|
| 108 |
-
search_summary = ""
|
| 109 |
-
all_results = []
|
| 110 |
-
|
| 111 |
-
for keyword, results in search_results.items():
|
| 112 |
-
search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n"
|
| 113 |
-
for i, result in enumerate(results[:10], 1):
|
| 114 |
-
search_summary += f"{i}. {result.get('title', 'N/A')} (신뢰도: {result.get('credibility_score', 0):.2f})\n"
|
| 115 |
-
search_summary += f" - {result.get('description', 'N/A')}\n"
|
| 116 |
-
search_summary += f" - 출처: {result.get('url', 'N/A')}\n"
|
| 117 |
-
if result.get('published'):
|
| 118 |
-
search_summary += f" - 게시일: {result.get('published')}\n"
|
| 119 |
-
|
| 120 |
-
all_results.extend(results)
|
| 121 |
-
|
| 122 |
-
contradictions = self.detect_contradictions(all_results)
|
| 123 |
-
contradiction_text = ""
|
| 124 |
-
if contradictions:
|
| 125 |
-
contradiction_text = "\n\n**발견된 정보 모순:**\n"
|
| 126 |
-
for cont in contradictions[:3]:
|
| 127 |
-
contradiction_text += f"- {cont['type']}: {cont['source1']} vs {cont['source2']}\n"
|
| 128 |
-
|
| 129 |
-
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.
|
| 130 |
-
|
| 131 |
-
사용자 질문: {user_query}
|
| 132 |
-
|
| 133 |
-
감독자 AI의 지침:
|
| 134 |
-
{supervisor_guidance}
|
| 135 |
-
|
| 136 |
-
브레이브 검색 결과 (신뢰도 점수 포함):
|
| 137 |
-
{search_summary}
|
| 138 |
-
{contradiction_text}
|
| 139 |
-
|
| 140 |
-
위 검색 결과를 바탕으로:
|
| 141 |
-
1. 각 키워드별로 중요한 정보를 정리하세요
|
| 142 |
-
2. 신뢰할 수 있는 출처(신뢰도 0.7 이상)를 우선적으로 참고하세요
|
| 143 |
-
3. 실제 구현 사례나 성공 사례를 중점적으로 찾아 정리하세요
|
| 144 |
-
4. 기술적 실현 가능성과 필요한 리소스 정보를 포함하세요
|
| 145 |
-
5. 최신 트렌드와 미래 전망을 강조하세요"""
|
| 146 |
-
|
| 147 |
-
def create_evaluator_research_prompt(self, user_query: str, creator_ideas: str, research_summary: str) -> str:
|
| 148 |
-
"""평가자 AI의 조사 결과 평가 프롬프트"""
|
| 149 |
-
return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.
|
| 150 |
-
|
| 151 |
-
사용자 질문: {user_query}
|
| 152 |
-
|
| 153 |
-
창조자 AI의 아이디어:
|
| 154 |
-
{creator_ideas}
|
| 155 |
-
|
| 156 |
-
조사자 AI의 조사 결과:
|
| 157 |
-
{research_summary}
|
| 158 |
-
|
| 159 |
-
위 내용을 종합적으로 평가하여:
|
| 160 |
-
1. 각 아이디어의 실현 가능성을 1-10점으로 평가하고 근거를 제시하세요
|
| 161 |
-
2. 예상되는 리스크와 장애물을 구체적으로 분석하세요
|
| 162 |
-
3. ROI(투자 대비 효과)를 예측하고 우선순위를 제안하세요
|
| 163 |
-
4. 조사 결과의 신뢰성과 충분성을 평가하세요
|
| 164 |
-
5. 추가로 필요한 정보나 검증 사항을 제시하세요
|
| 165 |
-
6. 최종적으로 가장 실행 가능한 2-3개 방안을 추천하세요"""
|
| 166 |
-
|
| 167 |
-
def create_supervisor_execution_prompt(self, user_query: str, evaluator_assessment: str) -> str:
|
| 168 |
-
"""감독자 AI의 실행 지시 프롬프트"""
|
| 169 |
-
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
| 170 |
-
|
| 171 |
-
사용자 질문: {user_query}
|
| 172 |
-
|
| 173 |
-
평가자 AI의 종합 평가:
|
| 174 |
-
{evaluator_assessment}
|
| 175 |
-
|
| 176 |
-
평가 결과를 바탕으로 실행자 AI에게 구체적인 지시를 내려주세요:
|
| 177 |
-
1. 평가자가 추천한 방안들을 어떻게 구현할지 단계별로 명시하세요
|
| 178 |
-
2. 각 단계의 구체적인 작업 내용과 예상 소요 시간을 제시하세요
|
| 179 |
-
3. 리스크 대응 방안을 각 단계별로 준비하세요
|
| 180 |
-
4. 성과 측정 지표와 마일스톤을 명확히 정의하세요
|
| 181 |
-
5. 필요한 리소스와 협력 체계를 구체화하세요"""
|
| 182 |
-
|
| 183 |
-
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, full_context: str) -> str:
|
| 184 |
-
"""실행자 AI 프롬프트 생성"""
|
| 185 |
-
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
| 186 |
-
|
| 187 |
-
사용자 질문: {user_query}
|
| 188 |
-
|
| 189 |
-
전체 맥락 (아이디어, 조사, 평가):
|
| 190 |
-
{full_context}
|
| 191 |
-
|
| 192 |
-
감독자 AI의 구체적인 지시:
|
| 193 |
-
{supervisor_guidance}
|
| 194 |
-
|
| 195 |
-
위 모든 정보를 바탕으로:
|
| 196 |
-
1. 즉시 실행 가능한 구체적인 행동 계획을 작성하세요
|
| 197 |
-
2. 각 작업의 상세한 실행 방법과 필요 도구를 명시하세요
|
| 198 |
-
3. 예상되는 결과물과 산출물을 구체적으로 설명하세요
|
| 199 |
-
4. 단계별 체크리스트와 검증 방법을 포함하세요
|
| 200 |
-
5. 실제 코드, 템플릿, 프로세스 등 즉시 사용 가능한 자료를 제공하세요"""
|
| 201 |
-
|
| 202 |
-
def create_evaluator_execution_prompt(self, user_query: str, executor_plan: str) -> str:
|
| 203 |
-
"""평가자 AI의 실행 계획 평가 프롬프트"""
|
| 204 |
-
return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.
|
| 205 |
-
|
| 206 |
-
사용자 질문: {user_query}
|
| 207 |
-
|
| 208 |
-
실행자 AI의 실행 계획:
|
| 209 |
-
{executor_plan}
|
| 210 |
-
|
| 211 |
-
이 실행 계획을 평가하여:
|
| 212 |
-
1. 계획의 완성도와 실행 가능성을 평가하세요 (1-10점)
|
| 213 |
-
2. 누락된 요소나 개선이 필요한 부분을 구체적으로 지적하세요
|
| 214 |
-
3. 예상되는 실행 상의 문제점과 해결 방안을 제시하세요
|
| 215 |
-
4. 성공 가능성을 높이기 위한 추가 제안을 하세요
|
| 216 |
-
5. 최종 점검 사항과 품질 기준을 제시하세요"""
|
| 217 |
-
|
| 218 |
-
def create_supervisor_final_prompt(self, user_query: str, evaluator_feedback: str) -> str:
|
| 219 |
-
"""감독자 AI의 최종 지시 프롬프트"""
|
| 220 |
-
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
| 221 |
-
|
| 222 |
-
사용자 질문: {user_query}
|
| 223 |
-
|
| 224 |
-
평가자 AI의 실행 계획 평가:
|
| 225 |
-
{evaluator_feedback}
|
| 226 |
-
|
| 227 |
-
평가 내용을 바탕으로:
|
| 228 |
-
1. 실행자 AI가 반드시 보완해야 할 핵심 사항을 명확히 지시하세요
|
| 229 |
-
2. 최종 품질 기준과 완성도 요구사항을 제시하세요
|
| 230 |
-
3. 즉시 실행 가능한 형���로 만들기 위한 구체적인 개선 방향을 제시하세요
|
| 231 |
-
4. 성공적인 실행을 위한 핵심 성공 요인을 강조하세요"""
|
| 232 |
-
|
| 233 |
-
def create_executor_final_prompt(self, user_query: str, initial_plan: str, supervisor_final_guidance: str, full_context: str) -> str:
|
| 234 |
-
"""실행자 AI 최종 보고서 프롬프트"""
|
| 235 |
-
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
| 236 |
-
|
| 237 |
-
사용자 질문: {user_query}
|
| 238 |
-
|
| 239 |
-
전체 협업 맥락:
|
| 240 |
-
{full_context}
|
| 241 |
-
|
| 242 |
-
당신의 초기 실행 계획:
|
| 243 |
-
{initial_plan}
|
| 244 |
-
|
| 245 |
-
감독자 AI의 최종 지시사항:
|
| 246 |
-
{supervisor_final_guidance}
|
| 247 |
-
|
| 248 |
-
모든 피드백을 완전히 반영하여 즉시 실행 가능한 최종 솔루션을 작성하세요:
|
| 249 |
-
1. 모든 개선사항을 반영한 완성된 실행 계획
|
| 250 |
-
2. 구체적인 실행 도구, 코드, 템플릿 제공
|
| 251 |
-
3. 단계별 실행 가이드와 체크리스트
|
| 252 |
-
4. 예상 결과와 성과 측정 방법
|
| 253 |
-
5. 리스크 대응 계획과 문제 해결 가이드
|
| 254 |
-
6. 지속적 개선을 위한 모니터링 체계
|
| 255 |
-
|
| 256 |
-
**반드시 실용적이고 즉시 적용 가능한 형태로 작성하세요.**"""
|
| 257 |
-
|
| 258 |
-
def extract_keywords(self, supervisor_response: str) -> List[str]:
|
| 259 |
-
"""감독자 응답에서 키워드 추출 (기존 코드 재사용)"""
|
| 260 |
-
keywords = []
|
| 261 |
-
|
| 262 |
-
keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE)
|
| 263 |
-
if keyword_match:
|
| 264 |
-
keyword_str = keyword_match.group(1)
|
| 265 |
-
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
| 266 |
-
|
| 267 |
-
if not keywords:
|
| 268 |
-
keywords = ["best practices", "implementation guide", "case studies", "latest trends", "success factors"]
|
| 269 |
-
|
| 270 |
-
return keywords[:7]
|
| 271 |
-
|
| 272 |
-
def generate_synonyms(self, keyword: str) -> List[str]:
|
| 273 |
-
"""키워드의 동의어/유사어 생성 (기존 코드 재사용)"""
|
| 274 |
-
synonyms = {
|
| 275 |
-
"optimization": ["improvement", "enhancement", "efficiency", "tuning"],
|
| 276 |
-
"performance": ["speed", "efficiency", "throughput", "latency"],
|
| 277 |
-
"strategy": ["approach", "method", "technique", "plan"],
|
| 278 |
-
"implementation": ["deployment", "execution", "development", "integration"],
|
| 279 |
-
"analysis": ["evaluation", "assessment", "study", "research"],
|
| 280 |
-
"management": ["administration", "governance", "control", "supervision"],
|
| 281 |
-
"best practices": ["proven methods", "industry standards", "guidelines", "recommendations"],
|
| 282 |
-
"trends": ["developments", "innovations", "emerging", "future"],
|
| 283 |
-
"machine learning": ["ML", "AI", "deep learning", "neural networks"],
|
| 284 |
-
"프로젝트": ["project", "사업", "업무", "작업"],
|
| 285 |
-
"innovation": ["disruption", "breakthrough", "transformation", "revolution"],
|
| 286 |
-
"solution": ["approach", "method", "system", "framework"]
|
| 287 |
-
}
|
| 288 |
-
|
| 289 |
-
keyword_lower = keyword.lower()
|
| 290 |
-
|
| 291 |
-
if keyword_lower in synonyms:
|
| 292 |
-
return synonyms[keyword_lower][:2]
|
| 293 |
-
|
| 294 |
-
for key, values in synonyms.items():
|
| 295 |
-
if key in keyword_lower or keyword_lower in key:
|
| 296 |
-
return values[:2]
|
| 297 |
-
|
| 298 |
-
return []
|
| 299 |
-
|
| 300 |
-
def calculate_credibility_score(self, result: Dict) -> float:
|
| 301 |
-
"""검색 결과의 신뢰도 점수 계산 (기존 코드 재사용)"""
|
| 302 |
-
score = 0.5
|
| 303 |
-
|
| 304 |
-
url = result.get('url', '')
|
| 305 |
-
title = result.get('title', '')
|
| 306 |
-
description = result.get('description', '')
|
| 307 |
-
|
| 308 |
-
trusted_domains = [
|
| 309 |
-
'.edu', '.gov', '.org', 'wikipedia.org', 'nature.com',
|
| 310 |
-
'sciencedirect.com', 'ieee.org', 'acm.org', 'springer.com',
|
| 311 |
-
'harvard.edu', 'mit.edu', 'stanford.edu', 'github.com'
|
| 312 |
-
]
|
| 313 |
-
|
| 314 |
-
for domain in trusted_domains:
|
| 315 |
-
if domain in url:
|
| 316 |
-
score += 0.2
|
| 317 |
-
break
|
| 318 |
-
|
| 319 |
-
if url.startswith('https://'):
|
| 320 |
-
score += 0.1
|
| 321 |
-
|
| 322 |
-
if len(title) > 20:
|
| 323 |
-
score += 0.05
|
| 324 |
-
if len(description) > 50:
|
| 325 |
-
score += 0.05
|
| 326 |
-
|
| 327 |
-
spam_keywords = ['buy now', 'sale', 'discount', 'click here', '100% free']
|
| 328 |
-
if any(spam in (title + description).lower() for spam in spam_keywords):
|
| 329 |
-
score -= 0.3
|
| 330 |
-
|
| 331 |
-
if any(year in description for year in ['2024', '2023', '2022']):
|
| 332 |
-
score += 0.1
|
| 333 |
-
|
| 334 |
-
return max(0, min(1, score))
|
| 335 |
-
|
| 336 |
-
def fetch_url_content(self, url: str, max_length: int = 2000) -> str:
|
| 337 |
-
"""URL에서 콘텐츠 추출 (기존 코드 재사용)"""
|
| 338 |
-
try:
|
| 339 |
-
headers = {
|
| 340 |
-
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
| 341 |
-
}
|
| 342 |
-
|
| 343 |
-
req = urllib.request.Request(url, headers=headers)
|
| 344 |
-
|
| 345 |
-
with urllib.request.urlopen(req, timeout=5) as response:
|
| 346 |
-
html = response.read().decode('utf-8', errors='ignore')
|
| 347 |
-
|
| 348 |
-
soup = BeautifulSoup(html, 'html.parser')
|
| 349 |
-
|
| 350 |
-
for script in soup(["script", "style"]):
|
| 351 |
-
script.decompose()
|
| 352 |
-
|
| 353 |
-
text = soup.get_text()
|
| 354 |
-
|
| 355 |
-
lines = (line.strip() for line in text.splitlines())
|
| 356 |
-
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
|
| 357 |
-
text = ' '.join(chunk for chunk in chunks if chunk)
|
| 358 |
-
|
| 359 |
-
if len(text) > max_length:
|
| 360 |
-
text = text[:max_length] + "..."
|
| 361 |
-
|
| 362 |
-
return text
|
| 363 |
-
|
| 364 |
-
except Exception as e:
|
| 365 |
-
logger.error(f"URL 콘텐츠 가져오기 실패 {url}: {str(e)}")
|
| 366 |
-
return ""
|
| 367 |
-
|
| 368 |
-
def detect_contradictions(self, results: List[Dict]) -> List[Dict]:
|
| 369 |
-
"""검색 결과 간 모순 감지 (기존 코드 재사용)"""
|
| 370 |
-
contradictions = []
|
| 371 |
-
|
| 372 |
-
opposite_pairs = [
|
| 373 |
-
("increase", "decrease"),
|
| 374 |
-
("improve", "worsen"),
|
| 375 |
-
("effective", "ineffective"),
|
| 376 |
-
("success", "failure"),
|
| 377 |
-
("benefit", "harm"),
|
| 378 |
-
("positive", "negative"),
|
| 379 |
-
("growth", "decline")
|
| 380 |
-
]
|
| 381 |
-
|
| 382 |
-
for i in range(len(results)):
|
| 383 |
-
for j in range(i + 1, len(results)):
|
| 384 |
-
desc1 = results[i].get('description', '').lower()
|
| 385 |
-
desc2 = results[j].get('description', '').lower()
|
| 386 |
-
|
| 387 |
-
for word1, word2 in opposite_pairs:
|
| 388 |
-
if (word1 in desc1 and word2 in desc2) or (word2 in desc1 and word1 in desc2):
|
| 389 |
-
common_words = set(desc1.split()) & set(desc2.split())
|
| 390 |
-
if len(common_words) > 5:
|
| 391 |
-
contradictions.append({
|
| 392 |
-
'source1': results[i]['url'],
|
| 393 |
-
'source2': results[j]['url'],
|
| 394 |
-
'type': f"{word1} vs {word2}",
|
| 395 |
-
'desc1': results[i]['description'][:100],
|
| 396 |
-
'desc2': results[j]['description'][:100]
|
| 397 |
-
})
|
| 398 |
-
|
| 399 |
-
return contradictions
|
| 400 |
-
|
| 401 |
-
def brave_search(self, query: str) -> List[Dict]:
|
| 402 |
-
"""Brave Search API 호출 (기존 코드 재사용)"""
|
| 403 |
-
if self.test_mode or self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
| 404 |
-
test_results = []
|
| 405 |
-
for i in range(5):
|
| 406 |
-
test_results.append({
|
| 407 |
-
"title": f"Best Practices for {query} - Source {i+1}",
|
| 408 |
-
"description": f"Comprehensive guide on implementing {query} with proven methodologies and real-world examples from industry leaders.",
|
| 409 |
-
"url": f"https://example{i+1}.com/{query.replace(' ', '-')}",
|
| 410 |
-
"credibility_score": 0.7 + (i * 0.05)
|
| 411 |
-
})
|
| 412 |
-
return test_results
|
| 413 |
-
|
| 414 |
-
try:
|
| 415 |
-
params = {
|
| 416 |
-
"q": query,
|
| 417 |
-
"count": 20,
|
| 418 |
-
"safesearch": "moderate",
|
| 419 |
-
"freshness": "pw"
|
| 420 |
-
}
|
| 421 |
-
|
| 422 |
-
response = requests.get(
|
| 423 |
-
self.brave_url,
|
| 424 |
-
headers=self.create_brave_headers(),
|
| 425 |
-
params=params,
|
| 426 |
-
timeout=10
|
| 427 |
-
)
|
| 428 |
-
|
| 429 |
-
if response.status_code == 200:
|
| 430 |
-
data = response.json()
|
| 431 |
-
results = []
|
| 432 |
-
for item in data.get("web", {}).get("results", [])[:20]:
|
| 433 |
-
result = {
|
| 434 |
-
"title": item.get("title", ""),
|
| 435 |
-
"description": item.get("description", ""),
|
| 436 |
-
"url": item.get("url", ""),
|
| 437 |
-
"published": item.get("published", "")
|
| 438 |
-
}
|
| 439 |
-
result["credibility_score"] = self.calculate_credibility_score(result)
|
| 440 |
-
results.append(result)
|
| 441 |
-
|
| 442 |
-
results.sort(key=lambda x: x['credibility_score'], reverse=True)
|
| 443 |
-
return results
|
| 444 |
-
else:
|
| 445 |
-
logger.error(f"Brave API 오류: {response.status_code}")
|
| 446 |
-
return []
|
| 447 |
-
|
| 448 |
-
except Exception as e:
|
| 449 |
-
logger.error(f"Brave 검색 중 오류: {str(e)}")
|
| 450 |
-
return []
|
| 451 |
-
|
| 452 |
-
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
|
| 453 |
-
"""테스트 모드에서 스트리밍 시뮬레이션"""
|
| 454 |
-
words = text.split()
|
| 455 |
-
for i in range(0, len(words), 3):
|
| 456 |
-
chunk = " ".join(words[i:i+3])
|
| 457 |
-
yield chunk + " "
|
| 458 |
-
time.sleep(0.05)
|
| 459 |
-
|
| 460 |
-
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]:
|
| 461 |
-
"""스트리밍 LLM API 호출"""
|
| 462 |
-
|
| 463 |
-
if self.test_mode:
|
| 464 |
-
logger.info(f"테스트 모드 스트리밍 - Role: {role}")
|
| 465 |
-
# test_responses 딕셔너리를 메서드 내부에 정의
|
| 466 |
-
test_responses = {
|
| 467 |
-
"supervisor_initial": """이 질문에 대한 거시적 분석을 제시하겠습니다.
|
| 468 |
-
|
| 469 |
-
**1. 문제의 본질 파악**
|
| 470 |
-
사용자는 실용적이고 즉시 적용 가능한 해결책을 원하고 있습니다. 단순한 이론이나 개념이 아닌, 실제로 구현 가능한 구체적인 방안이 필요합니다.
|
| 471 |
-
|
| 472 |
-
**2. 전략적 프레임워크**
|
| 473 |
-
- 단기 목표: 즉시 실행 가능한 quick win 솔루션 도출
|
| 474 |
-
- 중기 목표: 지속 가능한 개선 체계 구축
|
| 475 |
-
- 장기 목표: 혁신적 변화를 통한 경쟁 우위 확보
|
| 476 |
-
|
| 477 |
-
**3. 제약사항 및 맥락**
|
| 478 |
-
- 기존 리소스와 인프라 활용 극대화
|
| 479 |
-
- 최소한의 투자로 최대 효과 달성
|
| 480 |
-
- 실무진이 바로 이해하고 실행할 수 있는 수준
|
| 481 |
-
|
| 482 |
-
**4. 성공 기준**
|
| 483 |
-
- 측정 가능한 개선 지표 (30% 이상 향상)
|
| 484 |
-
- 3개월 내 가시적 성과 달성
|
| 485 |
-
- ROI 200% 이상 달성""",
|
| 486 |
-
|
| 487 |
-
"creator": """혁신적인 아이디어를 제시하겠습니다.
|
| 488 |
-
|
| 489 |
-
**🚀 아이디어 1: AI 기반 자동 최적화 시스템**
|
| 490 |
-
- 독창성: 머신러닝이 스스로 시스템을 개선하는 자가 진화 시스템
|
| 491 |
-
- 영향력: 인간 개입 없이 24/7 성능 향상, 90% 효율성 증가 가능
|
| 492 |
-
- 필요 리소스: 클라우드 컴퓨팅, ML 엔지니어 1명
|
| 493 |
-
- 실현 가능성: 8/10
|
| 494 |
-
|
| 495 |
-
**💡 아이디어 2: 크라우드소싱 혁신 플랫폼**
|
| 496 |
-
- 독창성: 전 직원이 참여하는 실시간 개선 아이디어 시장
|
| 497 |
-
- 영향력: 집단 지성 활용으로 혁신 속도 10배 가속
|
| 498 |
-
- 필요 리소스: 웹 플랫폼, 인센티브 예산
|
| 499 |
-
- 실현 가능성: 9/10
|
| 500 |
-
|
| 501 |
-
**🔄 아이디어 3: 디지털 트윈 시뮬레이션**
|
| 502 |
-
- 독창성: 가상 환경에서 모든 시나리오를 사전 테스트
|
| 503 |
-
- 영향력: 리스크 80% 감소, 실패 비용 제로화
|
| 504 |
-
- 필요 리소스: 시뮬레이션 소프트웨어, 데이터 분석가
|
| 505 |
-
- 실현 가능성: 7/10
|
| 506 |
-
|
| 507 |
-
**🌐 아이디어 4: 블록체인 기반 프로세스 자동화**
|
| 508 |
-
- 독창성: 신뢰 기반 자동 실행 스마트 컨트랙트
|
| 509 |
-
- 영향력: 중개 비용 제거, 처리 시간 95% 단축
|
| 510 |
-
- 필요 리소스: 블록체인 개발자, 네트워크 인프라
|
| 511 |
-
- 실현 가능성: 6/10
|
| 512 |
-
|
| 513 |
-
**🧬 아이디어 5: 생체모방 알고리즘 적용**
|
| 514 |
-
- 독창성: 자연의 최적화 원리를 비즈니스에 적용
|
| 515 |
-
- 영향력: 예측 불가능한 환경에서도 적응력 극대화
|
| 516 |
-
- 필요 리소스: R&D 팀, 실험 환경
|
| 517 |
-
- 실현 가능성: 5/10
|
| 518 |
-
|
| 519 |
-
**시너지 효과**
|
| 520 |
-
아이디어 1+2 결합: AI가 크라우드소싱 아이디어를 자동 평가하고 구현
|
| 521 |
-
아이디어 3+4 결합: 블록체인으로 검증된 디지털 트윈 결과 자동 실행""",
|
| 522 |
-
|
| 523 |
-
"supervisor_ideation_review": """창조자 AI의 아이디어를 검토한 결과입니다.
|
| 524 |
-
|
| 525 |
-
**전략적 평가**
|
| 526 |
-
1. AI 기반 자동 최적화 시스템 - ⭐⭐⭐⭐⭐
|
| 527 |
-
- 즉시 실행 가능하고 ROI가 명확함
|
| 528 |
-
- 기존 인프라 활용 가능
|
| 529 |
-
|
| 530 |
-
2. 크라우드소싱 혁신 플랫폼 - ⭐⭐⭐⭐⭐
|
| 531 |
-
- 조직 문화 개선과 혁신 동시 달성
|
| 532 |
-
- 빠른 구현과 낮은 리스크
|
| 533 |
-
|
| 534 |
-
3. 디지털 트윈 시뮬레이션 - ⭐⭐⭐⭐
|
| 535 |
-
- 중장기적 가치가 높음
|
| 536 |
-
- 초기 투자 대비 효과 검증 필요
|
| 537 |
-
|
| 538 |
-
**선별된 아이디어**
|
| 539 |
-
1, 2, 3번 아이디어를 중심으로 진행 권장
|
| 540 |
-
|
| 541 |
-
**조사 필요 사항**
|
| 542 |
-
- 성공 사례와 구현 방법론
|
| 543 |
-
- 필요 기술 스택과 도구
|
| 544 |
-
- 예상 비용과 ROI 데이터
|
| 545 |
-
- 산업별 적용 사례
|
| 546 |
-
|
| 547 |
-
[검색 키워드]: AI automation implementation case studies, crowdsourcing innovation platform examples, digital twin ROI analysis, machine learning optimization tools, employee innovation engagement systems""",
|
| 548 |
-
|
| 549 |
-
"researcher": """조사 결과를 종합하여 보고합니다.
|
| 550 |
-
|
| 551 |
-
**1. AI 자동 최적화 시스템 구현 사례 (신뢰도 0.92)**
|
| 552 |
-
- Google: AutoML로 모델 성능 40% 개선, 개발 시간 90% 단축
|
| 553 |
-
- Netflix: 실시간 최적화로 스트리밍 품질 35% 향상
|
| 554 |
-
- 구현 도구: TensorFlow Extended, AutoKeras, H2O.ai
|
| 555 |
-
- 평균 ROI: 6개월 내 250%
|
| 556 |
-
- 출처: Google AI Blog, Netflix Tech Blog
|
| 557 |
-
|
| 558 |
-
**2. 크라우드소싱 혁신 플랫폼 성공 사례 (신뢰도 0.88)**
|
| 559 |
-
- P&G Connect+Develop: 외부 혁신으로 R&D 생산성 60% 향상
|
| 560 |
-
- Lego Ideas: 고객 아이디어로 신제품 출시 주기 50% 단축
|
| 561 |
-
- 플랫폼: IdeaScale, Brightidea, Spigit
|
| 562 |
-
- 평균 참여율: 직원의 75%
|
| 563 |
-
- 출처: Harvard Business Review, MIT Sloan Review
|
| 564 |
-
|
| 565 |
-
**3. 디지털 트윈 ROI 분석 (신뢰도 0.85)**
|
| 566 |
-
- GE: 예측 정비로 다운타임 20% 감소, 연간 $1.6B 절감
|
| 567 |
-
- Siemens: 제품 개발 주기 50% 단축
|
| 568 |
-
- 필요 기술: Azure Digital Twins, AWS IoT TwinMaker
|
| 569 |
-
- 초기 투자 회수: 평균 18개월
|
| 570 |
-
- 출처: Gartner Report 2024, IDC Research
|
| 571 |
-
|
| 572 |
-
**4. 실제 구현 가이드 (신뢰도 0.90)**
|
| 573 |
-
- 단계별 구현 로드맵 확보
|
| 574 |
-
- 오픈소스 도구 목록 및 비용 분석
|
| 575 |
-
- 필요 인력: 프로젝트당 3-5명
|
| 576 |
-
- 구현 기간: 3-6개월
|
| 577 |
-
|
| 578 |
-
**5. 최신 트렌드 (신뢰도 0.87)**
|
| 579 |
-
- 2024년 AI 자동화가 주류�� 부상
|
| 580 |
-
- Low-code/No-code 플랫폼으로 진입 장벽 낮아짐
|
| 581 |
-
- Edge AI로 실시간 최적화 가능
|
| 582 |
-
- 출처: McKinsey Digital Report 2024
|
| 583 |
-
|
| 584 |
-
**핵심 인사이트**
|
| 585 |
-
- 세 가지 아이디어 모두 검증된 성공 사례 존재
|
| 586 |
-
- 투자 대비 효과가 명확히 입증됨
|
| 587 |
-
- 기술적 구현 장벽이 낮아지고 있음
|
| 588 |
-
- 빠른 실행이 경쟁 우위의 핵심""",
|
| 589 |
-
|
| 590 |
-
"evaluator_research": """조사 결과를 객관적으로 평가합니다.
|
| 591 |
-
|
| 592 |
-
**실현 가능성 평가**
|
| 593 |
-
1. AI 자동 최적화 시스템: 9/10
|
| 594 |
-
- 근거: 다수의 성공 사례, 명확한 ROI, 기술 성숙도 높음
|
| 595 |
-
- 리스크: 초기 데이터 품질, 내부 저항
|
| 596 |
-
- ROI 예측: 6개월 내 250% (조사 결과 검증됨)
|
| 597 |
-
|
| 598 |
-
2. 크라우드소싱 혁신 플랫폼: 9/10
|
| 599 |
-
- 근거: 즉시 구현 가능, 낮은 기술 장벽
|
| 600 |
-
- 리스크: 참여도 저하, 아이디어 품질 관리
|
| 601 |
-
- ROI 예측: 1년 내 180%
|
| 602 |
-
|
| 603 |
-
3. 디지털 트윈: 7/10
|
| 604 |
-
- 근거: 높은 잠재력, 장기적 가치
|
| 605 |
-
- 리스크: 초기 투자 규모, 기술 복잡도
|
| 606 |
-
- ROI 예측: 18개월 내 200%
|
| 607 |
-
|
| 608 |
-
**조사 신뢰성 평가**
|
| 609 |
-
- 출처 신뢰도: 평균 0.88 (매우 높음)
|
| 610 |
-
- 정보 충분성: 85% (실행에 충분)
|
| 611 |
-
- 추가 필요 정보: 산업별 세부 사례, 실패 요인 분석
|
| 612 |
-
|
| 613 |
-
**최종 추천**
|
| 614 |
-
1순위: AI 자동 최적화 + 크라우드소싱 통합 접근
|
| 615 |
-
- 두 방안을 결합하여 시너지 극대화
|
| 616 |
-
- 단계적 구현으로 리스크 최소화
|
| 617 |
-
- 3개월 내 가시적 성과 가능
|
| 618 |
-
|
| 619 |
-
2순위: 디지털 트윈 (중장기 프로젝트로 병행)""",
|
| 620 |
-
|
| 621 |
-
"supervisor_execution": """평가 결과를 바탕으로 구체적인 실행 지시를 내립니다.
|
| 622 |
-
|
| 623 |
-
**통합 실행 전략**
|
| 624 |
-
AI 자동 최적화와 크라우드소싱을 결합한 "지능형 혁신 시스템" 구축
|
| 625 |
-
|
| 626 |
-
**1단계: 기반 구축 (1-2주차)**
|
| 627 |
-
- AI 자동 최적화 파일럿 프로젝트 선정
|
| 628 |
-
- 크라우드소싱 플랫폼 도구 선정 (IdeaScale 추천)
|
| 629 |
-
- 프로젝트팀 구성: PM 1명, ML 엔지니어 2명, 플랫폼 관리자 1명
|
| 630 |
-
- 초기 예산: $50,000
|
| 631 |
-
|
| 632 |
-
**2단계: 파일럿 실행 (3-6주차)**
|
| 633 |
-
- 선정 부서에서 AI 최적화 테스트
|
| 634 |
-
- 전사 아이디어 공모 시작
|
| 635 |
-
- 주간 성과 측정 및 조정
|
| 636 |
-
- 리스크: 데이터 품질 → 대응: 데이터 정제 자동화
|
| 637 |
-
|
| 638 |
-
**3단계: 통합 및 확장 (7-12주차)**
|
| 639 |
-
- AI가 크라우드소싱 아이디어 자동 평가
|
| 640 |
-
- 최우수 아이디어 자동 시뮬레이션
|
| 641 |
-
- 단계적 전사 확대
|
| 642 |
-
- 성과 지표: 효율성 30% 향상, 혁신 아이디어 100개/월
|
| 643 |
-
|
| 644 |
-
**리스크 대응 계획**
|
| 645 |
-
- 기술적 문제: 24/7 모니터링, 롤백 계획
|
| 646 |
-
- 참여 저조: 게임화, 인센티브 강화
|
| 647 |
-
- 품질 이슈: AI 기반 품질 검증
|
| 648 |
-
|
| 649 |
-
**성과 측정**
|
| 650 |
-
- 주간: 시스템 성능, 참여율
|
| 651 |
-
- 월간: ROI, 혁신 지표
|
| 652 |
-
- 분기: 전략적 영향 평가""",
|
| 653 |
-
|
| 654 |
-
"executor": """즉시 실행 가능한 구체적 계획을 제시합니다.
|
| 655 |
-
|
| 656 |
-
**🚀 1주차: 킥오프 및 환경 구축**
|
| 657 |
-
|
| 658 |
-
월요일-화요일: 프로젝트팀 구성 및 환경 설정
|
| 659 |
-
```python
|
| 660 |
-
# AI 최적화 환경 설정 스크립트
|
| 661 |
-
import tensorflow as tf
|
| 662 |
-
from tensorflow import keras
|
| 663 |
-
import autokeras as ak
|
| 664 |
-
|
| 665 |
-
# 자동 최적화 파이프라인 설정
|
| 666 |
-
class AutoOptimizer:
|
| 667 |
-
def __init__(self):
|
| 668 |
-
self.model = ak.AutoModel(
|
| 669 |
-
project_name='auto_optimization',
|
| 670 |
-
max_trials=100
|
| 671 |
-
)
|
| 672 |
-
|
| 673 |
-
def optimize(self, data):
|
| 674 |
-
# 자동 하이퍼파라미터 튜닝
|
| 675 |
-
self.model.fit(data['X'], data['y'])
|
| 676 |
-
return self.model.evaluate(data['X_test'], data['y_test'])
|
| 677 |
-
```
|
| 678 |
-
|
| 679 |
-
수요일-금요일: 크라우드소싱 플랫폼 구축
|
| 680 |
-
- IdeaScale 계정 설정 및 커스터마이징
|
| 681 |
-
- 직원 온보딩 자료 작성
|
| 682 |
-
- 평가 기준 및 보상 체계 수립
|
| 683 |
-
|
| 684 |
-
**📊 2-3주차: 파일럿 프로그램 실행**
|
| 685 |
-
|
| 686 |
-
데이터 수집 및 AI 모델 훈련:
|
| 687 |
-
```python
|
| 688 |
-
# 실시간 성능 모니터링 대시보드
|
| 689 |
-
import dash
|
| 690 |
-
import plotly.graph_objs as go
|
| 691 |
-
|
| 692 |
-
app = dash.Dash(__name__)
|
| 693 |
-
app.layout = html.Div([
|
| 694 |
-
dcc.Graph(id='live-performance'),
|
| 695 |
-
dcc.Interval(id='graph-update', interval=1000)
|
| 696 |
-
])
|
| 697 |
-
|
| 698 |
-
@app.callback(Output('live-performance', 'figure'),
|
| 699 |
-
[Input('graph-update', 'n_intervals')])
|
| 700 |
-
def update_metrics(n):
|
| 701 |
-
# 실시간 성능 지표 업데이트
|
| 702 |
-
return create_performance_dashboard()
|
| 703 |
-
```
|
| 704 |
-
|
| 705 |
-
크라우드소싱 캠페인 런칭:
|
| 706 |
-
- 첫 주 챌린지: "효율성 10% 개선 아이디어"
|
| 707 |
-
- 일일 리더보드 및 포인트 시스템
|
| 708 |
-
- AI 자동 아이디어 분류 및 초기 평가
|
| 709 |
-
|
| 710 |
-
**🔧 4-6주차: 통합 시스템 구현**
|
| 711 |
-
|
| 712 |
-
AI-크라우드소싱 통합 모듈:
|
| 713 |
-
```python
|
| 714 |
-
class InnovationEngine:
|
| 715 |
-
def __init__(self):
|
| 716 |
-
self.ai_evaluator = AIIdeaEvaluator()
|
| 717 |
-
self.crowd_platform = CrowdsourcingPlatform()
|
| 718 |
-
|
| 719 |
-
def process_idea(self, idea):
|
| 720 |
-
# 1. AI 초기 평가
|
| 721 |
-
score = self.ai_evaluator.evaluate(idea)
|
| 722 |
-
|
| 723 |
-
# 2. 유망 아이디어 자동 시뮬레이션
|
| 724 |
-
if score > 0.7:
|
| 725 |
-
simulation_result = self.run_simulation(idea)
|
| 726 |
-
|
| 727 |
-
# 3. 실행 우선순위 자동 배정
|
| 728 |
-
return self.prioritize_execution(idea, score, simulation_result)
|
| 729 |
-
```
|
| 730 |
-
|
| 731 |
-
**📈 예상 산출물**
|
| 732 |
-
1. 구동 가능한 AI 최적화 시스템
|
| 733 |
-
2. 활성화된 크라우드소싱 플랫폼
|
| 734 |
-
3. 통합 대시보드 및 분석 도구
|
| 735 |
-
4. 첫 달 목표: 50개 아이디어, 5개 구현, 15% 효율성 개선""",
|
| 736 |
-
|
| 737 |
-
"evaluator_execution": """실행 계획을 평가합니다.
|
| 738 |
-
|
| 739 |
-
**계획 완성도: 8.5/10**
|
| 740 |
-
|
| 741 |
-
**강점**
|
| 742 |
-
- 즉시 실행 가능한 코드와 구체적 일정 제공
|
| 743 |
-
- 단계별 명확한 목표와 산출물 정의
|
| 744 |
-
- 기술 스택이 검증되고 실용적임
|
| 745 |
-
|
| 746 |
-
**개선 필요사항**
|
| 747 |
-
1. 데이터 보안 및 프라이버시 대책 미흡
|
| 748 |
-
- 추가 필요: GDPR 준수 체크리스트, 데이터 암호화 방안
|
| 749 |
-
|
| 750 |
-
2. 변화 관리 계획 부족
|
| 751 |
-
- 추가 필요: 직원 교육 프로그램, 저항 관리 전략
|
| 752 |
-
|
| 753 |
-
3. 백업 및 복구 계획 누락
|
| 754 |
-
- 추가 필요: 시스템 장애 시 BCP, 데이터 백업 주기
|
| 755 |
-
|
| 756 |
-
**실행 상 예상 문제점**
|
| 757 |
-
1. 초기 데이터 부족 → 해결: 합성 데이터 생성 또는 전이학습
|
| 758 |
-
2. 직원 참여 저조 → 해결: 챔피언 그룹 육성, 조기 성공 사례 홍보
|
| 759 |
-
3. 기술 통합 복잡도 → 해결: 마이크로서비스 아키텍처 채택
|
| 760 |
-
|
| 761 |
-
**추가 제안**
|
| 762 |
-
- A/B 테스트 프레임워크 구축
|
| 763 |
-
- 실패 시 빠른 피벗을 위한 의사결정 체계
|
| 764 |
-
- 외부 전문가 자문단 구성
|
| 765 |
-
- 경쟁사 벤치마킹 정기 실시
|
| 766 |
-
|
| 767 |
-
**품질 기준**
|
| 768 |
-
- 코드 커버리지 80% 이상
|
| 769 |
-
- 응답 시간 200ms 이하
|
| 770 |
-
- 시스템 가용성 99.9%
|
| 771 |
-
- 사용자 만족도 4.5/5 이상""",
|
| 772 |
-
|
| 773 |
-
"supervisor_final": """평가를 바탕으로 최종 개선 지시를 내립니다.
|
| 774 |
-
|
| 775 |
-
**필수 보완 사항**
|
| 776 |
-
|
| 777 |
-
1. **보안 및 컴플라이언스 강화**
|
| 778 |
-
- GDPR/CCPA 준수 체크리스트 즉시 작성
|
| 779 |
-
- 전체 데이터 플로우 암호화 구현
|
| 780 |
-
- 접근 권한 관리 시스템 구축
|
| 781 |
-
|
| 782 |
-
2. **변화 관리 프로그램 추가**
|
| 783 |
-
- 1주차에 전직원 타운홀 미팅 실시
|
| 784 |
-
- 부서별 챔피언 선정 및 인센티브 제공
|
| 785 |
-
- 주간 성공 사례 공유 세션 운영
|
| 786 |
-
|
| 787 |
-
3. **리스크 관리 체계 구축**
|
| 788 |
-
- 24/7 모니터링 대시보드 구현
|
| 789 |
-
- 자동 롤백 시스템 구축
|
| 790 |
-
- 핫라인 및 긴급 대응팀 구성
|
| 791 |
-
|
| 792 |
-
**품질 보증 요구사항**
|
| 793 |
-
- 모든 코드는 peer review 필수
|
| 794 |
-
- 자동화된 테스트 커버리지 85% 이상
|
| 795 |
-
- 일일 스탠드업으로 진행상황 체크
|
| 796 |
-
|
| 797 |
-
**성공을 위한 핵심 요소**
|
| 798 |
-
1. 경영진의 visible한 지원과 참여
|
| 799 |
-
2. Quick win 사례를 통한 모멘텀 구축
|
| 800 |
-
3. 지속적인 개선과 빠른 피드백 루프
|
| 801 |
-
4. 투명한 성과 공유와 보상
|
| 802 |
-
|
| 803 |
-
**최종 목표**
|
| 804 |
-
- 3개월 내 ROI 150% 달성
|
| 805 |
-
- 직원 참여율 80% 이상
|
| 806 |
-
- 시스템 안정성 99.9% 유지""",
|
| 807 |
-
|
| 808 |
-
"executor_final": """모든 피드백을 완전히 반영하여 최종 실행 가능 솔루션입니다.
|
| 809 |
-
|
| 810 |
-
# 🎯 지능형 혁신 시스템 구축 - 최종 실행 가이드
|
| 811 |
-
|
| 812 |
-
## 📋 Executive Summary
|
| 813 |
-
AI 자동 최적화와 크라우드소싱을 통합한 혁신 시스템으로 3개월 내 효율성 30% 향상, ROI 150% 달성을 목표로 합니다.
|
| 814 |
-
|
| 815 |
-
## 🚀 1주차: 보안 강화된 프로젝트 시작
|
| 816 |
-
|
| 817 |
-
### Day 1-2: 킥오프 및 보안 체계 구축
|
| 818 |
-
```python
|
| 819 |
-
# 보안 강화된 데이터 처리 파이프라인
|
| 820 |
-
from cryptography.fernet import Fernet
|
| 821 |
-
import hashlib
|
| 822 |
-
from datetime import datetime
|
| 823 |
-
|
| 824 |
-
class SecureDataPipeline:
|
| 825 |
-
def __init__(self):
|
| 826 |
-
self.key = Fernet.generate_key()
|
| 827 |
-
self.cipher = Fernet(self.key)
|
| 828 |
-
self.audit_log = []
|
| 829 |
-
|
| 830 |
-
def process_data(self, data, user_id):
|
| 831 |
-
# GDPR 준수 암호화
|
| 832 |
-
encrypted = self.cipher.encrypt(data.encode())
|
| 833 |
-
|
| 834 |
-
# 감사 로그
|
| 835 |
-
self.audit_log.append({
|
| 836 |
-
'user': user_id,
|
| 837 |
-
'action': 'data_process',
|
| 838 |
-
'timestamp': datetime.now(),
|
| 839 |
-
'data_hash': hashlib.sha256(data.encode()).hexdigest()
|
| 840 |
-
})
|
| 841 |
-
|
| 842 |
-
return self.run_optimization(encrypted)
|
| 843 |
-
|
| 844 |
-
def run_optimization(self, encrypted_data):
|
| 845 |
-
# 암호화된 상태에서 처리
|
| 846 |
-
decrypted = self.cipher.decrypt(encrypted_data)
|
| 847 |
-
# AI 최적화 로직
|
| 848 |
-
return optimized_result
|
| 849 |
-
```
|
| 850 |
-
|
| 851 |
-
### Day 3: 전직원 타운홀 미팅
|
| 852 |
-
**어젠다 (1시간)**
|
| 853 |
-
1. 비전 공유: CEO 발표 (10분)
|
| 854 |
-
2. 시스템 소개: 프로젝트 리더 (20분)
|
| 855 |
-
3. 혜택 설명: 직원 관점에서 (15분)
|
| 856 |
-
4. Q&A 및 피드백 (15분)
|
| 857 |
-
|
| 858 |
-
**변화 관리 자료**
|
| 859 |
-
```markdown
|
| 860 |
-
# 직원을 위한 혁신 시스템 가이드
|
| 861 |
-
|
| 862 |
-
## 당신에게 주는 혜택
|
| 863 |
-
✅ 아이디어가 즉시 실행됩니다
|
| 864 |
-
✅ 기여도에 따른 명확한 보상
|
| 865 |
-
✅ 반복 업무 자동화로 창의적 업무 집중
|
| 866 |
-
✅ 실시간 성과 확인 가능
|
| 867 |
-
|
| 868 |
-
## 참여 방법 (3단계)
|
| 869 |
-
1. 플랫폼 로그인 → 아이디어 제출
|
| 870 |
-
2. AI가 자동 평가 → 24시간 �� 피드백
|
| 871 |
-
3. 실행 및 보상 → 포인트/보너스 지급
|
| 872 |
-
```
|
| 873 |
-
|
| 874 |
-
### Day 4-5: 기술 인프라 구축
|
| 875 |
-
```python
|
| 876 |
-
# 통합 모니터링 대시보드
|
| 877 |
-
import dash
|
| 878 |
-
import plotly.graph_objs as go
|
| 879 |
-
from dash import dcc, html, Input, Output
|
| 880 |
-
import pandas as pd
|
| 881 |
-
|
| 882 |
-
class MonitoringDashboard:
|
| 883 |
-
def __init__(self):
|
| 884 |
-
self.app = dash.Dash(__name__)
|
| 885 |
-
self.setup_layout()
|
| 886 |
-
self.setup_callbacks()
|
| 887 |
-
|
| 888 |
-
def setup_layout(self):
|
| 889 |
-
self.app.layout = html.Div([
|
| 890 |
-
html.H1("지능형 혁신 시스템 대시보드"),
|
| 891 |
-
|
| 892 |
-
# 실시간 KPI
|
| 893 |
-
html.Div([
|
| 894 |
-
dcc.Graph(id='efficiency-gauge'),
|
| 895 |
-
dcc.Graph(id='participation-rate'),
|
| 896 |
-
dcc.Graph(id='roi-tracker'),
|
| 897 |
-
dcc.Graph(id='system-health')
|
| 898 |
-
], style={'display': 'flex'}),
|
| 899 |
-
|
| 900 |
-
# 알림 시스템
|
| 901 |
-
html.Div(id='alerts', className='alert-box'),
|
| 902 |
-
|
| 903 |
-
# 자동 업데이트
|
| 904 |
-
dcc.Interval(id='interval', interval=5000)
|
| 905 |
-
])
|
| 906 |
-
|
| 907 |
-
def setup_callbacks(self):
|
| 908 |
-
@self.app.callback(
|
| 909 |
-
[Output('efficiency-gauge', 'figure'),
|
| 910 |
-
Output('alerts', 'children')],
|
| 911 |
-
[Input('interval', 'n_intervals')]
|
| 912 |
-
)
|
| 913 |
-
def update_dashboard(n):
|
| 914 |
-
# 실시간 메트릭 수집
|
| 915 |
-
metrics = self.collect_metrics()
|
| 916 |
-
|
| 917 |
-
# 임계값 체크 및 알림
|
| 918 |
-
alerts = self.check_thresholds(metrics)
|
| 919 |
-
|
| 920 |
-
return self.create_gauge(metrics['efficiency']), alerts
|
| 921 |
-
```
|
| 922 |
-
|
| 923 |
-
## 📊 2-3주차: 스마트 파일럿 프로그램
|
| 924 |
-
|
| 925 |
-
### 크라우드소싱 게임화 시스템
|
| 926 |
-
```python
|
| 927 |
-
class GamificationEngine:
|
| 928 |
-
def __init__(self):
|
| 929 |
-
self.levels = {
|
| 930 |
-
'Novice': 0,
|
| 931 |
-
'Contributor': 100,
|
| 932 |
-
'Innovator': 500,
|
| 933 |
-
'Champion': 1000,
|
| 934 |
-
'Legend': 5000
|
| 935 |
-
}
|
| 936 |
-
self.badges = {
|
| 937 |
-
'first_idea': '첫 아이디어',
|
| 938 |
-
'week_streak': '주간 연속 참여',
|
| 939 |
-
'top_rated': '최고 평점',
|
| 940 |
-
'implemented': '아이디어 실행됨'
|
| 941 |
-
}
|
| 942 |
-
|
| 943 |
-
def process_contribution(self, user_id, idea):
|
| 944 |
-
points = self.calculate_points(idea)
|
| 945 |
-
badges = self.check_badges(user_id, idea)
|
| 946 |
-
level_up = self.check_level_up(user_id, points)
|
| 947 |
-
|
| 948 |
-
# 실시간 알림
|
| 949 |
-
if level_up:
|
| 950 |
-
self.notify_achievement(user_id, level_up)
|
| 951 |
-
|
| 952 |
-
return {
|
| 953 |
-
'points': points,
|
| 954 |
-
'badges': badges,
|
| 955 |
-
'level': self.get_user_level(user_id),
|
| 956 |
-
'ranking': self.get_ranking(user_id)
|
| 957 |
-
}
|
| 958 |
-
```
|
| 959 |
-
|
| 960 |
-
### AI 평가 및 시뮬레이션 엔진
|
| 961 |
-
```python
|
| 962 |
-
class AIInnovationEvaluator:
|
| 963 |
-
def __init__(self):
|
| 964 |
-
self.models = {
|
| 965 |
-
'feasibility': self.load_model('feasibility_model.h5'),
|
| 966 |
-
'impact': self.load_model('impact_model.h5'),
|
| 967 |
-
'cost': self.load_model('cost_model.h5')
|
| 968 |
-
}
|
| 969 |
-
|
| 970 |
-
def evaluate_idea(self, idea_text, metadata):
|
| 971 |
-
# NLP 처리
|
| 972 |
-
features = self.extract_features(idea_text)
|
| 973 |
-
|
| 974 |
-
# 다차원 평가
|
| 975 |
-
scores = {
|
| 976 |
-
'feasibility': self.models['feasibility'].predict(features),
|
| 977 |
-
'impact': self.models['impact'].predict(features),
|
| 978 |
-
'cost_efficiency': self.models['cost'].predict(features),
|
| 979 |
-
'innovation_index': self.calculate_innovation(features)
|
| 980 |
-
}
|
| 981 |
-
|
| 982 |
-
# 자동 시뮬레이션 트리거
|
| 983 |
-
if scores['feasibility'] > 0.7 and scores['impact'] > 0.8:
|
| 984 |
-
simulation_result = self.run_simulation(idea_text, metadata)
|
| 985 |
-
scores['simulation'] = simulation_result
|
| 986 |
-
|
| 987 |
-
return self.generate_report(scores, idea_text)
|
| 988 |
-
```
|
| 989 |
-
|
| 990 |
-
## 🔧 4-6주차: 고급 통합 및 최적화
|
| 991 |
-
|
| 992 |
-
### 자동 실행 파이프라인
|
| 993 |
-
```python
|
| 994 |
-
class AutoExecutionPipeline:
|
| 995 |
-
def __init__(self):
|
| 996 |
-
self.executor = TaskExecutor()
|
| 997 |
-
self.validator = ResultValidator()
|
| 998 |
-
self.rollback = RollbackManager()
|
| 999 |
-
|
| 1000 |
-
def execute_approved_idea(self, idea_id):
|
| 1001 |
-
try:
|
| 1002 |
-
# 실행 계획 생성
|
| 1003 |
-
plan = self.create_execution_plan(idea_id)
|
| 1004 |
-
|
| 1005 |
-
# 단계별 실행 with 체크포인트
|
| 1006 |
-
for step in plan.steps:
|
| 1007 |
-
result = self.executor.execute(step)
|
| 1008 |
-
|
| 1009 |
-
if not self.validator.validate(result):
|
| 1010 |
-
self.rollback.restore_checkpoint(step.checkpoint)
|
| 1011 |
-
return self.handle_failure(step, result)
|
| 1012 |
-
|
| 1013 |
-
# 실시간 진행상황 업데이트
|
| 1014 |
-
self.update_progress(idea_id, step.completion_rate)
|
| 1015 |
-
|
| 1016 |
-
return self.finalize_execution(idea_id)
|
| 1017 |
-
|
| 1018 |
-
except Exception as e:
|
| 1019 |
-
self.emergency_rollback(idea_id)
|
| 1020 |
-
self.alert_team(e)
|
| 1021 |
-
```
|
| 1022 |
-
|
| 1023 |
-
### 지속적 개선 시스템
|
| 1024 |
-
```python
|
| 1025 |
-
class ContinuousImprovement:
|
| 1026 |
-
def __init__(self):
|
| 1027 |
-
self.ml_pipeline = MLPipeline()
|
| 1028 |
-
self.feedback_loop = FeedbackLoop()
|
| 1029 |
-
|
| 1030 |
-
def daily_optimization(self):
|
| 1031 |
-
# 매일 자정 실행
|
| 1032 |
-
performance_data = self.collect_daily_metrics()
|
| 1033 |
-
|
| 1034 |
-
# 모델 재훈련
|
| 1035 |
-
self.ml_pipeline.retrain(performance_data)
|
| 1036 |
-
|
| 1037 |
-
# A/B 테스트 자동 설정
|
| 1038 |
-
experiments = self.design_experiments(performance_data)
|
| 1039 |
-
|
| 1040 |
-
for exp in experiments:
|
| 1041 |
-
self.run_ab_test(exp)
|
| 1042 |
-
|
| 1043 |
-
# 인사이트 생성
|
| 1044 |
-
insights = self.generate_insights(performance_data)
|
| 1045 |
-
self.distribute_report(insights)
|
| 1046 |
-
```
|
| 1047 |
-
|
| 1048 |
-
## 📈 성과 측정 및 보고 체계
|
| 1049 |
-
|
| 1050 |
-
### 실시간 KPI 대시보드
|
| 1051 |
-
```python
|
| 1052 |
-
kpi_metrics = {
|
| 1053 |
-
'efficiency_gain': {
|
| 1054 |
-
'current': 0,
|
| 1055 |
-
'target': 30,
|
| 1056 |
-
'unit': '%'
|
| 1057 |
-
},
|
| 1058 |
-
'participation_rate': {
|
| 1059 |
-
'current': 0,
|
| 1060 |
-
'target': 80,
|
| 1061 |
-
'unit': '%'
|
| 1062 |
-
},
|
| 1063 |
-
'ideas_per_month': {
|
| 1064 |
-
'current': 0,
|
| 1065 |
-
'target': 100,
|
| 1066 |
-
'unit': 'count'
|
| 1067 |
-
},
|
| 1068 |
-
'roi': {
|
| 1069 |
-
'current': 0,
|
| 1070 |
-
'target': 150,
|
| 1071 |
-
'unit': '%'
|
| 1072 |
-
},
|
| 1073 |
-
'system_uptime': {
|
| 1074 |
-
'current': 0,
|
| 1075 |
-
'target': 99.9,
|
| 1076 |
-
'unit': '%'
|
| 1077 |
-
}
|
| 1078 |
-
}
|
| 1079 |
-
|
| 1080 |
-
# 자동 보고서 생성
|
| 1081 |
-
def generate_weekly_report():
|
| 1082 |
-
report = f\"\"\"
|
| 1083 |
-
# 주간 성과 보고서 - {datetime.now().strftime('%Y-%m-%d')}
|
| 1084 |
-
|
| 1085 |
-
## 핵심 성과
|
| 1086 |
-
- 효율성 향상: {kpi_metrics['efficiency_gain']['current']}%
|
| 1087 |
-
- 직원 참여율: {kpi_metrics['participation_rate']['current']}%
|
| 1088 |
-
- 제출된 아이디어: {kpi_metrics['ideas_per_month']['current']}개
|
| 1089 |
-
- ROI: {kpi_metrics['roi']['current']}%
|
| 1090 |
-
|
| 1091 |
-
## 주요 성공 사례
|
| 1092 |
-
{get_success_stories()}
|
| 1093 |
-
|
| 1094 |
-
## 다음 주 계획
|
| 1095 |
-
{get_next_week_plan()}
|
| 1096 |
-
\"\"\"
|
| 1097 |
-
return report
|
| 1098 |
-
```
|
| 1099 |
-
|
| 1100 |
-
## 🛡️ 리스크 관리 및 비상 계획
|
| 1101 |
-
|
| 1102 |
-
### 자동 백업 및 복구
|
| 1103 |
-
```bash
|
| 1104 |
-
#!/bin/bash
|
| 1105 |
-
# 시간별 자동 백업 스크립트
|
| 1106 |
-
BACKUP_DIR="/secure/backups/$(date +%Y%m%d)"
|
| 1107 |
-
mkdir -p $BACKUP_DIR
|
| 1108 |
-
|
| 1109 |
-
# 데이터베이스 백업
|
| 1110 |
-
pg_dump -U postgres innovation_db > $BACKUP_DIR/db_backup_$(date +%H%M).sql
|
| 1111 |
-
|
| 1112 |
-
# 애플리케이션 상태 백업
|
| 1113 |
-
kubectl get all --all-namespaces -o yaml > $BACKUP_DIR/k8s_state_$(date +%H%M).yaml
|
| 1114 |
-
|
| 1115 |
-
# S3 업로드 (암호화)
|
| 1116 |
-
aws s3 cp $BACKUP_DIR s3://innovation-backups/ --recursive --sse
|
| 1117 |
-
```
|
| 1118 |
-
|
| 1119 |
-
### 24/7 모니터링 및 알림
|
| 1120 |
-
```python
|
| 1121 |
-
class AlertingSystem:
|
| 1122 |
-
def __init__(self):
|
| 1123 |
-
self.thresholds = {
|
| 1124 |
-
'response_time': 200, # ms
|
| 1125 |
-
'error_rate': 0.01, # 1%
|
| 1126 |
-
'cpu_usage': 80, # %
|
| 1127 |
-
'participation_drop': 20 # %
|
| 1128 |
-
}
|
| 1129 |
-
|
| 1130 |
-
def monitor(self):
|
| 1131 |
-
while True:
|
| 1132 |
-
metrics = self.collect_metrics()
|
| 1133 |
-
|
| 1134 |
-
for metric, value in metrics.items():
|
| 1135 |
-
if self.is_threshold_breached(metric, value):
|
| 1136 |
-
self.trigger_alert(metric, value)
|
| 1137 |
-
self.auto_remediate(metric)
|
| 1138 |
-
|
| 1139 |
-
time.sleep(60) # 1분마다 체크
|
| 1140 |
-
```
|
| 1141 |
-
|
| 1142 |
-
## 🎯 최종 체크리스트
|
| 1143 |
-
|
| 1144 |
-
### Week 1 완료 사항
|
| 1145 |
-
- [ ] 보안 인프라 구축 완료
|
| 1146 |
-
- [ ] 전직원 타운홀 미팅 실시
|
| 1147 |
-
- [ ] 챔피언 그룹 선정
|
| 1148 |
-
- [ ] 기본 시스템 배포
|
| 1149 |
-
|
| 1150 |
-
### Week 2-3 완료 사항
|
| 1151 |
-
- [ ] 파일럿 부서 선정 및 시작
|
| 1152 |
-
- [ ] 첫 아이디어 캠페인 런칭
|
| 1153 |
-
- [ ] AI 평가 시스템 가동
|
| 1154 |
-
- [ ] 첫 quick win 달성
|
| 1155 |
-
|
| 1156 |
-
### Week 4-6 완료 사항
|
| 1157 |
-
- [ ] 전사 확대 시작
|
| 1158 |
-
- [ ] 자동화 파이프라인 완성
|
| 1159 |
-
- [ ] KPI 목표 50% 달성
|
| 1160 |
-
- [ ] 첫 ROI 리포트 작성
|
| 1161 |
-
|
| 1162 |
-
## 💡 성공을 위한 팁
|
| 1163 |
-
1. 매일 아침 5분 스탠드업 미팅
|
| 1164 |
-
2. 주간 성공 사례 전사 공유
|
| 1165 |
-
3. 월간 혁신 어워드 시상
|
| 1166 |
-
4. 분기별 해커톤 개최
|
| 1167 |
-
|
| 1168 |
-
---
|
| 1169 |
-
*이 시스템은 지속적으로 진화합니다. 피드백은 [email protected]으로!*"""
|
| 1170 |
-
}
|
| 1171 |
-
|
| 1172 |
-
# 역할과 프롬프트에 따라 적절한 응답 선택
|
| 1173 |
-
if role == "supervisor" and "창조자 AI가 제시한" in messages[0]["content"]:
|
| 1174 |
-
response = test_responses["supervisor_ideation_review"]
|
| 1175 |
-
elif role == "supervisor" and "평가자 AI의 종합 평가" in messages[0]["content"]:
|
| 1176 |
-
response = test_responses["supervisor_execution"]
|
| 1177 |
-
elif role == "supervisor" and "평가자 AI의 실행 계획 평가" in messages[0]["content"]:
|
| 1178 |
-
response = test_responses["supervisor_final"]
|
| 1179 |
-
elif role == "supervisor":
|
| 1180 |
-
response = test_responses["supervisor_initial"]
|
| 1181 |
-
elif role == "creator":
|
| 1182 |
-
response = test_responses["creator"]
|
| 1183 |
-
elif role == "researcher":
|
| 1184 |
-
response = test_responses["researcher"]
|
| 1185 |
-
elif role == "evaluator" and "조사자 AI의 조사 결과" in messages[0]["content"]:
|
| 1186 |
-
response = test_responses["evaluator_research"]
|
| 1187 |
-
elif role == "evaluator":
|
| 1188 |
-
response = test_responses["evaluator_execution"]
|
| 1189 |
-
elif role == "executor" and "최종 솔루션" in messages[0]["content"]:
|
| 1190 |
-
response = test_responses["executor_final"]
|
| 1191 |
-
else:
|
| 1192 |
-
response = test_responses["executor"]
|
| 1193 |
-
|
| 1194 |
-
yield from self.simulate_streaming(response, role)
|
| 1195 |
-
return
|
| 1196 |
-
|
| 1197 |
-
# 실제 API 호출 (기존 코드와 동일)
|
| 1198 |
-
try:
|
| 1199 |
-
system_prompts = {
|
| 1200 |
-
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
| 1201 |
-
"creator": "당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다.",
|
| 1202 |
-
"researcher": "당신은 정보를 조사하고 체계적으로 정리하는 조사자 AI입니다.",
|
| 1203 |
-
"evaluator": "당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.",
|
| 1204 |
-
"executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다."
|
| 1205 |
-
}
|
| 1206 |
-
|
| 1207 |
-
full_messages = [
|
| 1208 |
-
{"role": "system", "content": system_prompts.get(role, "")},
|
| 1209 |
-
*messages
|
| 1210 |
-
]
|
| 1211 |
-
|
| 1212 |
-
payload = {
|
| 1213 |
-
"model": self.model_id,
|
| 1214 |
-
"messages": full_messages,
|
| 1215 |
-
"max_tokens": 2048,
|
| 1216 |
-
"temperature": 0.7,
|
| 1217 |
-
"top_p": 0.8,
|
| 1218 |
-
"stream": True,
|
| 1219 |
-
"stream_options": {"include_usage": True}
|
| 1220 |
-
}
|
| 1221 |
-
|
| 1222 |
-
logger.info(f"API 스트리밍 호출 시작 - Role: {role}")
|
| 1223 |
-
|
| 1224 |
-
response = requests.post(
|
| 1225 |
-
self.api_url,
|
| 1226 |
-
headers=self.create_headers(),
|
| 1227 |
-
json=payload,
|
| 1228 |
-
stream=True,
|
| 1229 |
-
timeout=10
|
| 1230 |
-
)
|
| 1231 |
-
|
| 1232 |
-
if response.status_code != 200:
|
| 1233 |
-
logger.error(f"API 오류: {response.status_code}")
|
| 1234 |
-
yield f"❌ API 오류 ({response.status_code}): {response.text[:200]}"
|
| 1235 |
-
return
|
| 1236 |
-
|
| 1237 |
-
for line in response.iter_lines():
|
| 1238 |
-
if line:
|
| 1239 |
-
line = line.decode('utf-8')
|
| 1240 |
-
if line.startswith("data: "):
|
| 1241 |
-
data = line[6:]
|
| 1242 |
-
if data == "[DONE]":
|
| 1243 |
-
break
|
| 1244 |
-
try:
|
| 1245 |
-
chunk = json.loads(data)
|
| 1246 |
-
if "choices" in chunk and chunk["choices"]:
|
| 1247 |
-
content = chunk["choices"][0].get("delta", {}).get("content", "")
|
| 1248 |
-
if content:
|
| 1249 |
-
yield content
|
| 1250 |
-
except json.JSONDecodeError:
|
| 1251 |
-
continue
|
| 1252 |
-
|
| 1253 |
-
except requests.exceptions.Timeout:
|
| 1254 |
-
yield "⏱️ API 호출 시간이 초과되었습니다. 다시 시도해주세요."
|
| 1255 |
-
except requests.exceptions.ConnectionError:
|
| 1256 |
-
yield "🔌 API 서버에 연결할 수 없습니다. 인터넷 연결을 확인해주세요."
|
| 1257 |
-
except Exception as e:
|
| 1258 |
-
logger.error(f"스트리밍 중 오류: {str(e)}")
|
| 1259 |
-
yield f"❌ 오류 발생: {str(e)}"
|
| 1260 |
-
|
| 1261 |
-
# 시스템 인스턴스 생성
|
| 1262 |
-
llm_system = LLMCollaborativeSystem()
|
| 1263 |
-
|
| 1264 |
-
# 내부 히스토리 관리
|
| 1265 |
-
internal_history = []
|
| 1266 |
-
|
| 1267 |
-
def process_query_streaming(user_query: str):
|
| 1268 |
-
"""향상된 협업 프로세스를 통한 쿼리 처리"""
|
| 1269 |
-
global internal_history
|
| 1270 |
-
|
| 1271 |
-
if not user_query:
|
| 1272 |
-
return "", "", "", "", "", "❌ 질문을 입력해주세요."
|
| 1273 |
-
|
| 1274 |
-
all_responses = {
|
| 1275 |
-
"supervisor": [],
|
| 1276 |
-
"creator": [],
|
| 1277 |
-
"researcher": [],
|
| 1278 |
-
"evaluator": [],
|
| 1279 |
-
"executor": []
|
| 1280 |
-
}
|
| 1281 |
-
|
| 1282 |
try:
|
| 1283 |
-
#
|
| 1284 |
-
|
| 1285 |
-
supervisor_initial_response = ""
|
| 1286 |
-
|
| 1287 |
-
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
| 1288 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1289 |
-
[{"role": "user", "content": supervisor_prompt}],
|
| 1290 |
-
"supervisor"
|
| 1291 |
-
):
|
| 1292 |
-
supervisor_initial_response += chunk
|
| 1293 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
| 1294 |
-
yield supervisor_text, "", "", "", "", "🔄 감독자 AI가 분석 중..."
|
| 1295 |
-
|
| 1296 |
-
all_responses["supervisor"].append(supervisor_initial_response)
|
| 1297 |
-
|
| 1298 |
-
# 2단계: 창조자 AI 혁신적 아이디어 생성
|
| 1299 |
-
creator_prompt = llm_system.create_creator_prompt(user_query, supervisor_initial_response)
|
| 1300 |
-
creator_response = ""
|
| 1301 |
-
|
| 1302 |
-
creator_text = "[혁신 아이디어] 🔄 생성 중...\n"
|
| 1303 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1304 |
-
[{"role": "user", "content": creator_prompt}],
|
| 1305 |
-
"creator"
|
| 1306 |
-
):
|
| 1307 |
-
creator_response += chunk
|
| 1308 |
-
creator_text = f"[혁신 아이디어] - {datetime.now().strftime('%H:%M:%S')}\n{creator_response}"
|
| 1309 |
-
yield supervisor_text, creator_text, "", "", "", "💡 창조자 AI가 아이디어 생성 중..."
|
| 1310 |
|
| 1311 |
-
|
| 1312 |
-
|
| 1313 |
-
|
| 1314 |
-
supervisor_review_prompt = llm_system.create_supervisor_ideation_review_prompt(user_query, creator_response)
|
| 1315 |
-
supervisor_review_response = ""
|
| 1316 |
-
|
| 1317 |
-
supervisor_text += "\n\n---\n\n[아이디어 검토] 🔄 생성 중...\n"
|
| 1318 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1319 |
-
[{"role": "user", "content": supervisor_review_prompt}],
|
| 1320 |
-
"supervisor"
|
| 1321 |
-
):
|
| 1322 |
-
supervisor_review_response += chunk
|
| 1323 |
-
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_review_response}"
|
| 1324 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
| 1325 |
-
yield supervisor_text, creator_text, "", "", "", "🎯 감독자 AI가 검토 중..."
|
| 1326 |
-
|
| 1327 |
-
all_responses["supervisor"].append(supervisor_review_response)
|
| 1328 |
-
|
| 1329 |
-
# 키워드 추출
|
| 1330 |
-
keywords = llm_system.extract_keywords(supervisor_review_response)
|
| 1331 |
-
logger.info(f"추출된 키워드: {keywords}")
|
| 1332 |
|
| 1333 |
-
#
|
| 1334 |
-
|
| 1335 |
-
|
|
|
|
| 1336 |
|
| 1337 |
-
|
| 1338 |
-
|
| 1339 |
|
| 1340 |
-
|
| 1341 |
-
|
| 1342 |
-
|
| 1343 |
-
|
| 1344 |
-
|
| 1345 |
-
researcher_text += f"✓ '{keyword}' 검색 완료 ({len(results)}개 결과)\n"
|
| 1346 |
-
yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
| 1347 |
|
| 1348 |
-
synonyms = llm_system.generate_synonyms(keyword)
|
| 1349 |
-
for synonym in synonyms:
|
| 1350 |
-
syn_results = llm_system.brave_search(f"{keyword} {synonym}")
|
| 1351 |
-
if syn_results:
|
| 1352 |
-
search_results[f"{keyword} ({synonym})"] = syn_results
|
| 1353 |
-
total_search_count += len(syn_results)
|
| 1354 |
-
researcher_text += f"✓ 동의어 '{synonym}' 검색 완료 ({len(syn_results)}개 결과)\n"
|
| 1355 |
-
yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 동의어 '{synonym}' 검색 중..."
|
| 1356 |
-
|
| 1357 |
-
researcher_text += f"\n📊 총 {total_search_count}개의 검색 결과 수집 완료\n"
|
| 1358 |
-
|
| 1359 |
-
# 5단계: 조사자 AI가 검색 결과 정리
|
| 1360 |
-
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_review_response, search_results)
|
| 1361 |
-
researcher_response = ""
|
| 1362 |
-
|
| 1363 |
-
researcher_text = "[조사 결과 정리] 🔄 생성 중...\n"
|
| 1364 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1365 |
-
[{"role": "user", "content": researcher_prompt}],
|
| 1366 |
-
"researcher"
|
| 1367 |
-
):
|
| 1368 |
-
researcher_response += chunk
|
| 1369 |
-
researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
| 1370 |
-
yield supervisor_text, creator_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
| 1371 |
-
|
| 1372 |
-
all_responses["researcher"].append(researcher_response)
|
| 1373 |
-
|
| 1374 |
-
# 6단계: 평가자 AI가 조사 결과 평가
|
| 1375 |
-
evaluator_research_prompt = llm_system.create_evaluator_research_prompt(
|
| 1376 |
-
user_query, creator_response, researcher_response
|
| 1377 |
-
)
|
| 1378 |
-
evaluator_research_response = ""
|
| 1379 |
-
|
| 1380 |
-
evaluator_text = "[조사 결과 평가] 🔄 생성 중...\n"
|
| 1381 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1382 |
-
[{"role": "user", "content": evaluator_research_prompt}],
|
| 1383 |
-
"evaluator"
|
| 1384 |
-
):
|
| 1385 |
-
evaluator_research_response += chunk
|
| 1386 |
-
evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_research_response}"
|
| 1387 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "⚖️ 평가자 AI가 평�� 중..."
|
| 1388 |
-
|
| 1389 |
-
all_responses["evaluator"].append(evaluator_research_response)
|
| 1390 |
-
|
| 1391 |
-
# 7단계: 감독자 AI가 실행 지시
|
| 1392 |
-
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(
|
| 1393 |
-
user_query, evaluator_research_response
|
| 1394 |
-
)
|
| 1395 |
-
supervisor_execution_response = ""
|
| 1396 |
-
|
| 1397 |
-
supervisor_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[실행 지시] 🔄 생성 중...\n"
|
| 1398 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1399 |
-
[{"role": "user", "content": supervisor_execution_prompt}],
|
| 1400 |
-
"supervisor"
|
| 1401 |
-
):
|
| 1402 |
-
supervisor_execution_response += chunk
|
| 1403 |
-
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{supervisor_execution_response}"
|
| 1404 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
| 1405 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "🎯 감독자 AI가 지시 중..."
|
| 1406 |
-
|
| 1407 |
-
all_responses["supervisor"].append(supervisor_execution_response)
|
| 1408 |
-
|
| 1409 |
-
# 8단계: 실행자 AI가 초기 실행 계획 수립
|
| 1410 |
-
full_context = f"""
|
| 1411 |
-
창조자 AI의 아이디어:
|
| 1412 |
-
{creator_response}
|
| 1413 |
-
|
| 1414 |
-
조사자 AI의 조사 결과:
|
| 1415 |
-
{researcher_response}
|
| 1416 |
-
|
| 1417 |
-
평가자 AI의 평가:
|
| 1418 |
-
{evaluator_research_response}
|
| 1419 |
-
"""
|
| 1420 |
-
|
| 1421 |
-
executor_prompt = llm_system.create_executor_prompt(
|
| 1422 |
-
user_query, supervisor_execution_response, full_context
|
| 1423 |
-
)
|
| 1424 |
-
executor_response = ""
|
| 1425 |
-
|
| 1426 |
-
executor_text = "[초기 실행 계획] 🔄 생성 중...\n"
|
| 1427 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1428 |
-
[{"role": "user", "content": executor_prompt}],
|
| 1429 |
-
"executor"
|
| 1430 |
-
):
|
| 1431 |
-
executor_response += chunk
|
| 1432 |
-
executor_text = f"[초기 실행 계획] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
| 1433 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🔧 실행자 AI가 계획 중..."
|
| 1434 |
-
|
| 1435 |
-
all_responses["executor"].append(executor_response)
|
| 1436 |
-
|
| 1437 |
-
# 9단계: 평가자 AI가 실행 계획 평가
|
| 1438 |
-
evaluator_execution_prompt = llm_system.create_evaluator_execution_prompt(
|
| 1439 |
-
user_query, executor_response
|
| 1440 |
-
)
|
| 1441 |
-
evaluator_execution_response = ""
|
| 1442 |
-
|
| 1443 |
-
evaluator_text += "\n\n---\n\n[실행 계획 평가] 🔄 생성 중...\n"
|
| 1444 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1445 |
-
[{"role": "user", "content": evaluator_execution_prompt}],
|
| 1446 |
-
"evaluator"
|
| 1447 |
-
):
|
| 1448 |
-
evaluator_execution_response += chunk
|
| 1449 |
-
temp_text = f"{all_responses['evaluator'][0]}\n\n---\n\n[실행 계획 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_execution_response}"
|
| 1450 |
-
evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
| 1451 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "⚖️ 평가자 AI가 검증 중..."
|
| 1452 |
-
|
| 1453 |
-
all_responses["evaluator"].append(evaluator_execution_response)
|
| 1454 |
-
|
| 1455 |
-
# 10단계: 감독자 AI 최종 지시
|
| 1456 |
-
supervisor_final_prompt = llm_system.create_supervisor_final_prompt(
|
| 1457 |
-
user_query, evaluator_execution_response
|
| 1458 |
-
)
|
| 1459 |
-
supervisor_final_response = ""
|
| 1460 |
-
|
| 1461 |
-
supervisor_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{all_responses['supervisor'][2]}\n\n---\n\n[최종 지시] 🔄 생성 중...\n"
|
| 1462 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1463 |
-
[{"role": "user", "content": supervisor_final_prompt}],
|
| 1464 |
-
"supervisor"
|
| 1465 |
-
):
|
| 1466 |
-
supervisor_final_response += chunk
|
| 1467 |
-
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{all_responses['supervisor'][2]}\n\n---\n\n[최종 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_final_response}"
|
| 1468 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
| 1469 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🎯 감독자 AI가 최종 검토 중..."
|
| 1470 |
-
|
| 1471 |
-
all_responses["supervisor"].append(supervisor_final_response)
|
| 1472 |
-
|
| 1473 |
-
# 11단계: 실행자 AI 최종 솔루션
|
| 1474 |
-
executor_final_prompt = llm_system.create_executor_final_prompt(
|
| 1475 |
-
user_query, executor_response, supervisor_final_response, full_context
|
| 1476 |
-
)
|
| 1477 |
-
final_executor_response = ""
|
| 1478 |
-
|
| 1479 |
-
executor_text += "\n\n---\n\n[최종 실행 솔루션] 🔄 작성 중...\n"
|
| 1480 |
-
for chunk in llm_system.call_llm_streaming(
|
| 1481 |
-
[{"role": "user", "content": executor_final_prompt}],
|
| 1482 |
-
"executor"
|
| 1483 |
-
):
|
| 1484 |
-
final_executor_response += chunk
|
| 1485 |
-
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}"
|
| 1486 |
-
executor_text = temp_text
|
| 1487 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "📄 최종 솔루션 작성 중..."
|
| 1488 |
-
|
| 1489 |
-
all_responses["executor"].append(final_executor_response)
|
| 1490 |
-
|
| 1491 |
-
# 최종 결과 생성
|
| 1492 |
-
final_summary = f"""## 🎯 최적화된 실용적 문제 해결 보고서
|
| 1493 |
-
|
| 1494 |
-
### 📌 사용자 질문
|
| 1495 |
-
{user_query}
|
| 1496 |
-
|
| 1497 |
-
### 🚀 최종 실행 솔루션
|
| 1498 |
-
{final_executor_response}
|
| 1499 |
-
|
| 1500 |
-
---
|
| 1501 |
-
|
| 1502 |
-
<details>
|
| 1503 |
-
<summary>📋 전체 협력 프로세스 보기</summary>
|
| 1504 |
-
|
| 1505 |
-
#### 1️⃣ 거시적 분석 (감독자 AI)
|
| 1506 |
-
{all_responses['supervisor'][0]}
|
| 1507 |
-
|
| 1508 |
-
#### 2️⃣ 혁신적 아이디어 (창조자 AI)
|
| 1509 |
-
{all_responses['creator'][0]}
|
| 1510 |
-
|
| 1511 |
-
#### 3️⃣ 아이디어 검토 및 조사 지시 (감독자 AI)
|
| 1512 |
-
{all_responses['supervisor'][1]}
|
| 1513 |
-
|
| 1514 |
-
#### 4️⃣ 조사 결과 (조사자 AI)
|
| 1515 |
-
{all_responses['researcher'][0]}
|
| 1516 |
-
|
| 1517 |
-
#### 5️⃣ 조사 결과 평가 (평가자 AI)
|
| 1518 |
-
{all_responses['evaluator'][0]}
|
| 1519 |
-
|
| 1520 |
-
#### 6️⃣ 실행 지시 (감독자 AI)
|
| 1521 |
-
{all_responses['supervisor'][2]}
|
| 1522 |
-
|
| 1523 |
-
#### 7️⃣ 초기 실행 계획 (실행자 AI)
|
| 1524 |
-
{all_responses['executor'][0]}
|
| 1525 |
-
|
| 1526 |
-
#### 8️⃣ 실행 계획 평가 (평가자 AI)
|
| 1527 |
-
{all_responses['evaluator'][1]}
|
| 1528 |
-
|
| 1529 |
-
#### 9️⃣ 최종 지시 (감독자 AI)
|
| 1530 |
-
{all_responses['supervisor'][3]}
|
| 1531 |
-
|
| 1532 |
-
</details>
|
| 1533 |
-
|
| 1534 |
-
---
|
| 1535 |
-
*이 보고서는 5개 AI의 협력적 프로세스를 통해 최적화된 실용적 해결책을 제공합니다.*
|
| 1536 |
-
*프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행*"""
|
| 1537 |
-
|
| 1538 |
-
internal_history.append((user_query, final_summary))
|
| 1539 |
-
|
| 1540 |
-
# 최종 마크다운 반환
|
| 1541 |
-
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, final_summary
|
| 1542 |
-
|
| 1543 |
except Exception as e:
|
| 1544 |
-
|
| 1545 |
-
|
| 1546 |
-
|
| 1547 |
-
def clear_all():
|
| 1548 |
-
"""모든 내용 초기화"""
|
| 1549 |
-
global internal_history
|
| 1550 |
-
internal_history = []
|
| 1551 |
-
return "", "", "", "", "", "🔄 초기화되었습니다."
|
| 1552 |
-
|
| 1553 |
-
# Gradio 인터페이스
|
| 1554 |
-
css = """
|
| 1555 |
-
.gradio-container {
|
| 1556 |
-
font-family: 'Arial', sans-serif;
|
| 1557 |
-
}
|
| 1558 |
-
.supervisor-box textarea {
|
| 1559 |
-
border-left: 4px solid #667eea !important;
|
| 1560 |
-
background-color: #f3f4f6 !important;
|
| 1561 |
-
}
|
| 1562 |
-
.creator-box textarea {
|
| 1563 |
-
border-left: 4px solid #f59e0b !important;
|
| 1564 |
-
background-color: #fffbeb !important;
|
| 1565 |
-
}
|
| 1566 |
-
.researcher-box textarea {
|
| 1567 |
-
border-left: 4px solid #10b981 !important;
|
| 1568 |
-
background-color: #ecfdf5 !important;
|
| 1569 |
-
}
|
| 1570 |
-
.evaluator-box textarea {
|
| 1571 |
-
border-left: 4px solid #ef4444 !important;
|
| 1572 |
-
background-color: #fef2f2 !important;
|
| 1573 |
-
}
|
| 1574 |
-
.executor-box textarea {
|
| 1575 |
-
border-left: 4px solid #764ba2 !important;
|
| 1576 |
-
background-color: #faf5ff !important;
|
| 1577 |
-
}
|
| 1578 |
-
"""
|
| 1579 |
-
|
| 1580 |
-
with gr.Blocks(title="최적화된 협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
| 1581 |
-
gr.Markdown(
|
| 1582 |
-
"""
|
| 1583 |
-
# 🚀 최적화된 최고의 실용적 문제 해결자
|
| 1584 |
-
### 5개 AI의 협력적 프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행
|
| 1585 |
-
"""
|
| 1586 |
-
)
|
| 1587 |
-
|
| 1588 |
-
# 입력 섹션
|
| 1589 |
-
with gr.Row():
|
| 1590 |
-
with gr.Column():
|
| 1591 |
-
gr.Markdown("""
|
| 1592 |
-
## 🎯 향상된 기능
|
| 1593 |
-
- **창조자 AI**: 혁신적이고 파괴적인 아이디어 생성
|
| 1594 |
-
- **평가자 AI**: 객관적이고 비판적인 검증 및 평가
|
| 1595 |
-
- **강화된 프로세스**: 11단계 협력적 문제 해결
|
| 1596 |
-
- **실용성 극대화**: 즉시 실행 가능한 솔루션 제공
|
| 1597 |
-
""")
|
| 1598 |
-
|
| 1599 |
-
user_input = gr.Textbox(
|
| 1600 |
-
label="질문 입력",
|
| 1601 |
-
placeholder="예: 우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?",
|
| 1602 |
-
lines=3
|
| 1603 |
-
)
|
| 1604 |
-
|
| 1605 |
-
with gr.Row():
|
| 1606 |
-
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2)
|
| 1607 |
-
clear_btn = gr.Button("🗑️ 초기화", scale=1)
|
| 1608 |
-
|
| 1609 |
-
status_text = gr.Textbox(
|
| 1610 |
-
label="상태",
|
| 1611 |
-
interactive=False,
|
| 1612 |
-
value="대기 중...",
|
| 1613 |
-
max_lines=1
|
| 1614 |
-
)
|
| 1615 |
-
|
| 1616 |
-
# 최종 결과 (상단에 크게 표시)
|
| 1617 |
-
with gr.Row():
|
| 1618 |
-
with gr.Column():
|
| 1619 |
-
with gr.Accordion("📊 최��� 실행 솔루션", open=True):
|
| 1620 |
-
final_output = gr.Markdown(
|
| 1621 |
-
value="*질문을 입력하면 최종 솔루션이 여기에 표시됩니다.*"
|
| 1622 |
-
)
|
| 1623 |
-
|
| 1624 |
-
# AI 출력들 - 2줄로 배치
|
| 1625 |
-
# 첫 번째 줄: 감독자, 창조자, 조사자
|
| 1626 |
-
with gr.Row():
|
| 1627 |
-
with gr.Column():
|
| 1628 |
-
gr.Markdown("### 🧠 감독자 AI (전략적 지휘)")
|
| 1629 |
-
supervisor_output = gr.Textbox(
|
| 1630 |
-
label="",
|
| 1631 |
-
lines=15,
|
| 1632 |
-
max_lines=20,
|
| 1633 |
-
interactive=False,
|
| 1634 |
-
elem_classes=["supervisor-box"]
|
| 1635 |
-
)
|
| 1636 |
-
|
| 1637 |
-
with gr.Column():
|
| 1638 |
-
gr.Markdown("### 💡 창조자 AI (혁신적 아이디어)")
|
| 1639 |
-
creator_output = gr.Textbox(
|
| 1640 |
-
label="",
|
| 1641 |
-
lines=15,
|
| 1642 |
-
max_lines=20,
|
| 1643 |
-
interactive=False,
|
| 1644 |
-
elem_classes=["creator-box"]
|
| 1645 |
-
)
|
| 1646 |
-
|
| 1647 |
-
with gr.Column():
|
| 1648 |
-
gr.Markdown("### 🔍 조사자 AI (정보 수집)")
|
| 1649 |
-
researcher_output = gr.Textbox(
|
| 1650 |
-
label="",
|
| 1651 |
-
lines=15,
|
| 1652 |
-
max_lines=20,
|
| 1653 |
-
interactive=False,
|
| 1654 |
-
elem_classes=["researcher-box"]
|
| 1655 |
-
)
|
| 1656 |
-
|
| 1657 |
-
# 두 번째 줄: 평가자, 실행자
|
| 1658 |
-
with gr.Row():
|
| 1659 |
-
with gr.Column():
|
| 1660 |
-
gr.Markdown("### ⚖️ 평가자 AI (객관적 평가)")
|
| 1661 |
-
evaluator_output = gr.Textbox(
|
| 1662 |
-
label="",
|
| 1663 |
-
lines=15,
|
| 1664 |
-
max_lines=20,
|
| 1665 |
-
interactive=False,
|
| 1666 |
-
elem_classes=["evaluator-box"]
|
| 1667 |
-
)
|
| 1668 |
-
|
| 1669 |
-
with gr.Column():
|
| 1670 |
-
gr.Markdown("### 🔧 실행자 AI (실용적 구현)")
|
| 1671 |
-
executor_output = gr.Textbox(
|
| 1672 |
-
label="",
|
| 1673 |
-
lines=15,
|
| 1674 |
-
max_lines=20,
|
| 1675 |
-
interactive=False,
|
| 1676 |
-
elem_classes=["executor-box"]
|
| 1677 |
-
)
|
| 1678 |
-
|
| 1679 |
-
# 프로세스 다이어그램
|
| 1680 |
-
gr.Markdown("""
|
| 1681 |
-
---
|
| 1682 |
-
### 🔄 협업 프로세스 흐름도
|
| 1683 |
-
```
|
| 1684 |
-
사용자 질문
|
| 1685 |
-
↓
|
| 1686 |
-
[1] 감독자 AI (초기 분석)
|
| 1687 |
-
↓
|
| 1688 |
-
[2] 창조자 AI (혁신 아이디어)
|
| 1689 |
-
↓
|
| 1690 |
-
[3] 감독자 AI (아이디어 검토)
|
| 1691 |
-
↓
|
| 1692 |
-
[4] 조사자 AI (웹 검색 & 정리)
|
| 1693 |
-
↓
|
| 1694 |
-
[5] 평가자 AI (조사 결과 평가)
|
| 1695 |
-
↓
|
| 1696 |
-
[6] 감독자 AI (실행 지시)
|
| 1697 |
-
↓
|
| 1698 |
-
[7] 실행자 AI (초기 계획)
|
| 1699 |
-
↓
|
| 1700 |
-
[8] 평가자 AI (계획 평가)
|
| 1701 |
-
↓
|
| 1702 |
-
[9] 감독자 AI (최종 지시)
|
| 1703 |
-
↓
|
| 1704 |
-
[10] 실행자 AI (최종 솔루션)
|
| 1705 |
-
↓
|
| 1706 |
-
최적화된 실용적 해결책
|
| 1707 |
-
```
|
| 1708 |
-
""")
|
| 1709 |
-
|
| 1710 |
-
# 예제
|
| 1711 |
-
gr.Examples(
|
| 1712 |
-
examples=[
|
| 1713 |
-
"우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?",
|
| 1714 |
-
"원격 근무 환경에서 팀 생산성을 2배로 높이는 구체적인 전략은?",
|
| 1715 |
-
"스타트업이 6개월 내에 수익을 3배 늘릴 수 있는 실행 가능한 방법은?",
|
| 1716 |
-
"기존 제품을 완전히 혁신하여 시장을 선도할 수 있는 아이디어는?",
|
| 1717 |
-
"AI를 활용해 운영 비용을 50% 절감하는 실질적인 방안은?"
|
| 1718 |
-
],
|
| 1719 |
-
inputs=user_input,
|
| 1720 |
-
label="💡 예제 질문"
|
| 1721 |
-
)
|
| 1722 |
-
|
| 1723 |
-
# 이벤트 핸들러
|
| 1724 |
-
submit_btn.click(
|
| 1725 |
-
fn=process_query_streaming,
|
| 1726 |
-
inputs=[user_input],
|
| 1727 |
-
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output]
|
| 1728 |
-
).then(
|
| 1729 |
-
fn=lambda: "",
|
| 1730 |
-
outputs=[user_input]
|
| 1731 |
-
)
|
| 1732 |
-
|
| 1733 |
-
user_input.submit(
|
| 1734 |
-
fn=process_query_streaming,
|
| 1735 |
-
inputs=[user_input],
|
| 1736 |
-
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output]
|
| 1737 |
-
).then(
|
| 1738 |
-
fn=lambda: "",
|
| 1739 |
-
outputs=[user_input]
|
| 1740 |
-
)
|
| 1741 |
-
|
| 1742 |
-
clear_btn.click(
|
| 1743 |
-
fn=clear_all,
|
| 1744 |
-
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, status_text]
|
| 1745 |
-
)
|
| 1746 |
|
| 1747 |
if __name__ == "__main__":
|
| 1748 |
-
|
| 1749 |
-
app.launch(
|
| 1750 |
-
server_name="0.0.0.0",
|
| 1751 |
-
server_port=7860,
|
| 1752 |
-
share=True,
|
| 1753 |
-
show_error=True
|
| 1754 |
-
)
|
|
|
|
|
|
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
try:
|
| 8 |
+
# Get the code from secrets
|
| 9 |
+
code = os.environ.get("MAIN_CODE")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
if not code:
|
| 12 |
+
st.error("⚠️ The application code wasn't found in secrets. Please add the MAIN_CODE secret.")
|
| 13 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Create a temporary Python file
|
| 16 |
+
with NamedTemporaryFile(suffix='.py', delete=False, mode='w') as tmp:
|
| 17 |
+
tmp.write(code)
|
| 18 |
+
tmp_path = tmp.name
|
| 19 |
|
| 20 |
+
# Execute the code
|
| 21 |
+
exec(compile(code, tmp_path, 'exec'), globals())
|
| 22 |
|
| 23 |
+
# Clean up the temporary file
|
| 24 |
+
try:
|
| 25 |
+
os.unlink(tmp_path)
|
| 26 |
+
except:
|
| 27 |
+
pass
|
|
|
|
|
|
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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