|
import gradio as gr |
|
import os |
|
import json |
|
import requests |
|
from datetime import datetime |
|
import time |
|
from typing import List, Dict, Any, Generator, Tuple |
|
import logging |
|
import re |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
from bs4 import BeautifulSoup |
|
from urllib.parse import urlparse |
|
import urllib.request |
|
|
|
|
|
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN") |
|
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN") |
|
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions" |
|
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search" |
|
MODEL_ID = "dep89a2fld32mcm" |
|
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true" |
|
|
|
|
|
conversation_history = [] |
|
|
|
class LLMCollaborativeSystem: |
|
def __init__(self): |
|
self.token = FRIENDLI_TOKEN |
|
self.bapi_token = BAPI_TOKEN |
|
self.api_url = API_URL |
|
self.brave_url = BRAVE_SEARCH_URL |
|
self.model_id = MODEL_ID |
|
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN") |
|
|
|
if self.test_mode: |
|
logger.warning("테스트 모드로 실행됩니다.") |
|
if self.bapi_token == "YOUR_BRAVE_API_TOKEN": |
|
logger.warning("Brave API 토큰이 설정되지 않았습니다.") |
|
|
|
def create_headers(self): |
|
"""API 헤더 생성""" |
|
return { |
|
"Authorization": f"Bearer {self.token}", |
|
"Content-Type": "application/json" |
|
} |
|
|
|
def create_brave_headers(self): |
|
"""Brave API 헤더 생성""" |
|
return { |
|
"Accept": "application/json", |
|
"Accept-Encoding": "gzip", |
|
"X-Subscription-Token": self.bapi_token |
|
} |
|
|
|
def create_supervisor_initial_prompt(self, user_query: str) -> str: |
|
"""감독자 AI 초기 프롬프트 생성""" |
|
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
이 질문에 대해: |
|
1. 문제의 본질과 핵심 요구사항을 파악하세요 |
|
2. 해결을 위한 전략적 프레임워크를 수립하세요 |
|
3. 창조자 AI가 혁신적인 아이디어를 낼 수 있도록 문제의 맥락과 제약사항을 명확히 정의하세요 |
|
4. 성공 기준과 목표를 구체적으로 제시하세요""" |
|
|
|
def create_creator_prompt(self, user_query: str, supervisor_guidance: str) -> str: |
|
"""창조자 AI 프롬프트 생성""" |
|
return f"""당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
감독자 AI의 분석: |
|
{supervisor_guidance} |
|
|
|
위 분석을 바탕으로: |
|
1. 기존 방식을 뛰어넘는 혁신적인 해결 방안 5-7개를 제시하세요 |
|
2. 각 아이디어의 독창성과 잠재적 영향력을 설명하세요 |
|
3. 실현 가능성과 함께 필요한 리소스를 개략적으로 제시하세요 |
|
4. 아이디어 간의 시너지 효과나 결합 가능성을 탐색하세요 |
|
5. 미래 지향적이고 파괴적인 혁신 요소를 포함하세요""" |
|
|
|
def create_supervisor_ideation_review_prompt(self, user_query: str, creator_ideas: str) -> str: |
|
"""감독자 AI의 아이디어 검토 및 조사 지시 프롬프트""" |
|
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
창조자 AI가 제시한 혁신적 아이디어들: |
|
{creator_ideas} |
|
|
|
이 아이디어들을 검토하고: |
|
1. 각 아이디어의 전략적 가치와 실현 가능성을 평가하세요 |
|
2. 가장 유망한 3-4개 아이디어를 선별하고 그 이유를 설명하세요 |
|
3. 선별된 아이디어에 대해 조사가 필요한 구체적인 키워드나 검색어를 제시하세요 |
|
4. 조사 시 중점적으로 확인해야 할 사항들을 명시하세요 |
|
|
|
키워드는 다음 형식으로 제시하세요: |
|
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5""" |
|
|
|
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str: |
|
"""조사자 AI 프롬프트 생성 (기존 코드 재사용)""" |
|
search_summary = "" |
|
all_results = [] |
|
|
|
for keyword, results in search_results.items(): |
|
search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n" |
|
for i, result in enumerate(results[:10], 1): |
|
search_summary += f"{i}. {result.get('title', 'N/A')} (신뢰도: {result.get('credibility_score', 0):.2f})\n" |
|
search_summary += f" - {result.get('description', 'N/A')}\n" |
|
search_summary += f" - 출처: {result.get('url', 'N/A')}\n" |
|
if result.get('published'): |
|
search_summary += f" - 게시일: {result.get('published')}\n" |
|
|
|
all_results.extend(results) |
|
|
|
contradictions = self.detect_contradictions(all_results) |
|
contradiction_text = "" |
|
if contradictions: |
|
contradiction_text = "\n\n**발견된 정보 모순:**\n" |
|
for cont in contradictions[:3]: |
|
contradiction_text += f"- {cont['type']}: {cont['source1']} vs {cont['source2']}\n" |
|
|
|
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
감독자 AI의 지침: |
|
{supervisor_guidance} |
|
|
|
브레이브 검색 결과 (신뢰도 점수 포함): |
|
{search_summary} |
|
{contradiction_text} |
|
|
|
위 검색 결과를 바탕으로: |
|
1. 각 키워드별로 중요한 정보를 정리하세요 |
|
2. 신뢰할 수 있는 출처(신뢰도 0.7 이상)를 우선적으로 참고하세요 |
|
3. 실제 구현 사례나 성공 사례를 중점적으로 찾아 정리하세요 |
|
4. 기술적 실현 가능성과 필요한 리소스 정보를 포함하세요 |
|
5. 최신 트렌드와 미래 전망을 강조하세요""" |
|
|
|
def create_evaluator_research_prompt(self, user_query: str, creator_ideas: str, research_summary: str) -> str: |
|
"""평가자 AI의 조사 결과 평가 프롬프트""" |
|
return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
창조자 AI의 아이디어: |
|
{creator_ideas} |
|
|
|
조사자 AI의 조사 결과: |
|
{research_summary} |
|
|
|
위 내용을 종합적으로 평가하여: |
|
1. 각 아이디어의 실현 가능성을 1-10점으로 평가하고 근거를 제시하세요 |
|
2. 예상되는 리스크와 장애물을 구체적으로 분석하세요 |
|
3. ROI(투자 대비 효과)를 예측하고 우선순위를 제안하세요 |
|
4. 조사 결과의 신뢰성과 충분성을 평가하세요 |
|
5. 추가로 필요한 정보나 검증 사항을 제시하세요 |
|
6. 최종적으로 가장 실행 가능한 2-3개 방안을 추천하세요""" |
|
|
|
def create_supervisor_execution_prompt(self, user_query: str, evaluator_assessment: str) -> str: |
|
"""감독자 AI의 실행 지시 프롬프트""" |
|
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
평가자 AI의 종합 평가: |
|
{evaluator_assessment} |
|
|
|
평가 결과를 바탕으로 실행자 AI에게 구체적인 지시를 내려주세요: |
|
1. 평가자가 추천한 방안들을 어떻게 구현할지 단계별로 명시하세요 |
|
2. 각 단계의 구체적인 작업 내용과 예상 소요 시간을 제시하세요 |
|
3. 리스크 대응 방안을 각 단계별로 준비하세요 |
|
4. 성과 측정 지표와 마일스톤을 명확히 정의하세요 |
|
5. 필요한 리소스와 협력 체계를 구체화하세요""" |
|
|
|
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, full_context: str) -> str: |
|
"""실행자 AI 프롬프트 생성""" |
|
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
전체 맥락 (아이디어, 조사, 평가): |
|
{full_context} |
|
|
|
감독자 AI의 구체적인 지시: |
|
{supervisor_guidance} |
|
|
|
위 모든 정보를 바탕으로: |
|
1. 즉시 실행 가능한 구체적인 행동 계획을 작성하세요 |
|
2. 각 작업의 상세한 실행 방법과 필요 도구를 명시하세요 |
|
3. 예상되는 결과물과 산출물을 구체적으로 설명하세요 |
|
4. 단계별 체크리스트와 검증 방법을 포함하세요 |
|
5. 실제 코드, 템플릿, 프로세스 등 즉시 사용 가능한 자료를 제공하세요""" |
|
|
|
def create_evaluator_execution_prompt(self, user_query: str, executor_plan: str) -> str: |
|
"""평가자 AI의 실행 계획 평가 프롬프트""" |
|
return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
실행자 AI의 실행 계획: |
|
{executor_plan} |
|
|
|
이 실행 계획을 평가하여: |
|
1. 계획의 완성도와 실행 가능성을 평가하세요 (1-10점) |
|
2. 누락된 요소나 개선이 필요한 부분을 구체적으로 지적하세요 |
|
3. 예상되는 실행 상의 문제점과 해결 방안을 제시하세요 |
|
4. 성공 가능성을 높이기 위한 추가 제안을 하세요 |
|
5. 최종 점검 사항과 품질 기준을 제시하세요""" |
|
|
|
def create_supervisor_final_prompt(self, user_query: str, evaluator_feedback: str) -> str: |
|
"""감독자 AI의 최종 지시 프롬프트""" |
|
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
평가자 AI의 실행 계획 평가: |
|
{evaluator_feedback} |
|
|
|
평가 내용을 바탕으로: |
|
1. 실행자 AI가 반드시 보완해야 할 핵심 사항을 명확히 지시하세요 |
|
2. 최종 품질 기준과 완성도 요구사항을 제시하세요 |
|
3. 즉시 실행 가능한 형태로 만들기 위한 구체적인 개선 방향을 제시하세요 |
|
4. 성공적인 실행을 위한 핵심 성공 요인을 강조하세요""" |
|
|
|
def create_executor_final_prompt(self, user_query: str, initial_plan: str, supervisor_final_guidance: str, full_context: str) -> str: |
|
"""실행자 AI 최종 보고서 프롬프트""" |
|
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다. |
|
|
|
사용자 질문: {user_query} |
|
|
|
전체 협업 맥락: |
|
{full_context} |
|
|
|
당신의 초기 실행 계획: |
|
{initial_plan} |
|
|
|
감독자 AI의 최종 지시사항: |
|
{supervisor_final_guidance} |
|
|
|
모든 피드백을 완전히 반영하여 즉시 실행 가능한 최종 솔루션을 작성하세요: |
|
1. 모든 개선사항을 반영한 완성된 실행 계획 |
|
2. 구체적인 실행 도구, 코드, 템플릿 제공 |
|
3. 단계별 실행 가이드와 체크리스트 |
|
4. 예상 결과와 성과 측정 방법 |
|
5. 리스크 대응 계획과 문제 해결 가이드 |
|
6. 지속적 개선을 위한 모니터링 체계 |
|
|
|
**반드시 실용적이고 즉시 적용 가능한 형태로 작성하세요.**""" |
|
|
|
def extract_keywords(self, supervisor_response: str) -> List[str]: |
|
"""감독자 응답에서 키워드 추출 (기존 코드 재사용)""" |
|
keywords = [] |
|
|
|
keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE) |
|
if keyword_match: |
|
keyword_str = keyword_match.group(1) |
|
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()] |
|
|
|
if not keywords: |
|
keywords = ["best practices", "implementation guide", "case studies", "latest trends", "success factors"] |
|
|
|
return keywords[:7] |
|
|
|
def generate_synonyms(self, keyword: str) -> List[str]: |
|
"""키워드의 동의어/유사어 생성 (기존 코드 재사용)""" |
|
synonyms = { |
|
"optimization": ["improvement", "enhancement", "efficiency", "tuning"], |
|
"performance": ["speed", "efficiency", "throughput", "latency"], |
|
"strategy": ["approach", "method", "technique", "plan"], |
|
"implementation": ["deployment", "execution", "development", "integration"], |
|
"analysis": ["evaluation", "assessment", "study", "research"], |
|
"management": ["administration", "governance", "control", "supervision"], |
|
"best practices": ["proven methods", "industry standards", "guidelines", "recommendations"], |
|
"trends": ["developments", "innovations", "emerging", "future"], |
|
"machine learning": ["ML", "AI", "deep learning", "neural networks"], |
|
"프로젝트": ["project", "사업", "업무", "작업"], |
|
"innovation": ["disruption", "breakthrough", "transformation", "revolution"], |
|
"solution": ["approach", "method", "system", "framework"] |
|
} |
|
|
|
keyword_lower = keyword.lower() |
|
|
|
if keyword_lower in synonyms: |
|
return synonyms[keyword_lower][:2] |
|
|
|
for key, values in synonyms.items(): |
|
if key in keyword_lower or keyword_lower in key: |
|
return values[:2] |
|
|
|
return [] |
|
|
|
def calculate_credibility_score(self, result: Dict) -> float: |
|
"""검색 결과의 신뢰도 점수 계산 (기존 코드 재사용)""" |
|
score = 0.5 |
|
|
|
url = result.get('url', '') |
|
title = result.get('title', '') |
|
description = result.get('description', '') |
|
|
|
trusted_domains = [ |
|
'.edu', '.gov', '.org', 'wikipedia.org', 'nature.com', |
|
'sciencedirect.com', 'ieee.org', 'acm.org', 'springer.com', |
|
'harvard.edu', 'mit.edu', 'stanford.edu', 'github.com' |
|
] |
|
|
|
for domain in trusted_domains: |
|
if domain in url: |
|
score += 0.2 |
|
break |
|
|
|
if url.startswith('https://'): |
|
score += 0.1 |
|
|
|
if len(title) > 20: |
|
score += 0.05 |
|
if len(description) > 50: |
|
score += 0.05 |
|
|
|
spam_keywords = ['buy now', 'sale', 'discount', 'click here', '100% free'] |
|
if any(spam in (title + description).lower() for spam in spam_keywords): |
|
score -= 0.3 |
|
|
|
if any(year in description for year in ['2024', '2023', '2022']): |
|
score += 0.1 |
|
|
|
return max(0, min(1, score)) |
|
|
|
def fetch_url_content(self, url: str, max_length: int = 2000) -> str: |
|
"""URL에서 콘텐츠 추출 (기존 코드 재사용)""" |
|
try: |
|
headers = { |
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' |
|
} |
|
|
|
req = urllib.request.Request(url, headers=headers) |
|
|
|
with urllib.request.urlopen(req, timeout=5) as response: |
|
html = response.read().decode('utf-8', errors='ignore') |
|
|
|
soup = BeautifulSoup(html, 'html.parser') |
|
|
|
for script in soup(["script", "style"]): |
|
script.decompose() |
|
|
|
text = soup.get_text() |
|
|
|
lines = (line.strip() for line in text.splitlines()) |
|
chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) |
|
text = ' '.join(chunk for chunk in chunks if chunk) |
|
|
|
if len(text) > max_length: |
|
text = text[:max_length] + "..." |
|
|
|
return text |
|
|
|
except Exception as e: |
|
logger.error(f"URL 콘텐츠 가져오기 실패 {url}: {str(e)}") |
|
return "" |
|
|
|
def detect_contradictions(self, results: List[Dict]) -> List[Dict]: |
|
"""검색 결과 간 모순 감지 (기존 코드 재사용)""" |
|
contradictions = [] |
|
|
|
opposite_pairs = [ |
|
("increase", "decrease"), |
|
("improve", "worsen"), |
|
("effective", "ineffective"), |
|
("success", "failure"), |
|
("benefit", "harm"), |
|
("positive", "negative"), |
|
("growth", "decline") |
|
] |
|
|
|
for i in range(len(results)): |
|
for j in range(i + 1, len(results)): |
|
desc1 = results[i].get('description', '').lower() |
|
desc2 = results[j].get('description', '').lower() |
|
|
|
for word1, word2 in opposite_pairs: |
|
if (word1 in desc1 and word2 in desc2) or (word2 in desc1 and word1 in desc2): |
|
common_words = set(desc1.split()) & set(desc2.split()) |
|
if len(common_words) > 5: |
|
contradictions.append({ |
|
'source1': results[i]['url'], |
|
'source2': results[j]['url'], |
|
'type': f"{word1} vs {word2}", |
|
'desc1': results[i]['description'][:100], |
|
'desc2': results[j]['description'][:100] |
|
}) |
|
|
|
return contradictions |
|
|
|
def brave_search(self, query: str) -> List[Dict]: |
|
"""Brave Search API 호출 (기존 코드 재사용)""" |
|
if self.test_mode or self.bapi_token == "YOUR_BRAVE_API_TOKEN": |
|
test_results = [] |
|
for i in range(5): |
|
test_results.append({ |
|
"title": f"Best Practices for {query} - Source {i+1}", |
|
"description": f"Comprehensive guide on implementing {query} with proven methodologies and real-world examples from industry leaders.", |
|
"url": f"https://example{i+1}.com/{query.replace(' ', '-')}", |
|
"credibility_score": 0.7 + (i * 0.05) |
|
}) |
|
return test_results |
|
|
|
try: |
|
params = { |
|
"q": query, |
|
"count": 20, |
|
"safesearch": "moderate", |
|
"freshness": "pw" |
|
} |
|
|
|
response = requests.get( |
|
self.brave_url, |
|
headers=self.create_brave_headers(), |
|
params=params, |
|
timeout=10 |
|
) |
|
|
|
if response.status_code == 200: |
|
data = response.json() |
|
results = [] |
|
for item in data.get("web", {}).get("results", [])[:20]: |
|
result = { |
|
"title": item.get("title", ""), |
|
"description": item.get("description", ""), |
|
"url": item.get("url", ""), |
|
"published": item.get("published", "") |
|
} |
|
result["credibility_score"] = self.calculate_credibility_score(result) |
|
results.append(result) |
|
|
|
results.sort(key=lambda x: x['credibility_score'], reverse=True) |
|
return results |
|
else: |
|
logger.error(f"Brave API 오류: {response.status_code}") |
|
return [] |
|
|
|
except Exception as e: |
|
logger.error(f"Brave 검색 중 오류: {str(e)}") |
|
return [] |
|
|
|
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]: |
|
"""테스트 모드에서 스트리밍 시뮬레이션""" |
|
words = text.split() |
|
for i in range(0, len(words), 3): |
|
chunk = " ".join(words[i:i+3]) |
|
yield chunk + " " |
|
time.sleep(0.05) |
|
|
|
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]: |
|
"""스트리밍 LLM API 호출""" |
|
|
|
if self.test_mode: |
|
logger.info(f"테스트 모드 스트리밍 - Role: {role}") |
|
|
|
test_responses = { |
|
"supervisor_initial": """이 질문에 대한 거시적 분석을 제시하겠습니다. |
|
|
|
**1. 문제의 본질 파악** |
|
사용자는 실용적이고 즉시 적용 가능한 해결책을 원하고 있습니다. 단순한 이론이나 개념이 아닌, 실제로 구현 가능한 구체적인 방안이 필요합니다. |
|
|
|
**2. 전략적 프레임워크** |
|
- 단기 목표: 즉시 실행 가능한 quick win 솔루션 도출 |
|
- 중기 목표: 지속 가능한 개선 체계 구축 |
|
- 장기 목표: 혁신적 변화를 통한 경쟁 우위 확보 |
|
|
|
**3. 제약사항 및 맥락** |
|
- 기존 리소스와 인프라 활용 극대화 |
|
- 최소한의 투자로 최대 효과 달성 |
|
- 실무진이 바로 이해하고 실행할 수 있는 수준 |
|
|
|
**4. 성공 기준** |
|
- 측정 가능한 개선 지표 (30% 이상 향상) |
|
- 3개월 내 가시적 성과 달성 |
|
- ROI 200% 이상 달성""", |
|
|
|
"creator": """혁신적인 아이디어를 제시하겠습니다. |
|
|
|
**🚀 아이디어 1: AI 기반 자동 최적화 시스템** |
|
- 독창성: 머신러닝이 스스로 시스템을 개선하는 자가 진화 시스템 |
|
- 영향력: 인간 개입 없이 24/7 성능 향상, 90% 효율성 증가 가능 |
|
- 필요 리소스: 클라우드 컴퓨팅, ML 엔지니어 1명 |
|
- 실현 가능성: 8/10 |
|
|
|
**💡 아이디어 2: 크라우드소싱 혁신 플랫폼** |
|
- 독창성: 전 직원이 참여하는 실시간 개선 아이디어 시장 |
|
- 영향력: 집단 지성 활용으로 혁신 속도 10배 가속 |
|
- 필요 리소스: 웹 플랫폼, 인센티브 예산 |
|
- 실현 가능성: 9/10 |
|
|
|
**🔄 아이디어 3: 디지털 트윈 시뮬레이션** |
|
- 독창성: 가상 환경에서 모든 시나리오를 사전 테스트 |
|
- 영향력: 리스크 80% 감소, 실패 비용 제로화 |
|
- 필요 리소스: 시뮬레이션 소프트웨어, 데이터 분석가 |
|
- 실현 가능성: 7/10 |
|
|
|
**🌐 아이디어 4: 블록체인 기반 프로세스 자동화** |
|
- 독창성: 신뢰 기반 자동 실행 스마트 컨트랙트 |
|
- 영향력: 중개 비용 제거, 처리 시간 95% 단축 |
|
- 필요 리소스: 블록체인 개발자, 네트워크 인프라 |
|
- 실현 가능성: 6/10 |
|
|
|
**🧬 아이디어 5: 생체모방 알고리즘 적용** |
|
- 독창성: 자연의 최적화 원리를 비즈니스에 적용 |
|
- 영향력: 예측 불가능한 환경에서도 적응력 극대화 |
|
- 필요 리소스: R&D 팀, 실험 환경 |
|
- 실현 가능성: 5/10 |
|
|
|
**시너지 효과** |
|
아이디어 1+2 결합: AI가 크라우드소싱 아이디어를 자동 평가하고 구현 |
|
아이디어 3+4 결합: 블록체인으로 검증된 디지털 트윈 결과 자동 실행""", |
|
|
|
"supervisor_ideation_review": """창조자 AI의 아이디어를 검토한 결과입니다. |
|
|
|
**전략적 평가** |
|
1. AI 기반 자동 최적화 시스템 - ⭐⭐⭐⭐⭐ |
|
- 즉시 실행 가능하고 ROI가 명확함 |
|
- 기존 인프라 활용 가능 |
|
|
|
2. 크라우드소싱 혁신 플랫폼 - ⭐⭐⭐⭐⭐ |
|
- 조직 문화 개선과 혁신 동시 달성 |
|
- 빠른 구현과 낮은 리스크 |
|
|
|
3. 디지털 트윈 시뮬레이션 - ⭐⭐⭐⭐ |
|
- 중장기적 가치가 높음 |
|
- 초기 투자 대비 효과 검증 필요 |
|
|
|
**선별된 아이디어** |
|
1, 2, 3번 아이디어를 중심으로 진행 권장 |
|
|
|
**조사 필요 사항** |
|
- 성공 사례와 구현 방법론 |
|
- 필요 기술 스택과 도구 |
|
- 예상 비용과 ROI 데이터 |
|
- 산업별 적용 사례 |
|
|
|
[검색 키워드]: AI automation implementation case studies, crowdsourcing innovation platform examples, digital twin ROI analysis, machine learning optimization tools, employee innovation engagement systems""", |
|
|
|
"researcher": """조사 결과를 종합하여 보고합니다. |
|
|
|
**1. AI 자동 최적화 시스템 구현 사례 (신뢰도 0.92)** |
|
- Google: AutoML로 모델 성능 40% 개선, 개발 시간 90% 단축 |
|
- Netflix: 실시간 최적화로 스트리밍 품질 35% 향상 |
|
- 구현 도구: TensorFlow Extended, AutoKeras, H2O.ai |
|
- 평균 ROI: 6개월 내 250% |
|
- 출처: Google AI Blog, Netflix Tech Blog |
|
|
|
**2. 크라우드소싱 혁신 플랫폼 성공 사례 (신뢰도 0.88)** |
|
- P&G Connect+Develop: 외부 혁신으로 R&D 생산성 60% 향상 |
|
- Lego Ideas: 고객 아이디어로 신제품 출시 주기 50% 단축 |
|
- 플랫폼: IdeaScale, Brightidea, Spigit |
|
- 평균 참여율: 직원의 75% |
|
- 출처: Harvard Business Review, MIT Sloan Review |
|
|
|
**3. 디지털 트윈 ROI 분석 (신뢰도 0.85)** |
|
- GE: 예측 정비로 다운타임 20% 감소, 연간 $1.6B 절감 |
|
- Siemens: 제품 개발 주기 50% 단축 |
|
- 필요 기술: Azure Digital Twins, AWS IoT TwinMaker |
|
- 초기 투자 회수: 평균 18개월 |
|
- 출처: Gartner Report 2024, IDC Research |
|
|
|
**4. 실제 구현 가이드 (신뢰도 0.90)** |
|
- 단계별 구현 로드맵 확보 |
|
- 오픈소스 도구 목록 및 비용 분석 |
|
- 필요 인력: 프로젝트당 3-5명 |
|
- 구현 기간: 3-6개월 |
|
|
|
**5. 최신 트렌드 (신뢰도 0.87)** |
|
- 2024년 AI 자동화가 주류로 부상 |
|
- Low-code/No-code 플랫폼으로 진입 장벽 낮아짐 |
|
- Edge AI로 실시간 최적화 가능 |
|
- 출처: McKinsey Digital Report 2024 |
|
|
|
**핵심 인사이트** |
|
- 세 가지 아이디어 모두 검증된 성공 사례 존재 |
|
- 투자 대비 효과가 명확히 입증됨 |
|
- 기술적 구현 장벽이 낮아지고 있음 |
|
- 빠른 실행이 경쟁 우위의 핵심""", |
|
|
|
"evaluator_research": """조사 결과를 객관적으로 평가합니다. |
|
|
|
**실현 가능성 평가** |
|
1. AI 자동 최적화 시스템: 9/10 |
|
- 근거: 다수의 성공 사례, 명확한 ROI, 기술 성숙도 높음 |
|
- 리스크: 초기 데이터 품질, 내부 저항 |
|
- ROI 예측: 6개월 내 250% (조사 결과 검증됨) |
|
|
|
2. 크라우드소싱 혁신 플랫폼: 9/10 |
|
- 근거: 즉시 구현 가능, 낮은 기술 장벽 |
|
- 리스크: 참여도 저하, 아이디어 품질 관리 |
|
- ROI 예측: 1년 내 180% |
|
|
|
3. 디지털 트윈: 7/10 |
|
- 근거: 높은 잠재력, 장기적 가치 |
|
- 리스크: 초기 투자 규모, 기술 복잡도 |
|
- ROI 예측: 18개월 내 200% |
|
|
|
**조사 신뢰성 평가** |
|
- 출처 신뢰도: 평균 0.88 (매우 높음) |
|
- 정보 충분성: 85% (실행에 충분) |
|
- 추가 필요 정보: 산업별 세부 사례, 실패 요인 분석 |
|
|
|
**최종 추천** |
|
1순위: AI 자동 최적화 + 크라우드소싱 통합 접근 |
|
- 두 방안을 결합하여 시너지 극대화 |
|
- 단계적 구현으로 리스크 최소화 |
|
- 3개월 내 가시적 성과 가능 |
|
|
|
2순위: 디지털 트윈 (중장기 프로젝트로 병행)""", |
|
|
|
"supervisor_execution": """평가 결과를 바탕으로 구체적인 실행 지시를 내립니다. |
|
|
|
**통합 실행 전략** |
|
AI 자동 최적화와 크라우드소싱을 결합한 "지능형 혁신 시스템" 구축 |
|
|
|
**1단계: 기반 구축 (1-2주차)** |
|
- AI 자동 최적화 파일럿 프로젝트 선정 |
|
- 크라우드소싱 플랫폼 도구 선정 (IdeaScale 추천) |
|
- 프로젝트팀 구성: PM 1명, ML 엔지니어 2명, 플랫폼 관리자 1명 |
|
- 초기 예산: $50,000 |
|
|
|
**2단계: 파일럿 실행 (3-6주차)** |
|
- 선정 부서에서 AI 최적화 테스트 |
|
- 전사 아이디어 공모 시작 |
|
- 주간 성과 측정 및 조정 |
|
- 리스크: 데이터 품질 → 대응: 데이터 정제 자동화 |
|
|
|
**3단계: 통합 및 확장 (7-12주차)** |
|
- AI가 크라우드소싱 아이디어 자동 평가 |
|
- 최우수 아이디어 자동 시뮬레이션 |
|
- 단계적 전사 확대 |
|
- 성과 지표: 효율성 30% 향상, 혁신 아이디어 100개/월 |
|
|
|
**리스크 대응 계획** |
|
- 기술적 문제: 24/7 모니터링, 롤백 계획 |
|
- 참여 저조: 게임화, 인센티브 강화 |
|
- 품질 이슈: AI 기반 품질 검증 |
|
|
|
**성과 측정** |
|
- 주간: 시스템 성능, 참여율 |
|
- 월간: ROI, 혁신 지표 |
|
- 분기: 전략적 영향 평가""", |
|
|
|
"executor": """즉시 실행 가능한 구체적 계획을 제시합니다. |
|
|
|
**🚀 1주차: 킥오프 및 환경 구축** |
|
|
|
월요일-화요일: 프로젝트팀 구성 및 환경 설정 |
|
```python |
|
# AI 최적화 환경 설정 스크립트 |
|
import tensorflow as tf |
|
from tensorflow import keras |
|
import autokeras as ak |
|
|
|
# 자동 최적화 파이프라인 설정 |
|
class AutoOptimizer: |
|
def __init__(self): |
|
self.model = ak.AutoModel( |
|
project_name='auto_optimization', |
|
max_trials=100 |
|
) |
|
|
|
def optimize(self, data): |
|
# 자동 하이퍼파라미터 튜닝 |
|
self.model.fit(data['X'], data['y']) |
|
return self.model.evaluate(data['X_test'], data['y_test']) |
|
``` |
|
|
|
수요일-금요일: 크라우드소싱 플랫폼 구축 |
|
- IdeaScale 계정 설정 및 커스터마이징 |
|
- 직원 온보딩 자료 작성 |
|
- 평가 기준 및 보상 체계 수립 |
|
|
|
**📊 2-3주차: 파일럿 프로그램 실행** |
|
|
|
데이터 수집 및 AI 모델 훈련: |
|
```python |
|
# 실시간 성능 모니터링 대시보드 |
|
import dash |
|
import plotly.graph_objs as go |
|
|
|
app = dash.Dash(__name__) |
|
app.layout = html.Div([ |
|
dcc.Graph(id='live-performance'), |
|
dcc.Interval(id='graph-update', interval=1000) |
|
]) |
|
|
|
@app.callback(Output('live-performance', 'figure'), |
|
[Input('graph-update', 'n_intervals')]) |
|
def update_metrics(n): |
|
# 실시간 성능 지표 업데이트 |
|
return create_performance_dashboard() |
|
``` |
|
|
|
크라우드소싱 캠페인 런칭: |
|
- 첫 주 챌린지: "효율성 10% 개선 아이디어" |
|
- 일일 리더보드 및 포인트 시스템 |
|
- AI 자동 아이디어 분류 및 초기 평가 |
|
|
|
**🔧 4-6주차: 통합 시스템 구현** |
|
|
|
AI-크라우드소싱 통합 모듈: |
|
```python |
|
class InnovationEngine: |
|
def __init__(self): |
|
self.ai_evaluator = AIIdeaEvaluator() |
|
self.crowd_platform = CrowdsourcingPlatform() |
|
|
|
def process_idea(self, idea): |
|
# 1. AI 초기 평가 |
|
score = self.ai_evaluator.evaluate(idea) |
|
|
|
# 2. 유망 아이디어 자동 시뮬레이션 |
|
if score > 0.7: |
|
simulation_result = self.run_simulation(idea) |
|
|
|
# 3. 실행 우선순위 자동 배정 |
|
return self.prioritize_execution(idea, score, simulation_result) |
|
``` |
|
|
|
**📈 예상 산출물** |
|
1. 구동 가능한 AI 최적화 시스템 |
|
2. 활성화된 크라우드소싱 플랫폼 |
|
3. 통합 대시보드 및 분석 도구 |
|
4. 첫 달 목표: 50개 아이디어, 5개 구현, 15% 효율성 개선""", |
|
|
|
"evaluator_execution": """실행 계획을 평가합니다. |
|
|
|
**계획 완성도: 8.5/10** |
|
|
|
**강점** |
|
- 즉시 실행 가능한 코드와 구체적 일정 제공 |
|
- 단계별 명확한 목표와 산출물 정의 |
|
- 기술 스택이 검증되고 실용적임 |
|
|
|
**개선 필요사항** |
|
1. 데이터 보안 및 프라이버시 대책 미흡 |
|
- 추가 필요: GDPR 준수 체크리스트, 데이터 암호화 방안 |
|
|
|
2. 변화 관리 계획 부족 |
|
- 추가 필요: 직원 교육 프로그램, 저항 관리 전략 |
|
|
|
3. 백업 및 복구 계획 누락 |
|
- 추가 필요: 시스템 장애 시 BCP, 데이터 백업 주기 |
|
|
|
**실행 상 예상 문제점** |
|
1. 초기 데이터 부족 → 해결: 합성 데이터 생성 또는 전이학습 |
|
2. 직원 참여 저조 → 해결: 챔피언 그룹 육성, 조기 성공 사례 홍보 |
|
3. 기술 통합 복잡도 → 해결: 마이크로서비스 아키텍처 채택 |
|
|
|
**추가 제안** |
|
- A/B 테스트 프레임워크 구축 |
|
- 실패 시 빠른 피벗을 위한 의사결정 체계 |
|
- 외부 전문가 자문단 구성 |
|
- 경쟁사 벤치마킹 정기 실시 |
|
|
|
**품질 기준** |
|
- 코드 커버리지 80% 이상 |
|
- 응답 시간 200ms 이하 |
|
- 시스템 가용성 99.9% |
|
- 사용자 만족도 4.5/5 이상""", |
|
|
|
"supervisor_final": """평가를 바탕으로 최종 개선 지시를 내립니다. |
|
|
|
**필수 보완 사항** |
|
|
|
1. **보안 및 컴플라이언스 강화** |
|
- GDPR/CCPA 준수 체크리스트 즉시 작성 |
|
- 전체 데이터 플로우 암호화 구현 |
|
- 접근 권한 관리 시스템 구축 |
|
|
|
2. **변화 관리 프로그램 추가** |
|
- 1주차에 전직원 타운홀 미팅 실시 |
|
- 부서별 챔피언 선정 및 인센티브 제공 |
|
- 주간 성공 사례 공유 세션 운영 |
|
|
|
3. **리스크 관리 체계 구축** |
|
- 24/7 모니터링 대시보드 구현 |
|
- 자동 롤백 시스템 구축 |
|
- 핫라인 및 긴급 대응팀 구성 |
|
|
|
**품질 보증 요구사항** |
|
- 모든 코드는 peer review 필수 |
|
- 자동화된 테스트 커버리지 85% 이상 |
|
- 일일 스탠드업으로 진행상황 체크 |
|
|
|
**성공을 위한 핵심 요소** |
|
1. 경영진의 visible한 지원과 참여 |
|
2. Quick win 사례를 통한 모멘텀 구축 |
|
3. 지속적인 개선과 빠른 피드백 루프 |
|
4. 투명한 성과 공유와 보상 |
|
|
|
**최종 목표** |
|
- 3개월 내 ROI 150% 달성 |
|
- 직원 참여율 80% 이상 |
|
- 시스템 안정성 99.9% 유지""", |
|
|
|
"executor_final": """모든 피드백을 완전히 반영하여 최종 실행 가능 솔루션입니다. |
|
|
|
# 🎯 지능형 혁신 시스템 구축 - 최종 실행 가이드 |
|
|
|
## 📋 Executive Summary |
|
AI 자동 최적화와 크라우드소싱을 통합한 혁신 시스템으로 3개월 내 효율성 30% 향상, ROI 150% 달성을 목표로 합니다. |
|
|
|
## 🚀 1주차: 보안 강화된 프로젝트 시작 |
|
|
|
### Day 1-2: 킥오프 및 보안 체계 구축 |
|
```python |
|
# 보안 강화된 데이터 처리 파이프라인 |
|
from cryptography.fernet import Fernet |
|
import hashlib |
|
from datetime import datetime |
|
|
|
class SecureDataPipeline: |
|
def __init__(self): |
|
self.key = Fernet.generate_key() |
|
self.cipher = Fernet(self.key) |
|
self.audit_log = [] |
|
|
|
def process_data(self, data, user_id): |
|
# GDPR 준수 암호화 |
|
encrypted = self.cipher.encrypt(data.encode()) |
|
|
|
# 감사 로그 |
|
self.audit_log.append({ |
|
'user': user_id, |
|
'action': 'data_process', |
|
'timestamp': datetime.now(), |
|
'data_hash': hashlib.sha256(data.encode()).hexdigest() |
|
}) |
|
|
|
return self.run_optimization(encrypted) |
|
|
|
def run_optimization(self, encrypted_data): |
|
# 암호화된 상태에서 처리 |
|
decrypted = self.cipher.decrypt(encrypted_data) |
|
# AI 최적화 로직 |
|
return optimized_result |
|
``` |
|
|
|
### Day 3: 전직원 타운홀 미팅 |
|
**어젠다 (1시간)** |
|
1. 비전 공유: CEO 발표 (10분) |
|
2. 시스템 소개: 프로젝트 리더 (20분) |
|
3. 혜택 설명: 직원 관점에서 (15분) |
|
4. Q&A 및 피드백 (15분) |
|
|
|
**변화 관리 자료** |
|
```markdown |
|
# 직원을 위한 혁신 시스템 가이드 |
|
|
|
## 당신에게 주는 혜택 |
|
✅ 아이디어가 즉시 실행됩니다 |
|
✅ 기여도에 따른 명확한 보상 |
|
✅ 반복 업무 자동화로 창의적 업무 집중 |
|
✅ 실시간 성과 확인 가능 |
|
|
|
## 참여 방법 (3단계) |
|
1. 플랫폼 로그인 → 아이디어 제출 |
|
2. AI가 자동 평가 → 24시간 내 피드백 |
|
3. 실행 및 보상 → 포인트/보너스 지급 |
|
``` |
|
|
|
### Day 4-5: 기술 인프라 구축 |
|
```python |
|
# 통합 모니터링 대시보드 |
|
import dash |
|
import plotly.graph_objs as go |
|
from dash import dcc, html, Input, Output |
|
import pandas as pd |
|
|
|
class MonitoringDashboard: |
|
def __init__(self): |
|
self.app = dash.Dash(__name__) |
|
self.setup_layout() |
|
self.setup_callbacks() |
|
|
|
def setup_layout(self): |
|
self.app.layout = html.Div([ |
|
html.H1("지능형 혁신 시스템 대시보드"), |
|
|
|
# 실시간 KPI |
|
html.Div([ |
|
dcc.Graph(id='efficiency-gauge'), |
|
dcc.Graph(id='participation-rate'), |
|
dcc.Graph(id='roi-tracker'), |
|
dcc.Graph(id='system-health') |
|
], style={'display': 'flex'}), |
|
|
|
# 알림 시스템 |
|
html.Div(id='alerts', className='alert-box'), |
|
|
|
# 자동 업데이트 |
|
dcc.Interval(id='interval', interval=5000) |
|
]) |
|
|
|
def setup_callbacks(self): |
|
@self.app.callback( |
|
[Output('efficiency-gauge', 'figure'), |
|
Output('alerts', 'children')], |
|
[Input('interval', 'n_intervals')] |
|
) |
|
def update_dashboard(n): |
|
# 실시간 메트릭 수집 |
|
metrics = self.collect_metrics() |
|
|
|
# 임계값 체크 및 알림 |
|
alerts = self.check_thresholds(metrics) |
|
|
|
return self.create_gauge(metrics['efficiency']), alerts |
|
``` |
|
|
|
## 📊 2-3주차: 스마트 파일럿 프로그램 |
|
|
|
### 크라우드소싱 게임화 시스템 |
|
```python |
|
class GamificationEngine: |
|
def __init__(self): |
|
self.levels = { |
|
'Novice': 0, |
|
'Contributor': 100, |
|
'Innovator': 500, |
|
'Champion': 1000, |
|
'Legend': 5000 |
|
} |
|
self.badges = { |
|
'first_idea': '첫 아이디어', |
|
'week_streak': '주간 연속 참여', |
|
'top_rated': '최고 평점', |
|
'implemented': '아이디어 실행됨' |
|
} |
|
|
|
def process_contribution(self, user_id, idea): |
|
points = self.calculate_points(idea) |
|
badges = self.check_badges(user_id, idea) |
|
level_up = self.check_level_up(user_id, points) |
|
|
|
# 실시간 알림 |
|
if level_up: |
|
self.notify_achievement(user_id, level_up) |
|
|
|
return { |
|
'points': points, |
|
'badges': badges, |
|
'level': self.get_user_level(user_id), |
|
'ranking': self.get_ranking(user_id) |
|
} |
|
``` |
|
|
|
### AI 평가 및 시뮬레이션 엔진 |
|
```python |
|
class AIInnovationEvaluator: |
|
def __init__(self): |
|
self.models = { |
|
'feasibility': self.load_model('feasibility_model.h5'), |
|
'impact': self.load_model('impact_model.h5'), |
|
'cost': self.load_model('cost_model.h5') |
|
} |
|
|
|
def evaluate_idea(self, idea_text, metadata): |
|
# NLP 처리 |
|
features = self.extract_features(idea_text) |
|
|
|
# 다차원 평가 |
|
scores = { |
|
'feasibility': self.models['feasibility'].predict(features), |
|
'impact': self.models['impact'].predict(features), |
|
'cost_efficiency': self.models['cost'].predict(features), |
|
'innovation_index': self.calculate_innovation(features) |
|
} |
|
|
|
# 자동 시뮬레이션 트리거 |
|
if scores['feasibility'] > 0.7 and scores['impact'] > 0.8: |
|
simulation_result = self.run_simulation(idea_text, metadata) |
|
scores['simulation'] = simulation_result |
|
|
|
return self.generate_report(scores, idea_text) |
|
``` |
|
|
|
## 🔧 4-6주차: 고급 통합 및 최적화 |
|
|
|
### 자동 실행 파이프라인 |
|
```python |
|
class AutoExecutionPipeline: |
|
def __init__(self): |
|
self.executor = TaskExecutor() |
|
self.validator = ResultValidator() |
|
self.rollback = RollbackManager() |
|
|
|
def execute_approved_idea(self, idea_id): |
|
try: |
|
# 실행 계획 생성 |
|
plan = self.create_execution_plan(idea_id) |
|
|
|
# 단계별 실행 with 체크포인트 |
|
for step in plan.steps: |
|
result = self.executor.execute(step) |
|
|
|
if not self.validator.validate(result): |
|
self.rollback.restore_checkpoint(step.checkpoint) |
|
return self.handle_failure(step, result) |
|
|
|
# 실시간 진행상황 업데이트 |
|
self.update_progress(idea_id, step.completion_rate) |
|
|
|
return self.finalize_execution(idea_id) |
|
|
|
except Exception as e: |
|
self.emergency_rollback(idea_id) |
|
self.alert_team(e) |
|
``` |
|
|
|
### 지속적 개선 시스템 |
|
```python |
|
class ContinuousImprovement: |
|
def __init__(self): |
|
self.ml_pipeline = MLPipeline() |
|
self.feedback_loop = FeedbackLoop() |
|
|
|
def daily_optimization(self): |
|
# 매일 자정 실행 |
|
performance_data = self.collect_daily_metrics() |
|
|
|
# 모델 재훈련 |
|
self.ml_pipeline.retrain(performance_data) |
|
|
|
# A/B 테스트 자동 설정 |
|
experiments = self.design_experiments(performance_data) |
|
|
|
for exp in experiments: |
|
self.run_ab_test(exp) |
|
|
|
# 인사이트 생성 |
|
insights = self.generate_insights(performance_data) |
|
self.distribute_report(insights) |
|
``` |
|
|
|
## 📈 성과 측정 및 보고 체계 |
|
|
|
### 실시간 KPI 대시보드 |
|
```python |
|
kpi_metrics = { |
|
'efficiency_gain': { |
|
'current': 0, |
|
'target': 30, |
|
'unit': '%' |
|
}, |
|
'participation_rate': { |
|
'current': 0, |
|
'target': 80, |
|
'unit': '%' |
|
}, |
|
'ideas_per_month': { |
|
'current': 0, |
|
'target': 100, |
|
'unit': 'count' |
|
}, |
|
'roi': { |
|
'current': 0, |
|
'target': 150, |
|
'unit': '%' |
|
}, |
|
'system_uptime': { |
|
'current': 0, |
|
'target': 99.9, |
|
'unit': '%' |
|
} |
|
} |
|
|
|
# 자동 보고서 생성 |
|
def generate_weekly_report(): |
|
report = f\"\"\" |
|
# 주간 성과 보고서 - {datetime.now().strftime('%Y-%m-%d')} |
|
|
|
## 핵심 성과 |
|
- 효율성 향상: {kpi_metrics['efficiency_gain']['current']}% |
|
- 직원 참여율: {kpi_metrics['participation_rate']['current']}% |
|
- 제출된 아이디어: {kpi_metrics['ideas_per_month']['current']}개 |
|
- ROI: {kpi_metrics['roi']['current']}% |
|
|
|
## 주요 성공 사례 |
|
{get_success_stories()} |
|
|
|
## 다음 주 계획 |
|
{get_next_week_plan()} |
|
\"\"\" |
|
return report |
|
``` |
|
|
|
## 🛡️ 리스크 관리 및 비상 계획 |
|
|
|
### 자동 백업 및 복구 |
|
```bash |
|
#!/bin/bash |
|
# 시간별 자동 백업 스크립트 |
|
BACKUP_DIR="/secure/backups/$(date +%Y%m%d)" |
|
mkdir -p $BACKUP_DIR |
|
|
|
# 데이터베이스 백업 |
|
pg_dump -U postgres innovation_db > $BACKUP_DIR/db_backup_$(date +%H%M).sql |
|
|
|
# 애플리케이션 상태 백업 |
|
kubectl get all --all-namespaces -o yaml > $BACKUP_DIR/k8s_state_$(date +%H%M).yaml |
|
|
|
# S3 업로드 (암호화) |
|
aws s3 cp $BACKUP_DIR s3://innovation-backups/ --recursive --sse |
|
``` |
|
|
|
### 24/7 모니터링 및 알림 |
|
```python |
|
class AlertingSystem: |
|
def __init__(self): |
|
self.thresholds = { |
|
'response_time': 200, # ms |
|
'error_rate': 0.01, # 1% |
|
'cpu_usage': 80, # % |
|
'participation_drop': 20 # % |
|
} |
|
|
|
def monitor(self): |
|
while True: |
|
metrics = self.collect_metrics() |
|
|
|
for metric, value in metrics.items(): |
|
if self.is_threshold_breached(metric, value): |
|
self.trigger_alert(metric, value) |
|
self.auto_remediate(metric) |
|
|
|
time.sleep(60) # 1분마다 체크 |
|
``` |
|
|
|
## 🎯 최종 체크리스트 |
|
|
|
### Week 1 완료 사항 |
|
- [ ] 보안 인프라 구축 완료 |
|
- [ ] 전직원 타운홀 미팅 실시 |
|
- [ ] 챔피언 그룹 선정 |
|
- [ ] 기본 시스템 배포 |
|
|
|
### Week 2-3 완료 사항 |
|
- [ ] 파일럿 부서 선정 및 시작 |
|
- [ ] 첫 아이디어 캠페인 런칭 |
|
- [ ] AI 평가 시스템 가동 |
|
- [ ] 첫 quick win 달성 |
|
|
|
### Week 4-6 완료 사항 |
|
- [ ] 전사 확대 시작 |
|
- [ ] 자동화 파이프라인 완성 |
|
- [ ] KPI 목표 50% 달성 |
|
- [ ] 첫 ROI 리포트 작성 |
|
|
|
## 💡 성공을 위한 팁 |
|
1. 매일 아침 5분 스탠드업 미팅 |
|
2. 주간 성공 사례 전사 공유 |
|
3. 월간 혁신 어워드 시상 |
|
4. 분기별 해커톤 개최 |
|
|
|
--- |
|
*이 시스템은 지속적으로 진화합니다. 피드백은 [email protected]으로!*""" |
|
} |
|
|
|
|
|
if role == "supervisor" and "창조자 AI가 제시한" in messages[0]["content"]: |
|
response = test_responses["supervisor_ideation_review"] |
|
elif role == "supervisor" and "평가자 AI의 종합 평가" in messages[0]["content"]: |
|
response = test_responses["supervisor_execution"] |
|
elif role == "supervisor" and "평가자 AI의 실행 계획 평가" in messages[0]["content"]: |
|
response = test_responses["supervisor_final"] |
|
elif role == "supervisor": |
|
response = test_responses["supervisor_initial"] |
|
elif role == "creator": |
|
response = test_responses["creator"] |
|
elif role == "researcher": |
|
response = test_responses["researcher"] |
|
elif role == "evaluator" and "조사자 AI의 조사 결과" in messages[0]["content"]: |
|
response = test_responses["evaluator_research"] |
|
elif role == "evaluator": |
|
response = test_responses["evaluator_execution"] |
|
elif role == "executor" and "최종 솔루션" in messages[0]["content"]: |
|
response = test_responses["executor_final"] |
|
else: |
|
response = test_responses["executor"] |
|
|
|
yield from self.simulate_streaming(response, role) |
|
return |
|
|
|
|
|
try: |
|
system_prompts = { |
|
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.", |
|
"creator": "당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다.", |
|
"researcher": "당신은 정보를 조사하고 체계적으로 정리하는 조사자 AI입니다.", |
|
"evaluator": "당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.", |
|
"executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다." |
|
} |
|
|
|
full_messages = [ |
|
{"role": "system", "content": system_prompts.get(role, "")}, |
|
*messages |
|
] |
|
|
|
payload = { |
|
"model": self.model_id, |
|
"messages": full_messages, |
|
"max_tokens": 2048, |
|
"temperature": 0.7, |
|
"top_p": 0.8, |
|
"stream": True, |
|
"stream_options": {"include_usage": True} |
|
} |
|
|
|
logger.info(f"API 스트리밍 호출 시작 - Role: {role}") |
|
|
|
response = requests.post( |
|
self.api_url, |
|
headers=self.create_headers(), |
|
json=payload, |
|
stream=True, |
|
timeout=10 |
|
) |
|
|
|
if response.status_code != 200: |
|
logger.error(f"API 오류: {response.status_code}") |
|
yield f"❌ API 오류 ({response.status_code}): {response.text[:200]}" |
|
return |
|
|
|
for line in response.iter_lines(): |
|
if line: |
|
line = line.decode('utf-8') |
|
if line.startswith("data: "): |
|
data = line[6:] |
|
if data == "[DONE]": |
|
break |
|
try: |
|
chunk = json.loads(data) |
|
if "choices" in chunk and chunk["choices"]: |
|
content = chunk["choices"][0].get("delta", {}).get("content", "") |
|
if content: |
|
yield content |
|
except json.JSONDecodeError: |
|
continue |
|
|
|
except requests.exceptions.Timeout: |
|
yield "⏱️ API 호출 시간이 초과되었습니다. 다시 시도해주세요." |
|
except requests.exceptions.ConnectionError: |
|
yield "🔌 API 서버에 연결할 수 없습니다. 인터넷 연결을 확인해주세요." |
|
except Exception as e: |
|
logger.error(f"스트리밍 중 오류: {str(e)}") |
|
yield f"❌ 오류 발생: {str(e)}" |
|
|
|
|
|
llm_system = LLMCollaborativeSystem() |
|
|
|
|
|
internal_history = [] |
|
|
|
def process_query_streaming(user_query: str): |
|
"""향상된 협업 프로세스를 통한 쿼리 처리""" |
|
global internal_history |
|
|
|
if not user_query: |
|
return "", "", "", "", "", "❌ 질문을 입력해주세요." |
|
|
|
all_responses = { |
|
"supervisor": [], |
|
"creator": [], |
|
"researcher": [], |
|
"evaluator": [], |
|
"executor": [] |
|
} |
|
|
|
try: |
|
|
|
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query) |
|
supervisor_initial_response = "" |
|
|
|
supervisor_text = "[초기 분석] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": supervisor_prompt}], |
|
"supervisor" |
|
): |
|
supervisor_initial_response += chunk |
|
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}" |
|
yield supervisor_text, "", "", "", "", "🔄 감독자 AI가 분석 중..." |
|
|
|
all_responses["supervisor"].append(supervisor_initial_response) |
|
|
|
|
|
creator_prompt = llm_system.create_creator_prompt(user_query, supervisor_initial_response) |
|
creator_response = "" |
|
|
|
creator_text = "[혁신 아이디어] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": creator_prompt}], |
|
"creator" |
|
): |
|
creator_response += chunk |
|
creator_text = f"[혁신 아이디어] - {datetime.now().strftime('%H:%M:%S')}\n{creator_response}" |
|
yield supervisor_text, creator_text, "", "", "", "💡 창조자 AI가 아이디어 생성 중..." |
|
|
|
all_responses["creator"].append(creator_response) |
|
|
|
|
|
supervisor_review_prompt = llm_system.create_supervisor_ideation_review_prompt(user_query, creator_response) |
|
supervisor_review_response = "" |
|
|
|
supervisor_text += "\n\n---\n\n[아이디어 검토] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": supervisor_review_prompt}], |
|
"supervisor" |
|
): |
|
supervisor_review_response += chunk |
|
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_review_response}" |
|
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}" |
|
yield supervisor_text, creator_text, "", "", "", "🎯 감독자 AI가 검토 중..." |
|
|
|
all_responses["supervisor"].append(supervisor_review_response) |
|
|
|
|
|
keywords = llm_system.extract_keywords(supervisor_review_response) |
|
logger.info(f"추출된 키워드: {keywords}") |
|
|
|
|
|
researcher_text = "[웹 검색] 🔍 검색 중...\n" |
|
yield supervisor_text, creator_text, researcher_text, "", "", "🔍 웹 검색 수행 중..." |
|
|
|
search_results = {} |
|
total_search_count = 0 |
|
|
|
for keyword in keywords: |
|
results = llm_system.brave_search(keyword) |
|
if results: |
|
search_results[keyword] = results |
|
total_search_count += len(results) |
|
researcher_text += f"✓ '{keyword}' 검색 완료 ({len(results)}개 결과)\n" |
|
yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..." |
|
|
|
synonyms = llm_system.generate_synonyms(keyword) |
|
for synonym in synonyms: |
|
syn_results = llm_system.brave_search(f"{keyword} {synonym}") |
|
if syn_results: |
|
search_results[f"{keyword} ({synonym})"] = syn_results |
|
total_search_count += len(syn_results) |
|
researcher_text += f"✓ 동의어 '{synonym}' 검색 완료 ({len(syn_results)}개 결과)\n" |
|
yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 동의어 '{synonym}' 검색 중..." |
|
|
|
researcher_text += f"\n📊 총 {total_search_count}개의 검색 결과 수집 완료\n" |
|
|
|
|
|
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_review_response, search_results) |
|
researcher_response = "" |
|
|
|
researcher_text = "[조사 결과 정리] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": researcher_prompt}], |
|
"researcher" |
|
): |
|
researcher_response += chunk |
|
researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}" |
|
yield supervisor_text, creator_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..." |
|
|
|
all_responses["researcher"].append(researcher_response) |
|
|
|
|
|
evaluator_research_prompt = llm_system.create_evaluator_research_prompt( |
|
user_query, creator_response, researcher_response |
|
) |
|
evaluator_research_response = "" |
|
|
|
evaluator_text = "[조사 결과 평가] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": evaluator_research_prompt}], |
|
"evaluator" |
|
): |
|
evaluator_research_response += chunk |
|
evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_research_response}" |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "⚖️ 평가자 AI가 평가 중..." |
|
|
|
all_responses["evaluator"].append(evaluator_research_response) |
|
|
|
|
|
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt( |
|
user_query, evaluator_research_response |
|
) |
|
supervisor_execution_response = "" |
|
|
|
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" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": supervisor_execution_prompt}], |
|
"supervisor" |
|
): |
|
supervisor_execution_response += chunk |
|
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}" |
|
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}" |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "🎯 감독자 AI가 지시 중..." |
|
|
|
all_responses["supervisor"].append(supervisor_execution_response) |
|
|
|
|
|
full_context = f""" |
|
창조자 AI의 아이디어: |
|
{creator_response} |
|
|
|
조사자 AI의 조사 결과: |
|
{researcher_response} |
|
|
|
평가자 AI의 평가: |
|
{evaluator_research_response} |
|
""" |
|
|
|
executor_prompt = llm_system.create_executor_prompt( |
|
user_query, supervisor_execution_response, full_context |
|
) |
|
executor_response = "" |
|
|
|
executor_text = "[초기 실행 계획] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": executor_prompt}], |
|
"executor" |
|
): |
|
executor_response += chunk |
|
executor_text = f"[초기 실행 계획] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}" |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🔧 실행자 AI가 계획 중..." |
|
|
|
all_responses["executor"].append(executor_response) |
|
|
|
|
|
evaluator_execution_prompt = llm_system.create_evaluator_execution_prompt( |
|
user_query, executor_response |
|
) |
|
evaluator_execution_response = "" |
|
|
|
evaluator_text += "\n\n---\n\n[실행 계획 평가] 🔄 생성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": evaluator_execution_prompt}], |
|
"evaluator" |
|
): |
|
evaluator_execution_response += chunk |
|
temp_text = f"{all_responses['evaluator'][0]}\n\n---\n\n[실행 계획 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_execution_response}" |
|
evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}" |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "⚖️ 평가자 AI가 검증 중..." |
|
|
|
all_responses["evaluator"].append(evaluator_execution_response) |
|
|
|
|
|
supervisor_final_prompt = llm_system.create_supervisor_final_prompt( |
|
user_query, evaluator_execution_response |
|
) |
|
supervisor_final_response = "" |
|
|
|
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" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": supervisor_final_prompt}], |
|
"supervisor" |
|
): |
|
supervisor_final_response += chunk |
|
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}" |
|
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}" |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🎯 감독자 AI가 최종 검토 중..." |
|
|
|
all_responses["supervisor"].append(supervisor_final_response) |
|
|
|
|
|
executor_final_prompt = llm_system.create_executor_final_prompt( |
|
user_query, executor_response, supervisor_final_response, full_context |
|
) |
|
final_executor_response = "" |
|
|
|
executor_text += "\n\n---\n\n[최종 실행 솔루션] 🔄 작성 중...\n" |
|
for chunk in llm_system.call_llm_streaming( |
|
[{"role": "user", "content": executor_final_prompt}], |
|
"executor" |
|
): |
|
final_executor_response += chunk |
|
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}" |
|
executor_text = temp_text |
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "📄 최종 솔루션 작성 중..." |
|
|
|
all_responses["executor"].append(final_executor_response) |
|
|
|
|
|
final_summary = f"""## 🎯 최적화된 실용적 문제 해결 보고서 |
|
|
|
### 📌 사용자 질문 |
|
{user_query} |
|
|
|
### 🚀 최종 실행 솔루션 |
|
{final_executor_response} |
|
|
|
--- |
|
|
|
<details> |
|
<summary>📋 전체 협력 프로세스 보기</summary> |
|
|
|
#### 1️⃣ 거시적 분석 (감독자 AI) |
|
{all_responses['supervisor'][0]} |
|
|
|
#### 2️⃣ 혁신적 아이디어 (창조자 AI) |
|
{all_responses['creator'][0]} |
|
|
|
#### 3️⃣ 아이디어 검토 및 조사 지시 (감독자 AI) |
|
{all_responses['supervisor'][1]} |
|
|
|
#### 4️⃣ 조사 결과 (조사자 AI) |
|
{all_responses['researcher'][0]} |
|
|
|
#### 5️⃣ 조사 결과 평가 (평가자 AI) |
|
{all_responses['evaluator'][0]} |
|
|
|
#### 6️⃣ 실행 지시 (감독자 AI) |
|
{all_responses['supervisor'][2]} |
|
|
|
#### 7️⃣ 초기 실행 계획 (실행자 AI) |
|
{all_responses['executor'][0]} |
|
|
|
#### 8️⃣ 실행 계획 평가 (평가자 AI) |
|
{all_responses['evaluator'][1]} |
|
|
|
#### 9️⃣ 최종 지시 (감독자 AI) |
|
{all_responses['supervisor'][3]} |
|
|
|
</details> |
|
|
|
--- |
|
*이 보고서는 5개 AI의 협력적 프로세스를 통해 최적화된 실용적 해결책을 제공합니다.* |
|
*프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행*""" |
|
|
|
internal_history.append((user_query, final_summary)) |
|
|
|
|
|
yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, final_summary |
|
|
|
except Exception as e: |
|
error_msg = f"❌ 처리 중 오류: {str(e)}" |
|
yield "", "", "", "", "", error_msg |
|
|
|
def clear_all(): |
|
"""모든 내용 초기화""" |
|
global internal_history |
|
internal_history = [] |
|
return "", "", "", "", "", "🔄 초기화되었습니다." |
|
|
|
|
|
css = """ |
|
.gradio-container { |
|
font-family: 'Arial', sans-serif; |
|
} |
|
.supervisor-box textarea { |
|
border-left: 4px solid #667eea !important; |
|
background-color: #f3f4f6 !important; |
|
} |
|
.creator-box textarea { |
|
border-left: 4px solid #f59e0b !important; |
|
background-color: #fffbeb !important; |
|
} |
|
.researcher-box textarea { |
|
border-left: 4px solid #10b981 !important; |
|
background-color: #ecfdf5 !important; |
|
} |
|
.evaluator-box textarea { |
|
border-left: 4px solid #ef4444 !important; |
|
background-color: #fef2f2 !important; |
|
} |
|
.executor-box textarea { |
|
border-left: 4px solid #764ba2 !important; |
|
background-color: #faf5ff !important; |
|
} |
|
""" |
|
|
|
with gr.Blocks(title="최적화된 협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app: |
|
gr.Markdown( |
|
""" |
|
# 🚀 최적화된 최고의 실용적 문제 해결자 |
|
### 5개 AI의 협력적 프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행 |
|
""" |
|
) |
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
gr.Markdown(""" |
|
## 🎯 향상된 기능 |
|
- **창조자 AI**: 혁신적이고 파괴적인 아이디어 생성 |
|
- **평가자 AI**: 객관적이고 비판적인 검증 및 평가 |
|
- **강화된 프로세스**: 11단계 협력적 문제 해결 |
|
- **실용성 극대화**: 즉시 실행 가능한 솔루션 제공 |
|
""") |
|
|
|
user_input = gr.Textbox( |
|
label="질문 입력", |
|
placeholder="예: 우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?", |
|
lines=3 |
|
) |
|
|
|
with gr.Row(): |
|
submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2) |
|
clear_btn = gr.Button("🗑️ 초기화", scale=1) |
|
|
|
status_text = gr.Textbox( |
|
label="상태", |
|
interactive=False, |
|
value="대기 중...", |
|
max_lines=1 |
|
) |
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
with gr.Accordion("📊 최종 실행 솔루션", open=True): |
|
final_output = gr.Markdown( |
|
value="*질문을 입력하면 최종 솔루션이 여기에 표시됩니다.*" |
|
) |
|
|
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
gr.Markdown("### 🧠 감독자 AI (전략적 지휘)") |
|
supervisor_output = gr.Textbox( |
|
label="", |
|
lines=15, |
|
max_lines=20, |
|
interactive=False, |
|
elem_classes=["supervisor-box"] |
|
) |
|
|
|
with gr.Column(): |
|
gr.Markdown("### 💡 창조자 AI (혁신적 아이디어)") |
|
creator_output = gr.Textbox( |
|
label="", |
|
lines=15, |
|
max_lines=20, |
|
interactive=False, |
|
elem_classes=["creator-box"] |
|
) |
|
|
|
with gr.Column(): |
|
gr.Markdown("### 🔍 조사자 AI (정보 수집)") |
|
researcher_output = gr.Textbox( |
|
label="", |
|
lines=15, |
|
max_lines=20, |
|
interactive=False, |
|
elem_classes=["researcher-box"] |
|
) |
|
|
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
gr.Markdown("### ⚖️ 평가자 AI (객관적 평가)") |
|
evaluator_output = gr.Textbox( |
|
label="", |
|
lines=15, |
|
max_lines=20, |
|
interactive=False, |
|
elem_classes=["evaluator-box"] |
|
) |
|
|
|
with gr.Column(): |
|
gr.Markdown("### 🔧 실행자 AI (실용적 구현)") |
|
executor_output = gr.Textbox( |
|
label="", |
|
lines=15, |
|
max_lines=20, |
|
interactive=False, |
|
elem_classes=["executor-box"] |
|
) |
|
|
|
|
|
gr.Markdown(""" |
|
--- |
|
### 🔄 협업 프로세스 흐름도 |
|
``` |
|
사용자 질문 |
|
↓ |
|
[1] 감독자 AI (초기 분석) |
|
↓ |
|
[2] 창조자 AI (혁신 아이디어) |
|
↓ |
|
[3] 감독자 AI (아이디어 검토) |
|
↓ |
|
[4] 조사자 AI (웹 검색 & 정리) |
|
↓ |
|
[5] 평가자 AI (조사 결과 평가) |
|
↓ |
|
[6] 감독자 AI (실행 지시) |
|
↓ |
|
[7] 실행자 AI (초기 계획) |
|
↓ |
|
[8] 평가자 AI (계획 평가) |
|
↓ |
|
[9] 감독자 AI (최종 지시) |
|
↓ |
|
[10] 실행자 AI (최종 솔루션) |
|
↓ |
|
최적화된 실용적 해결책 |
|
``` |
|
""") |
|
|
|
|
|
gr.Examples( |
|
examples=[ |
|
"우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?", |
|
"원격 근무 환경에서 팀 생산성을 2배로 높이는 구체적인 전략은?", |
|
"스타트업이 6개월 내에 수익을 3배 늘릴 수 있는 실행 가능한 방법은?", |
|
"기존 제품을 완전히 혁신하여 시장을 선도할 수 있는 아이디어는?", |
|
"AI를 활용해 운영 비용을 50% 절감하는 실질적인 방안은?" |
|
], |
|
inputs=user_input, |
|
label="💡 예제 질문" |
|
) |
|
|
|
|
|
submit_btn.click( |
|
fn=process_query_streaming, |
|
inputs=[user_input], |
|
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output] |
|
).then( |
|
fn=lambda: "", |
|
outputs=[user_input] |
|
) |
|
|
|
user_input.submit( |
|
fn=process_query_streaming, |
|
inputs=[user_input], |
|
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output] |
|
).then( |
|
fn=lambda: "", |
|
outputs=[user_input] |
|
) |
|
|
|
clear_btn.click( |
|
fn=clear_all, |
|
outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, status_text] |
|
) |
|
|
|
if __name__ == "__main__": |
|
app.queue() |
|
app.launch( |
|
server_name="0.0.0.0", |
|
server_port=7860, |
|
share=True, |
|
show_error=True |
|
) |