Update app.py
Browse files
app.py
CHANGED
@@ -4,8 +4,9 @@ import json
|
|
4 |
import requests
|
5 |
from datetime import datetime
|
6 |
import time
|
7 |
-
from typing import List, Dict, Any, Generator
|
8 |
import logging
|
|
|
9 |
|
10 |
# 로깅 설정
|
11 |
logging.basicConfig(level=logging.INFO)
|
@@ -13,7 +14,9 @@ logger = logging.getLogger(__name__)
|
|
13 |
|
14 |
# 환경 변수에서 토큰 가져오기
|
15 |
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
|
|
|
16 |
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
|
|
17 |
MODEL_ID = "dep89a2fld32mcm"
|
18 |
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
19 |
|
@@ -23,12 +26,16 @@ conversation_history = []
|
|
23 |
class LLMCollaborativeSystem:
|
24 |
def __init__(self):
|
25 |
self.token = FRIENDLI_TOKEN
|
|
|
26 |
self.api_url = API_URL
|
|
|
27 |
self.model_id = MODEL_ID
|
28 |
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
|
29 |
|
30 |
if self.test_mode:
|
31 |
logger.warning("테스트 모드로 실행됩니다.")
|
|
|
|
|
32 |
|
33 |
def create_headers(self):
|
34 |
"""API 헤더 생성"""
|
@@ -37,34 +44,157 @@ class LLMCollaborativeSystem:
|
|
37 |
"Content-Type": "application/json"
|
38 |
}
|
39 |
|
40 |
-
def
|
41 |
-
"""
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
사용자 질문: {user_query}
|
46 |
|
47 |
-
|
48 |
-
|
|
|
|
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
사용자 질문: {user_query}
|
55 |
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
"""실행자 AI 프롬프트 생성"""
|
60 |
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
61 |
|
62 |
-
감독자 AI의 지침:
|
63 |
-
{supervisor_guidance}
|
64 |
-
|
65 |
사용자 질문: {user_query}
|
66 |
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
|
70 |
"""테스트 모드에서 스트리밍 시뮬레이션"""
|
@@ -72,7 +202,7 @@ class LLMCollaborativeSystem:
|
|
72 |
for i in range(0, len(words), 3):
|
73 |
chunk = " ".join(words[i:i+3])
|
74 |
yield chunk + " "
|
75 |
-
time.sleep(0.
|
76 |
|
77 |
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]:
|
78 |
"""스트리밍 LLM API 호출"""
|
@@ -96,54 +226,125 @@ class LLMCollaborativeSystem:
|
|
96 |
3. **기대 효과와 과제**
|
97 |
- 예상되는 긍정적 성과를 분석합니다
|
98 |
- 잠재적 도전 과제를 식별합니다
|
99 |
-
- 지속가능한 발전
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
-
"executor": """
|
102 |
-
|
103 |
-
|
104 |
-
-
|
105 |
-
|
106 |
-
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
-
|
112 |
-
|
113 |
-
|
114 |
-
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
|
123 |
-
"supervisor_review": """실행자 AI의 계획을 검토한 결과,
|
124 |
|
125 |
**강점**
|
126 |
-
-
|
127 |
-
-
|
128 |
-
-
|
129 |
|
130 |
-
|
131 |
-
1. 각 단계별
|
132 |
-
2.
|
133 |
-
3.
|
134 |
|
135 |
**추가 권장사항**
|
136 |
-
-
|
137 |
-
-
|
138 |
-
-
|
139 |
}
|
140 |
|
141 |
-
if role == "supervisor" and
|
|
|
|
|
|
|
|
|
142 |
response = test_responses["supervisor_initial"]
|
143 |
-
elif role == "
|
144 |
-
response = test_responses["
|
145 |
else:
|
146 |
-
response = test_responses["
|
147 |
|
148 |
yield from self.simulate_streaming(response, role)
|
149 |
return
|
@@ -152,6 +353,7 @@ class LLMCollaborativeSystem:
|
|
152 |
try:
|
153 |
system_prompts = {
|
154 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
|
|
155 |
"executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다."
|
156 |
}
|
157 |
|
@@ -215,35 +417,76 @@ llm_system = LLMCollaborativeSystem()
|
|
215 |
def process_query_streaming(user_query: str, history: List):
|
216 |
"""스트리밍을 지원하는 쿼리 처리"""
|
217 |
if not user_query:
|
218 |
-
return history, "", "", "", "❌ 질문을 입력해주세요."
|
219 |
|
220 |
conversation_log = []
|
221 |
-
all_responses = {"supervisor": [], "executor": []}
|
222 |
|
223 |
try:
|
224 |
-
# 1단계: 감독자 AI 초기 분석
|
225 |
-
supervisor_prompt = llm_system.
|
226 |
-
|
227 |
|
228 |
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
229 |
for chunk in llm_system.call_llm_streaming(
|
230 |
[{"role": "user", "content": supervisor_prompt}],
|
231 |
"supervisor"
|
232 |
):
|
233 |
-
|
234 |
-
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{
|
235 |
-
yield history, supervisor_text, "", "", "🔄 감독자 AI가 분석 중..."
|
236 |
-
|
237 |
-
all_responses["supervisor"].append(
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
247 |
executor_response = ""
|
248 |
|
249 |
executor_text = "[세부 구현] 🔄 생성 중...\n"
|
@@ -253,30 +496,32 @@ def process_query_streaming(user_query: str, history: List):
|
|
253 |
):
|
254 |
executor_response += chunk
|
255 |
executor_text = f"[세부 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
256 |
-
yield history, supervisor_text, executor_text, "", "
|
257 |
|
258 |
all_responses["executor"].append(executor_response)
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
|
|
|
|
|
|
268 |
review_response = ""
|
|
|
269 |
|
270 |
-
supervisor_text += "\n\n---\n\n[검토 및 피드백] 🔄 생성 중...\n"
|
271 |
for chunk in llm_system.call_llm_streaming(
|
272 |
[{"role": "user", "content": review_prompt}],
|
273 |
"supervisor"
|
274 |
):
|
275 |
review_response += chunk
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
all_responses["supervisor"].append(review_response)
|
280 |
|
281 |
# 최종 결과 생성
|
282 |
final_summary = f"""## 🤝 협력적 AI 시스템 종합 답변
|
@@ -287,27 +532,33 @@ def process_query_streaming(user_query: str, history: List):
|
|
287 |
### 🔍 거시적 분석 (감독자 AI)
|
288 |
{all_responses['supervisor'][0]}
|
289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
290 |
### 💡 세부 구현 (실행자 AI)
|
291 |
{executor_response}
|
292 |
|
293 |
-
### ✨
|
294 |
{review_response}
|
295 |
|
296 |
---
|
297 |
-
*이 답변은
|
298 |
|
299 |
# 히스토리 업데이트
|
300 |
new_history = history + [(user_query, final_summary)]
|
301 |
|
302 |
-
yield new_history, supervisor_text, executor_text, final_summary, "✅ 분석 완료!"
|
303 |
|
304 |
except Exception as e:
|
305 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
306 |
-
yield history, "", "", error_msg, error_msg
|
307 |
|
308 |
def clear_all():
|
309 |
"""모든 내용 초기화"""
|
310 |
-
return [], "", "", "", "🔄 초기화되었습니다."
|
311 |
|
312 |
# Gradio 인터페이스
|
313 |
css = """
|
@@ -318,6 +569,10 @@ css = """
|
|
318 |
border-left: 4px solid #667eea !important;
|
319 |
padding-left: 10px !important;
|
320 |
}
|
|
|
|
|
|
|
|
|
321 |
.executor-box textarea {
|
322 |
border-left: 4px solid #764ba2 !important;
|
323 |
padding-left: 10px !important;
|
@@ -327,16 +582,19 @@ css = """
|
|
327 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
328 |
gr.Markdown(
|
329 |
f"""
|
330 |
-
# 🤝 협력적 LLM 시스템
|
331 |
|
332 |
-
>
|
333 |
|
334 |
-
**상태**:
|
|
|
|
|
335 |
|
336 |
**시스템 구조:**
|
337 |
-
- 🧠 **감독자 AI**: 전체적인
|
338 |
-
-
|
339 |
-
-
|
|
|
340 |
"""
|
341 |
)
|
342 |
|
@@ -345,7 +603,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
345 |
with gr.Column(scale=1):
|
346 |
chatbot = gr.Chatbot(
|
347 |
label="💬 대화 기록",
|
348 |
-
height=
|
349 |
show_copy_button=True,
|
350 |
bubble_full_width=False
|
351 |
)
|
@@ -375,25 +633,38 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
375 |
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
376 |
)
|
377 |
|
|
|
378 |
with gr.Row():
|
379 |
# 감독자 AI 출력
|
380 |
with gr.Column():
|
381 |
gr.Markdown("### 🧠 감독자 AI (거시적 분석)")
|
382 |
supervisor_output = gr.Textbox(
|
383 |
label="",
|
384 |
-
lines=
|
385 |
-
max_lines=
|
386 |
interactive=False,
|
387 |
elem_classes=["supervisor-box"]
|
388 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
389 |
|
390 |
# 실행자 AI 출력
|
391 |
with gr.Column():
|
392 |
gr.Markdown("### 👁️ 실행자 AI (미시적 구현)")
|
393 |
executor_output = gr.Textbox(
|
394 |
label="",
|
395 |
-
lines=
|
396 |
-
max_lines=
|
397 |
interactive=False,
|
398 |
elem_classes=["executor-box"]
|
399 |
)
|
@@ -401,11 +672,11 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
401 |
# 예제
|
402 |
gr.Examples(
|
403 |
examples=[
|
404 |
-
"기계학습 모델의 성능을 향상시키는 방법은?",
|
405 |
-
"효과적인 프로젝트 관리
|
406 |
-
"지속 가능한 비즈니스
|
407 |
-
"
|
408 |
-
"팀의 생산성을 높이는 방법은?"
|
409 |
],
|
410 |
inputs=user_input,
|
411 |
label="💡 예제 질문"
|
@@ -415,7 +686,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
415 |
submit_btn.click(
|
416 |
fn=process_query_streaming,
|
417 |
inputs=[user_input, chatbot],
|
418 |
-
outputs=[chatbot, supervisor_output, executor_output, final_output, status_text]
|
419 |
).then(
|
420 |
fn=lambda: "",
|
421 |
outputs=[user_input]
|
@@ -424,7 +695,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
424 |
user_input.submit(
|
425 |
fn=process_query_streaming,
|
426 |
inputs=[user_input, chatbot],
|
427 |
-
outputs=[chatbot, supervisor_output, executor_output, final_output, status_text]
|
428 |
).then(
|
429 |
fn=lambda: "",
|
430 |
outputs=[user_input]
|
@@ -432,7 +703,7 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
432 |
|
433 |
clear_btn.click(
|
434 |
fn=clear_all,
|
435 |
-
outputs=[chatbot, supervisor_output, executor_output, final_output, status_text]
|
436 |
)
|
437 |
|
438 |
gr.Markdown(
|
@@ -440,13 +711,18 @@ with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css)
|
|
440 |
---
|
441 |
### 📝 사용 방법
|
442 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
443 |
-
2.
|
444 |
-
3.
|
|
|
445 |
|
446 |
### ⚙️ 환경 설정
|
447 |
-
-
|
|
|
448 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
449 |
-
|
|
|
|
|
|
|
450 |
"""
|
451 |
)
|
452 |
|
|
|
4 |
import requests
|
5 |
from datetime import datetime
|
6 |
import time
|
7 |
+
from typing import List, Dict, Any, Generator, Tuple
|
8 |
import logging
|
9 |
+
import re
|
10 |
|
11 |
# 로깅 설정
|
12 |
logging.basicConfig(level=logging.INFO)
|
|
|
14 |
|
15 |
# 환경 변수에서 토큰 가져오기
|
16 |
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
|
17 |
+
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN")
|
18 |
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
|
19 |
+
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
|
20 |
MODEL_ID = "dep89a2fld32mcm"
|
21 |
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"
|
22 |
|
|
|
26 |
class LLMCollaborativeSystem:
|
27 |
def __init__(self):
|
28 |
self.token = FRIENDLI_TOKEN
|
29 |
+
self.bapi_token = BAPI_TOKEN
|
30 |
self.api_url = API_URL
|
31 |
+
self.brave_url = BRAVE_SEARCH_URL
|
32 |
self.model_id = MODEL_ID
|
33 |
self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
|
34 |
|
35 |
if self.test_mode:
|
36 |
logger.warning("테스트 모드로 실행됩니다.")
|
37 |
+
if self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
38 |
+
logger.warning("Brave API 토큰이 설정되지 않았습니다.")
|
39 |
|
40 |
def create_headers(self):
|
41 |
"""API 헤더 생성"""
|
|
|
44 |
"Content-Type": "application/json"
|
45 |
}
|
46 |
|
47 |
+
def create_brave_headers(self):
|
48 |
+
"""Brave API 헤더 생성"""
|
49 |
+
return {
|
50 |
+
"Accept": "application/json",
|
51 |
+
"Accept-Encoding": "gzip",
|
52 |
+
"X-Subscription-Token": self.bapi_token
|
53 |
+
}
|
54 |
+
|
55 |
+
def create_supervisor_initial_prompt(self, user_query: str) -> str:
|
56 |
+
"""감독자 AI 초기 프롬프트 생성"""
|
57 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
58 |
|
59 |
사용자 질문: {user_query}
|
60 |
|
61 |
+
이 질문에 대해:
|
62 |
+
1. 전체적인 접근 방향과 프레임워크를 제시하세요
|
63 |
+
2. 핵심 요소와 고려사항을 구조화하여 설명하세요
|
64 |
+
3. 이 주제에 대해 조사가 필요한 5-7개의 구체적인 키워드나 검색어를 제시하세요
|
65 |
|
66 |
+
키워드는 다음 형식으로 제시하세요:
|
67 |
+
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
|
68 |
+
|
69 |
+
def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
|
70 |
+
"""조사자 AI 프롬프트 생성"""
|
71 |
+
search_summary = ""
|
72 |
+
for keyword, results in search_results.items():
|
73 |
+
search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n"
|
74 |
+
for i, result in enumerate(results[:3], 1):
|
75 |
+
search_summary += f"{i}. {result.get('title', 'N/A')}\n"
|
76 |
+
search_summary += f" - {result.get('description', 'N/A')}\n"
|
77 |
+
search_summary += f" - 출처: {result.get('url', 'N/A')}\n"
|
78 |
+
|
79 |
+
return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.
|
80 |
|
81 |
사용자 질문: {user_query}
|
82 |
|
83 |
+
감독자 AI의 지침:
|
84 |
+
{supervisor_guidance}
|
85 |
+
|
86 |
+
브레이브 검색 결과:
|
87 |
+
{search_summary}
|
88 |
+
|
89 |
+
위 검색 결과를 바탕으로:
|
90 |
+
1. 각 키워드별로 중요한 정보를 정리하세요
|
91 |
+
2. 신뢰할 수 있는 출처를 명시하세요
|
92 |
+
3. 실행자 AI가 활용할 수 있는 구체적인 데이터와 사실을 추출하세요
|
93 |
+
4. 최신 트렌드나 중요한 통계가 있다면 강조하세요"""
|
94 |
|
95 |
+
def create_supervisor_execution_prompt(self, user_query: str, research_summary: str) -> str:
|
96 |
+
"""감독자 AI의 실행 지시 프롬프트"""
|
97 |
+
return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
98 |
+
|
99 |
+
사용자 질문: {user_query}
|
100 |
+
|
101 |
+
조사자 AI가 정리한 조사 내용:
|
102 |
+
{research_summary}
|
103 |
+
|
104 |
+
위 조사 내용을 기반으로 실행자 AI에게 아주 구체적인 지시를 내려주세요:
|
105 |
+
1. 조사된 정보를 어떻게 활용할지 명확히 지시하세요
|
106 |
+
2. 실행 가능한 단계별 작업을 구체적으로 제시하세요
|
107 |
+
3. 각 단계에서 ���고해야 할 조사 내용을 명시하세요
|
108 |
+
4. 예상되는 결과물의 형태를 구체적으로 설명하세요"""
|
109 |
+
|
110 |
+
def create_executor_prompt(self, user_query: str, supervisor_guidance: str, research_summary: str) -> str:
|
111 |
"""실행자 AI 프롬프트 생성"""
|
112 |
return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.
|
113 |
|
|
|
|
|
|
|
114 |
사용자 질문: {user_query}
|
115 |
|
116 |
+
조사자 AI가 정리한 조사 내용:
|
117 |
+
{research_summary}
|
118 |
+
|
119 |
+
감독자 AI의 구체적인 지시:
|
120 |
+
{supervisor_guidance}
|
121 |
+
|
122 |
+
위 조사 내용과 지시사항을 바탕으로:
|
123 |
+
1. 조사된 정보를 적극 활용하여 구체적인 실행 계획을 작성하세요
|
124 |
+
2. 각 단계별로 참고한 조사 내용을 명시하세요
|
125 |
+
3. 실제로 적용 가능한 구체적인 방법론을 제시하세요
|
126 |
+
4. 예상되는 성과와 측정 방법을 포함하세요"""
|
127 |
+
|
128 |
+
def extract_keywords(self, supervisor_response: str) -> List[str]:
|
129 |
+
"""감독자 응답에서 키워드 추출"""
|
130 |
+
keywords = []
|
131 |
+
|
132 |
+
# [검색 키워드]: 형식으로 키워드 찾기
|
133 |
+
keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE)
|
134 |
+
if keyword_match:
|
135 |
+
keyword_str = keyword_match.group(1)
|
136 |
+
keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
|
137 |
+
|
138 |
+
# 키워드가 없으면 기본 키워드 생성
|
139 |
+
if not keywords:
|
140 |
+
keywords = ["best practices", "implementation guide", "case studies", "latest trends", "success factors"]
|
141 |
+
|
142 |
+
return keywords[:7] # 최대 7개로 제한
|
143 |
+
|
144 |
+
def brave_search(self, query: str) -> List[Dict]:
|
145 |
+
"""Brave Search API 호출"""
|
146 |
+
if self.test_mode or self.bapi_token == "YOUR_BRAVE_API_TOKEN":
|
147 |
+
# 테스트 모드에서는 시뮬레이션된 결과 반환
|
148 |
+
return [
|
149 |
+
{
|
150 |
+
"title": f"Best Practices for {query}",
|
151 |
+
"description": f"Comprehensive guide on implementing {query} with proven methodologies and real-world examples.",
|
152 |
+
"url": f"https://example.com/{query.replace(' ', '-')}"
|
153 |
+
},
|
154 |
+
{
|
155 |
+
"title": f"Latest Trends in {query}",
|
156 |
+
"description": f"Analysis of current trends and future directions in {query}, including market insights and expert opinions.",
|
157 |
+
"url": f"https://trends.example.com/{query.replace(' ', '-')}"
|
158 |
+
},
|
159 |
+
{
|
160 |
+
"title": f"{query}: Case Studies and Success Stories",
|
161 |
+
"description": f"Real-world implementations of {query} across various industries with measurable results.",
|
162 |
+
"url": f"https://casestudies.example.com/{query.replace(' ', '-')}"
|
163 |
+
}
|
164 |
+
]
|
165 |
+
|
166 |
+
try:
|
167 |
+
params = {
|
168 |
+
"q": query,
|
169 |
+
"count": 5,
|
170 |
+
"safesearch": "moderate",
|
171 |
+
"freshness": "pw" # Past week for recent results
|
172 |
+
}
|
173 |
+
|
174 |
+
response = requests.get(
|
175 |
+
self.brave_url,
|
176 |
+
headers=self.create_brave_headers(),
|
177 |
+
params=params,
|
178 |
+
timeout=10
|
179 |
+
)
|
180 |
+
|
181 |
+
if response.status_code == 200:
|
182 |
+
data = response.json()
|
183 |
+
results = []
|
184 |
+
for item in data.get("web", {}).get("results", [])[:5]:
|
185 |
+
results.append({
|
186 |
+
"title": item.get("title", ""),
|
187 |
+
"description": item.get("description", ""),
|
188 |
+
"url": item.get("url", "")
|
189 |
+
})
|
190 |
+
return results
|
191 |
+
else:
|
192 |
+
logger.error(f"Brave API 오류: {response.status_code}")
|
193 |
+
return []
|
194 |
+
|
195 |
+
except Exception as e:
|
196 |
+
logger.error(f"Brave 검색 중 오류: {str(e)}")
|
197 |
+
return []
|
198 |
|
199 |
def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
|
200 |
"""테스트 모드에서 스트리밍 시뮬레이션"""
|
|
|
202 |
for i in range(0, len(words), 3):
|
203 |
chunk = " ".join(words[i:i+3])
|
204 |
yield chunk + " "
|
205 |
+
time.sleep(0.05)
|
206 |
|
207 |
def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]:
|
208 |
"""스트리밍 LLM API 호출"""
|
|
|
226 |
3. **기대 효과와 과제**
|
227 |
- 예상되는 긍정적 성과를 분석합니다
|
228 |
- 잠재적 도전 과제를 식별합니다
|
229 |
+
- 지속가능한 발전 ��향을 제시합니다
|
230 |
+
|
231 |
+
[검색 키워드]: machine learning optimization, performance improvement strategies, model efficiency techniques, hyperparameter tuning best practices, latest ML trends 2024""",
|
232 |
+
|
233 |
+
"researcher": """조사 결과를 종합하여 다음과 같이 정리했습니다.
|
234 |
+
|
235 |
+
**1. Machine Learning Optimization**
|
236 |
+
- 최신 연구에 따르면 모델 최적화의 핵심은 아키텍처 설계와 훈련 전략의 균형입니다
|
237 |
+
- AutoML 도구들이 하이퍼파라미터 튜닝을 자동화하여 효율성을 크게 향상시킵니다
|
238 |
+
- 출처: ML Conference 2024, Google Research
|
239 |
+
|
240 |
+
**2. Performance Improvement Strategies**
|
241 |
+
- 데이터 품질 개선이 모델 성능 향상의 80%를 차지한다는 연구 결과
|
242 |
+
- 앙상블 기법과 전이학습이 주요 성능 개선 방법으로 입증됨
|
243 |
+
- 벤치마크: ImageNet에서 95% 이상의 정확도 달성 사례
|
244 |
+
|
245 |
+
**3. Model Efficiency Techniques**
|
246 |
+
- 모델 경량화(Pruning, Quantization)로 추론 속도 10배 향상 가능
|
247 |
+
- Knowledge Distillation으로 모델 크기 90% 감소, 성능 유지
|
248 |
+
- 최신 트렌드: Efficient Transformers, Neural Architecture Search
|
249 |
+
|
250 |
+
**4. 실제 적용 사례**
|
251 |
+
- Netflix: 추천 시스템 개선으로 사용자 만족도 35% 향상
|
252 |
+
- Tesla: 실시간 객체 인식 속도 50% 개선
|
253 |
+
- OpenAI: GPT 모델 효율성 개선으로 비용 70% 절감""",
|
254 |
+
|
255 |
+
"supervisor_execution": """조사 내용을 바탕으로 실행자 AI에게 다음과 같이 구체적으로 지시합니다.
|
256 |
+
|
257 |
+
**1단계: 현재 모델 진단 (1주차)**
|
258 |
+
- 조사된 벤치마크 기준으로 현재 모델 성능 평가
|
259 |
+
- Netflix 사례를 참고하여 주요 병목 지점 식별
|
260 |
+
- AutoML 도구를 활용한 초기 최적화 가능성 탐색
|
261 |
+
|
262 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
263 |
+
- 조사 결과의 "80% 규칙"에 따라 데이터 정제 우선 실행
|
264 |
+
- 데이터 증강 기법 적용 (조사된 최신 기법 활용)
|
265 |
+
- A/B 테스트로 개선 효과 측정
|
266 |
+
|
267 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
268 |
+
- Knowledge Distillation 적용하여 모델 경량화
|
269 |
+
- 조사된 Pruning 기법으로 추론 속도 개선
|
270 |
+
- Tesla 사례의 실시간 처리 최적화 기법 벤치마킹
|
271 |
+
|
272 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
273 |
+
- OpenAI 사례의 비용 절감 지표 적용
|
274 |
+
- 조사된 성능 지표로 개선율 측정
|
275 |
+
- 단계적 배포 전략 수립""",
|
276 |
|
277 |
+
"executor": """감독자의 지시와 조사 내용을 기반으로 구체적인 실행 계획을 수립합니다.
|
278 |
+
|
279 |
+
**1단계: 현재 모델 진단 (1주차)**
|
280 |
+
- 월요일-화요일: MLflow를 사용한 현재 모델 메트릭 수집
|
281 |
+
* 조사 결과 참고: Netflix가 사용한 핵심 지표 (정확도, 지연시간, 처리량)
|
282 |
+
- 수요일-목요일: AutoML 도구 (Optuna, Ray Tune) 설정 및 초기 실행
|
283 |
+
* 조사된 best practice에 따라 search space 정의
|
284 |
+
- 금요일: 진단 보고서 작성 및 개선 우선순위 결정
|
285 |
+
|
286 |
+
**2단계: 데이터 품질 개선 (2-3주차)**
|
287 |
+
- 데이터 정제 파이프라인 구축
|
288 |
+
* 조사 결과의 "80% 규칙" 적용: 누락값, 이상치, 레이블 오류 처리
|
289 |
+
* 코드 예시: `data_quality_pipeline.py` 구현
|
290 |
+
- 데이터 증강 구현
|
291 |
+
* 최신 기법 적용: MixUp, CutMix, AutoAugment
|
292 |
+
* 검증 데이터셋으로 효과 측정 (목표: 15% 성능 향상)
|
293 |
+
|
294 |
+
**3단계: 모델 최적화 구현 (4-6주차)**
|
295 |
+
- Knowledge Distillation 구현
|
296 |
+
* Teacher 모델: 현재 대규모 모델
|
297 |
+
* Student 모델: 90% 작은 크기 목표 (조사 결과 기반)
|
298 |
+
* 구현 프레임워크: PyTorch/TensorFlow
|
299 |
+
- Pruning 및 Quantization 적용
|
300 |
+
* 구조적 pruning으로 50% 파라미터 제거
|
301 |
+
* INT8 quantization으로 추가 4배 속도 향상
|
302 |
+
* Tesla 사례 참고: TensorRT 최적화 적용
|
303 |
+
|
304 |
+
**4단계: 성과 검증 및 배포 (7-8주차)**
|
305 |
+
- 성과 지표 측정
|
306 |
+
* 추론 속도: 목표 10배 향상 (조사 결과 기반)
|
307 |
+
* 정확도 손실: 최대 2% 이내 유지
|
308 |
+
* 비용 절감: 70% 목표 (OpenAI 사례 참고)
|
309 |
+
- 배포 전략
|
310 |
+
* A/B 테스트: 10% 트래픽으로 시작
|
311 |
+
* 모니터링: Prometheus + Grafana 대시보드
|
312 |
+
* 롤백 계획: 성능 저하 시 자동 롤백
|
313 |
+
|
314 |
+
**예상 결과물**
|
315 |
+
- 최���화된 모델 (크기 90% 감소, 속도 10배 향상)
|
316 |
+
- 상세 성능 벤치마크 보고서
|
317 |
+
- 프로덕션 배포 가이드 및 모니터링 대시보드
|
318 |
+
- 재현 가능한 최적화 파이프라인 코드""",
|
319 |
|
320 |
+
"supervisor_review": """실행자 AI의 계획을 검토한 결과, 조사 내용이 잘 반영되었습니다. 추가 개선사항을 제안합니다.
|
321 |
|
322 |
**강점**
|
323 |
+
- 조사된 사례들(Netflix, Tesla, OpenAI)이 각 단계에 적절히 활용됨
|
324 |
+
- 구체적인 도구와 기법이 명시되어 실행 가능성이 높음
|
325 |
+
- 측정 가능한 목표가 조사 결과를 기반으로 설정됨
|
326 |
|
327 |
+
**보완 필요사항**
|
328 |
+
1. 리스크 관리: 각 단계별 실패 시나리오와 대응 방안 추가
|
329 |
+
2. 비용 분석: OpenAI 사례의 70% 절감을 위한 구체적인 비용 계산
|
330 |
+
3. 팀 협업: 데이터 과학자, ML 엔지니어, DevOps 간 역할 분담 명확화
|
331 |
|
332 |
**추가 권장사항**
|
333 |
+
- 최신 연구 동향 모니터링 체계 구축
|
334 |
+
- 경쟁사 벤치마킹을 위한 정기적인 조사 프로세스
|
335 |
+
- 내부 지식 공유를 위한 문서화 및 세미나 계획"""
|
336 |
}
|
337 |
|
338 |
+
if role == "supervisor" and "조사자 AI가 정리한" in messages[0]["content"]:
|
339 |
+
response = test_responses["supervisor_execution"]
|
340 |
+
elif role == "supervisor" and messages[0]["content"].find("실행자 AI의 답변") > -1:
|
341 |
+
response = test_responses["supervisor_review"]
|
342 |
+
elif role == "supervisor":
|
343 |
response = test_responses["supervisor_initial"]
|
344 |
+
elif role == "researcher":
|
345 |
+
response = test_responses["researcher"]
|
346 |
else:
|
347 |
+
response = test_responses["executor"]
|
348 |
|
349 |
yield from self.simulate_streaming(response, role)
|
350 |
return
|
|
|
353 |
try:
|
354 |
system_prompts = {
|
355 |
"supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
|
356 |
+
"researcher": "당신은 정보를 조사하고 체계적으로 정리하는 조사자 AI입니다.",
|
357 |
"executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다."
|
358 |
}
|
359 |
|
|
|
417 |
def process_query_streaming(user_query: str, history: List):
|
418 |
"""스트리밍을 지원하는 쿼리 처리"""
|
419 |
if not user_query:
|
420 |
+
return history, "", "", "", "", "❌ 질문을 입력해주세요."
|
421 |
|
422 |
conversation_log = []
|
423 |
+
all_responses = {"supervisor": [], "researcher": [], "executor": []}
|
424 |
|
425 |
try:
|
426 |
+
# 1단계: 감독자 AI 초기 분석 및 키워드 추출
|
427 |
+
supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
428 |
+
supervisor_initial_response = ""
|
429 |
|
430 |
supervisor_text = "[초기 분석] 🔄 생성 중...\n"
|
431 |
for chunk in llm_system.call_llm_streaming(
|
432 |
[{"role": "user", "content": supervisor_prompt}],
|
433 |
"supervisor"
|
434 |
):
|
435 |
+
supervisor_initial_response += chunk
|
436 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
|
437 |
+
yield history, supervisor_text, "", "", "", "🔄 감독자 AI가 분석 중..."
|
438 |
+
|
439 |
+
all_responses["supervisor"].append(supervisor_initial_response)
|
440 |
+
|
441 |
+
# 키워드 추출
|
442 |
+
keywords = llm_system.extract_keywords(supervisor_initial_response)
|
443 |
+
logger.info(f"추출된 키워드: {keywords}")
|
444 |
+
|
445 |
+
# 2단계: 브레이브 검색 수행
|
446 |
+
researcher_text = "[웹 검색] 🔍 검색 중...\n"
|
447 |
+
yield history, supervisor_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
|
448 |
+
|
449 |
+
search_results = {}
|
450 |
+
for keyword in keywords:
|
451 |
+
results = llm_system.brave_search(keyword)
|
452 |
+
if results:
|
453 |
+
search_results[keyword] = results
|
454 |
+
researcher_text += f"✓ '{keyword}' 검색 완료\n"
|
455 |
+
yield history, supervisor_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
|
456 |
+
|
457 |
+
# 3단계: 조사자 AI가 검색 결과 정리
|
458 |
+
researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_initial_response, search_results)
|
459 |
+
researcher_response = ""
|
460 |
+
|
461 |
+
researcher_text = "[조사 결과 정리] 🔄 생성 중...\n"
|
462 |
+
for chunk in llm_system.call_llm_streaming(
|
463 |
+
[{"role": "user", "content": researcher_prompt}],
|
464 |
+
"researcher"
|
465 |
+
):
|
466 |
+
researcher_response += chunk
|
467 |
+
researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
|
468 |
+
yield history, supervisor_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
|
469 |
+
|
470 |
+
all_responses["researcher"].append(researcher_response)
|
471 |
+
|
472 |
+
# 4단계: 감독자 AI가 조사 내용 기반으로 실행 지시
|
473 |
+
supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(user_query, researcher_response)
|
474 |
+
supervisor_execution_response = ""
|
475 |
+
|
476 |
+
supervisor_text += "\n\n---\n\n[실행 지시] 🔄 생성 중...\n"
|
477 |
+
for chunk in llm_system.call_llm_streaming(
|
478 |
+
[{"role": "user", "content": supervisor_execution_prompt}],
|
479 |
+
"supervisor"
|
480 |
+
):
|
481 |
+
supervisor_execution_response += chunk
|
482 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
|
483 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
484 |
+
yield history, supervisor_text, researcher_text, "", "", "🎯 감독자 AI가 지시 중..."
|
485 |
+
|
486 |
+
all_responses["supervisor"].append(supervisor_execution_response)
|
487 |
+
|
488 |
+
# 5단계: 실행자 AI가 조사 내용과 지시를 기반으로 세부 구현
|
489 |
+
executor_prompt = llm_system.create_executor_prompt(user_query, supervisor_execution_response, researcher_response)
|
490 |
executor_response = ""
|
491 |
|
492 |
executor_text = "[세부 구현] 🔄 생성 중...\n"
|
|
|
496 |
):
|
497 |
executor_response += chunk
|
498 |
executor_text = f"[세부 구현] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
|
499 |
+
yield history, supervisor_text, researcher_text, executor_text, "", "🔧 실행자 AI가 구현 중..."
|
500 |
|
501 |
all_responses["executor"].append(executor_response)
|
502 |
+
|
503 |
+
# 6단계: 감독자 AI 최종 검토
|
504 |
+
review_prompt = llm_system.create_supervisor_initial_prompt(user_query)
|
505 |
+
review_prompt = f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.
|
506 |
+
|
507 |
+
사용자 질문: {user_query}
|
508 |
+
|
509 |
+
실행자 AI의 답변:
|
510 |
+
{executor_response}
|
511 |
+
|
512 |
+
이 답변을 검토하고 개선점과 추가 고려사항을 제시해주세요."""
|
513 |
+
|
514 |
review_response = ""
|
515 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[최종 검토] 🔄 생성 중...\n"
|
516 |
|
|
|
517 |
for chunk in llm_system.call_llm_streaming(
|
518 |
[{"role": "user", "content": review_prompt}],
|
519 |
"supervisor"
|
520 |
):
|
521 |
review_response += chunk
|
522 |
+
temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[최종 검토] - {datetime.now().strftime('%H:%M:%S')}\n{review_response}"
|
523 |
+
supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
|
524 |
+
yield history, supervisor_text, researcher_text, executor_text, "", "🔄 감독자 AI가 검토 중..."
|
|
|
525 |
|
526 |
# 최종 결과 생성
|
527 |
final_summary = f"""## 🤝 협력적 AI 시스템 종합 답변
|
|
|
532 |
### 🔍 거시적 분석 (감독자 AI)
|
533 |
{all_responses['supervisor'][0]}
|
534 |
|
535 |
+
### 📚 조사 결과 (조사자 AI)
|
536 |
+
{researcher_response}
|
537 |
+
|
538 |
+
### 🎯 실행 지시 (감독자 AI)
|
539 |
+
{all_responses['supervisor'][1]}
|
540 |
+
|
541 |
### 💡 세부 구현 (실행자 AI)
|
542 |
{executor_response}
|
543 |
|
544 |
+
### ✨ 최종 검토 및 개선사항 (감독자 AI)
|
545 |
{review_response}
|
546 |
|
547 |
---
|
548 |
+
*이 답변은 웹 검색을 통한 최신 정보와 AI들의 협력을 통해 작성되었습니다.*"""
|
549 |
|
550 |
# 히스토리 업데이트
|
551 |
new_history = history + [(user_query, final_summary)]
|
552 |
|
553 |
+
yield new_history, supervisor_text, researcher_text, executor_text, final_summary, "✅ 분석 완료!"
|
554 |
|
555 |
except Exception as e:
|
556 |
error_msg = f"❌ 처리 중 오류: {str(e)}"
|
557 |
+
yield history, "", "", "", error_msg, error_msg
|
558 |
|
559 |
def clear_all():
|
560 |
"""모든 내용 초기화"""
|
561 |
+
return [], "", "", "", "", "🔄 초기화되었습니다."
|
562 |
|
563 |
# Gradio 인터페이스
|
564 |
css = """
|
|
|
569 |
border-left: 4px solid #667eea !important;
|
570 |
padding-left: 10px !important;
|
571 |
}
|
572 |
+
.researcher-box textarea {
|
573 |
+
border-left: 4px solid #10b981 !important;
|
574 |
+
padding-left: 10px !important;
|
575 |
+
}
|
576 |
.executor-box textarea {
|
577 |
border-left: 4px solid #764ba2 !important;
|
578 |
padding-left: 10px !important;
|
|
|
582 |
with gr.Blocks(title="협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
|
583 |
gr.Markdown(
|
584 |
f"""
|
585 |
+
# 🤝 협력적 LLM 시스템 (조사자 포함)
|
586 |
|
587 |
+
> 감독자, 조사자, 실행자 AI가 협력하여 최상의 답변을 만들어냅니다.
|
588 |
|
589 |
+
**상태**:
|
590 |
+
- LLM: {'🟢 실제 모드' if not llm_system.test_mode else '🟡 테스트 모드'}
|
591 |
+
- Brave Search: {'🟢 활성화' if llm_system.bapi_token != "YOUR_BRAVE_API_TOKEN" else '🟡 테스트 모드'}
|
592 |
|
593 |
**시스템 구조:**
|
594 |
+
- 🧠 **감독자 AI**: 전체적인 방향 제시 및 키워드 추출
|
595 |
+
- 🔍 **조사자 AI**: 브레이브 검색으로 최신 정보 조사 및 정리
|
596 |
+
- 👁️ **실행자 AI**: 조사 내용 기반 구체적 구현
|
597 |
+
- 🔄 **협력 프로세스**: 검색 정보 기반 상호 피드백
|
598 |
"""
|
599 |
)
|
600 |
|
|
|
603 |
with gr.Column(scale=1):
|
604 |
chatbot = gr.Chatbot(
|
605 |
label="💬 대화 기록",
|
606 |
+
height=600,
|
607 |
show_copy_button=True,
|
608 |
bubble_full_width=False
|
609 |
)
|
|
|
633 |
value="*질문을 입력하면 결과가 여기에 표시됩니다.*"
|
634 |
)
|
635 |
|
636 |
+
# AI 출력들
|
637 |
with gr.Row():
|
638 |
# 감독자 AI 출력
|
639 |
with gr.Column():
|
640 |
gr.Markdown("### 🧠 감독자 AI (거시적 분석)")
|
641 |
supervisor_output = gr.Textbox(
|
642 |
label="",
|
643 |
+
lines=12,
|
644 |
+
max_lines=15,
|
645 |
interactive=False,
|
646 |
elem_classes=["supervisor-box"]
|
647 |
)
|
648 |
+
|
649 |
+
with gr.Row():
|
650 |
+
# 조사자 AI 출력
|
651 |
+
with gr.Column():
|
652 |
+
gr.Markdown("### 🔍 조사자 AI (웹 검색 & 정리)")
|
653 |
+
researcher_output = gr.Textbox(
|
654 |
+
label="",
|
655 |
+
lines=12,
|
656 |
+
max_lines=15,
|
657 |
+
interactive=False,
|
658 |
+
elem_classes=["researcher-box"]
|
659 |
+
)
|
660 |
|
661 |
# 실행자 AI 출력
|
662 |
with gr.Column():
|
663 |
gr.Markdown("### 👁️ 실행자 AI (미시적 구현)")
|
664 |
executor_output = gr.Textbox(
|
665 |
label="",
|
666 |
+
lines=12,
|
667 |
+
max_lines=15,
|
668 |
interactive=False,
|
669 |
elem_classes=["executor-box"]
|
670 |
)
|
|
|
672 |
# 예제
|
673 |
gr.Examples(
|
674 |
examples=[
|
675 |
+
"기계학습 모델의 성능을 향상시키는 최신 방법은?",
|
676 |
+
"2024년 효과적인 프로젝트 관리 도구와 전략은?",
|
677 |
+
"지속 가능한 비즈니스 모델의 최신 트렌드는?",
|
678 |
+
"최신 데이터 시각화 도구와 기법은?",
|
679 |
+
"원격 팀의 생산성을 높이는 검증된 방법은?"
|
680 |
],
|
681 |
inputs=user_input,
|
682 |
label="💡 예제 질문"
|
|
|
686 |
submit_btn.click(
|
687 |
fn=process_query_streaming,
|
688 |
inputs=[user_input, chatbot],
|
689 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
690 |
).then(
|
691 |
fn=lambda: "",
|
692 |
outputs=[user_input]
|
|
|
695 |
user_input.submit(
|
696 |
fn=process_query_streaming,
|
697 |
inputs=[user_input, chatbot],
|
698 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
699 |
).then(
|
700 |
fn=lambda: "",
|
701 |
outputs=[user_input]
|
|
|
703 |
|
704 |
clear_btn.click(
|
705 |
fn=clear_all,
|
706 |
+
outputs=[chatbot, supervisor_output, researcher_output, executor_output, final_output, status_text]
|
707 |
)
|
708 |
|
709 |
gr.Markdown(
|
|
|
711 |
---
|
712 |
### 📝 사용 방법
|
713 |
1. 질문을 입력하고 Enter 또는 '분석 시작' 버튼을 클릭하세요.
|
714 |
+
2. 감독자 AI가 키워드를 추출하고, 조사자 AI가 웹 검색을 수행합니다.
|
715 |
+
3. 세 AI가 협력하여 답변을 생성하는 과정을 실시간으로 확인할 수 있습니다.
|
716 |
+
4. 최종 종합 결과는 상단에 표시됩니다.
|
717 |
|
718 |
### ⚙️ 환경 설정
|
719 |
+
- **LLM API**: `export FRIENDLI_TOKEN="your_token"`
|
720 |
+
- **Brave Search API**: `export BAPI_TOKEN="your_brave_api_token"`
|
721 |
- **테스트 모드**: `export TEST_MODE=true` (API 없이 작동)
|
722 |
+
|
723 |
+
### 🔗 API 키 획득
|
724 |
+
- Friendli API: [https://friendli.ai](https://friendli.ai)
|
725 |
+
- Brave Search API: [https://brave.com/search/api/](https://brave.com/search/api/)
|
726 |
"""
|
727 |
)
|
728 |
|