Update app-backup.py
Browse files- app-backup.py +689 -330
app-backup.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""
|
| 2 |
โก Speed-Optimized Multi-Agent RAG System for Complex Questions
|
| 3 |
-
๋ณ๋ ฌ ์ฒ๋ฆฌ,
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
|
@@ -8,6 +10,8 @@ import json
|
|
| 8 |
import time
|
| 9 |
import asyncio
|
| 10 |
import hashlib
|
|
|
|
|
|
|
| 11 |
from typing import Optional, List, Dict, Any, Tuple, Generator, AsyncGenerator
|
| 12 |
from datetime import datetime, timedelta
|
| 13 |
from enum import Enum
|
|
@@ -59,105 +63,60 @@ class AgentResponse(BaseModel):
|
|
| 59 |
|
| 60 |
|
| 61 |
# ============================================================================
|
| 62 |
-
#
|
| 63 |
# ============================================================================
|
| 64 |
|
| 65 |
-
class
|
| 66 |
-
"""
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
self.max_size = max_size
|
| 73 |
-
self.ttl = timedelta(hours=ttl_hours)
|
| 74 |
-
self.reasoning_patterns = self._init_reasoning_patterns()
|
| 75 |
-
|
| 76 |
-
def _init_reasoning_patterns(self) -> Dict:
|
| 77 |
-
"""์์ฃผ ์ฌ์ฉ๋๋ ์ถ๋ก ํจํด ์ด๊ธฐํ"""
|
| 78 |
-
return {
|
| 79 |
-
"analysis": {
|
| 80 |
-
"structure": ["ํํฉ ๋ถ์", "ํต์ฌ ์์ธ", "์ํฅ ํ๊ฐ", "์ ๋ต ์ ์"],
|
| 81 |
-
"keywords": ["๋ถ์", "ํ๊ฐ", "์ํฅ", "์ ๋ต"]
|
| 82 |
-
},
|
| 83 |
-
"comparison": {
|
| 84 |
-
"structure": ["๋์ ์ ์", "๋น๊ต ๊ธฐ์ค", "์ฅ๋จ์ ๋ถ์", "๊ฒฐ๋ก "],
|
| 85 |
-
"keywords": ["๋น๊ต", "์ฐจ์ด", "์ฅ๋จ์ ", "vs"]
|
| 86 |
-
},
|
| 87 |
-
"creative": {
|
| 88 |
-
"structure": ["๋ฌธ์ ์ ์", "์ฐฝ์์ ์ ๊ทผ", "๊ตฌํ ๋ฐฉ๋ฒ", "์์ ํจ๊ณผ"],
|
| 89 |
-
"keywords": ["์ฐฝ์์ ", "ํ์ ์ ", "์๋ก์ด", "์์ด๋์ด"]
|
| 90 |
-
},
|
| 91 |
-
"technical": {
|
| 92 |
-
"structure": ["๊ธฐ์ ๊ฐ์", "ํต์ฌ ์๋ฆฌ", "๊ตฌํ ์์ธ", "์ค์ฉ ์์"],
|
| 93 |
-
"keywords": ["๊ธฐ์ ", "๊ตฌํ", "์ฝ๋", "์์คํ
"]
|
| 94 |
-
}
|
| 95 |
-
}
|
| 96 |
-
|
| 97 |
-
def get_query_hash(self, query: str) -> str:
|
| 98 |
-
"""์ฟผ๋ฆฌ ํด์ ์์ฑ"""
|
| 99 |
-
return hashlib.md5(query.encode()).hexdigest()
|
| 100 |
-
|
| 101 |
-
def get(self, query: str) -> Optional[Dict]:
|
| 102 |
-
"""์บ์์์ ์กฐํ"""
|
| 103 |
-
query_hash = self.get_query_hash(query)
|
| 104 |
-
|
| 105 |
-
if query_hash in self.cache:
|
| 106 |
-
# TTL ์ฒดํฌ
|
| 107 |
-
if datetime.now() - self.timestamps[query_hash] < self.ttl:
|
| 108 |
-
self.access_count[query_hash] += 1
|
| 109 |
-
return self.cache[query_hash]
|
| 110 |
-
else:
|
| 111 |
-
# ๋ง๋ฃ๋ ์บ์ ์ญ์
|
| 112 |
-
del self.cache[query_hash]
|
| 113 |
-
del self.timestamps[query_hash]
|
| 114 |
-
del self.access_count[query_hash]
|
| 115 |
-
|
| 116 |
-
return None
|
| 117 |
-
|
| 118 |
-
def set(self, query: str, response: Dict):
|
| 119 |
-
"""์บ์์ ์ ์ฅ"""
|
| 120 |
-
query_hash = self.get_query_hash(query)
|
| 121 |
-
|
| 122 |
-
# ์บ์ ํฌ๊ธฐ ๊ด๋ฆฌ
|
| 123 |
-
if len(self.cache) >= self.max_size:
|
| 124 |
-
# LRU ์ ์ฑ
: ๊ฐ์ฅ ์ ๊ฒ ์ฌ์ฉ๋ ํญ๋ชฉ ์ ๊ฑฐ
|
| 125 |
-
least_used = min(self.access_count, key=self.access_count.get)
|
| 126 |
-
del self.cache[least_used]
|
| 127 |
-
del self.timestamps[least_used]
|
| 128 |
-
del self.access_count[least_used]
|
| 129 |
-
|
| 130 |
-
self.cache[query_hash] = response
|
| 131 |
-
self.timestamps[query_hash] = datetime.now()
|
| 132 |
-
self.access_count[query_hash] = 1
|
| 133 |
-
|
| 134 |
-
def get_reasoning_pattern(self, query: str) -> Optional[Dict]:
|
| 135 |
-
"""์ฟผ๋ฆฌ์ ์ ํฉํ ์ถ๋ก ํจํด ๋ฐํ"""
|
| 136 |
-
query_lower = query.lower()
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
|
| 148 |
# ============================================================================
|
| 149 |
-
# ๋ณ๋ ฌ ์ฒ๋ฆฌ ์ต์ ํ Brave Search
|
| 150 |
# ============================================================================
|
| 151 |
|
| 152 |
class AsyncBraveSearch:
|
| 153 |
-
"""๋น๋๊ธฐ Brave ๊ฒ์ ํด๋ผ์ด์ธํธ"""
|
| 154 |
|
| 155 |
def __init__(self, api_key: Optional[str] = None):
|
| 156 |
self.api_key = api_key or os.getenv("BRAVE_SEARCH_API_KEY")
|
| 157 |
self.base_url = "https://api.search.brave.com/res/v1/web/search"
|
|
|
|
| 158 |
|
| 159 |
-
async def search_async(self, query: str, count: int = 5) -> List[Dict]:
|
| 160 |
-
"""๋น๋๊ธฐ ๊ฒ์"""
|
| 161 |
if not self.api_key:
|
| 162 |
return []
|
| 163 |
|
|
@@ -166,48 +125,70 @@ class AsyncBraveSearch:
|
|
| 166 |
"X-Subscription-Token": self.api_key
|
| 167 |
}
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
params = {
|
| 170 |
"q": query,
|
| 171 |
"count": count,
|
| 172 |
"text_decorations": False,
|
| 173 |
-
|
| 174 |
-
"country": "KR"
|
| 175 |
}
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
async with
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
results
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
|
| 205 |
# ============================================================================
|
| 206 |
-
# ์ต์ ํ๋ Fireworks ํด๋ผ์ด์ธํธ
|
| 207 |
# ============================================================================
|
| 208 |
|
| 209 |
class OptimizedFireworksClient:
|
| 210 |
-
"""์ต์ ํ๋ LLM ํด๋ผ์ด์ธํธ"""
|
| 211 |
|
| 212 |
def __init__(self, api_key: Optional[str] = None):
|
| 213 |
self.api_key = api_key or os.getenv("FIREWORKS_API_KEY")
|
|
@@ -223,13 +204,32 @@ class OptimizedFireworksClient:
|
|
| 223 |
|
| 224 |
# ํญ์ ์ต๊ณ ์ฑ๋ฅ ๋ชจ๋ธ ์ฌ์ฉ (๋ณต์กํ ์ง๋ฌธ ์ ์ )
|
| 225 |
self.model = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
async def chat_stream_async(
|
| 228 |
self,
|
| 229 |
messages: List[Dict],
|
| 230 |
**kwargs
|
| 231 |
) -> AsyncGenerator[str, None]:
|
| 232 |
-
"""๋น๋๊ธฐ ์คํธ๋ฆฌ๋ฐ ๋ํ"""
|
| 233 |
|
| 234 |
payload = {
|
| 235 |
"model": self.model,
|
|
@@ -241,34 +241,43 @@ class OptimizedFireworksClient:
|
|
| 241 |
"stream": True
|
| 242 |
}
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
async with
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
# ============================================================================
|
| 271 |
-
# ๊ฒฝ๋ํ๋ ์ถ๋ก ์ฒด์ธ
|
| 272 |
# ============================================================================
|
| 273 |
|
| 274 |
class LightweightReasoningChain:
|
|
@@ -276,28 +285,70 @@ class LightweightReasoningChain:
|
|
| 276 |
|
| 277 |
def __init__(self):
|
| 278 |
self.templates = {
|
| 279 |
-
"
|
| 280 |
-
"
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
"
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
},
|
| 287 |
-
"
|
| 288 |
-
"
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
}
|
| 291 |
}
|
| 292 |
|
| 293 |
-
def get_reasoning_structure(self, query_type: str) -> Dict:
|
| 294 |
"""์ฟผ๋ฆฌ ์ ํ์ ๋ง๋ ์ถ๋ก ๊ตฌ์กฐ ๋ฐํ"""
|
| 295 |
-
|
| 296 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
|
| 299 |
# ============================================================================
|
| 300 |
-
# ์กฐ๊ธฐ ์ข
๋ฃ ๋ฉ์ปค๋์ฆ
|
| 301 |
# ============================================================================
|
| 302 |
|
| 303 |
class QualityChecker:
|
|
@@ -312,16 +363,27 @@ class QualityChecker:
|
|
| 312 |
"clarity": 0.2
|
| 313 |
}
|
| 314 |
|
| 315 |
-
def evaluate_response(self, response: str, query: str) -> Tuple[float, bool]:
|
| 316 |
-
"""์๋ต ํ์ง ํ๊ฐ"""
|
| 317 |
scores = {}
|
| 318 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
# ๊ธธ์ด ํ๊ฐ
|
| 320 |
-
scores["length"] = min(len(response) /
|
| 321 |
|
| 322 |
-
# ๊ตฌ์กฐ ํ๊ฐ
|
| 323 |
-
structure_markers =
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
# ์์ ์ฑ ํ๊ฐ (์ฟผ๋ฆฌ ํค์๋ ํฌํจ ์ฌ๋ถ)
|
| 327 |
query_words = set(query.split())
|
|
@@ -329,9 +391,16 @@ class QualityChecker:
|
|
| 329 |
scores["completeness"] = len(query_words & response_words) / max(len(query_words), 1)
|
| 330 |
|
| 331 |
# ๋ช
ํ์ฑ ํ๊ฐ (๋ฌธ์ฅ ๊ตฌ์กฐ)
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
avg_sentence_length = sum(len(s.split()) for s in sentences) / max(len(sentences), 1)
|
| 334 |
-
scores["clarity"] = min(avg_sentence_length / 20, 1.0)
|
| 335 |
|
| 336 |
# ๊ฐ์ค ํ๊ท ๊ณ์ฐ
|
| 337 |
total_score = sum(
|
|
@@ -345,29 +414,41 @@ class QualityChecker:
|
|
| 345 |
|
| 346 |
|
| 347 |
# ============================================================================
|
| 348 |
-
# ์คํธ๋ฆฌ๋ฐ ์ต์ ํ
|
| 349 |
# ============================================================================
|
| 350 |
|
| 351 |
class OptimizedStreaming:
|
| 352 |
-
"""์คํธ๋ฆฌ๋ฐ ๋ฒํผ ์ต์ ํ"""
|
| 353 |
|
| 354 |
-
def __init__(self, chunk_size: int =
|
| 355 |
self.chunk_size = chunk_size
|
| 356 |
self.flush_interval = flush_interval
|
| 357 |
self.buffer = ""
|
| 358 |
self.last_flush = time.time()
|
|
|
|
| 359 |
|
| 360 |
async def buffer_and_yield(
|
| 361 |
self,
|
| 362 |
-
stream: AsyncGenerator[str, None]
|
|
|
|
| 363 |
) -> AsyncGenerator[str, None]:
|
| 364 |
-
"""๋ฒํผ๋ง๋ ์คํธ๋ฆฌ๋ฐ"""
|
| 365 |
|
|
|
|
| 366 |
async for chunk in stream:
|
| 367 |
self.buffer += chunk
|
| 368 |
current_time = time.time()
|
|
|
|
| 369 |
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
current_time - self.last_flush >= self.flush_interval):
|
| 372 |
|
| 373 |
yield self.buffer
|
|
@@ -380,85 +461,212 @@ class OptimizedStreaming:
|
|
| 380 |
|
| 381 |
|
| 382 |
# ============================================================================
|
| 383 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
# ============================================================================
|
| 385 |
|
| 386 |
class SpeedOptimizedMultiAgentSystem:
|
| 387 |
-
"""์๋ ์ต์ ํ๋ ๋ฉํฐ ์์ด์ ํธ ์์คํ
"""
|
| 388 |
|
| 389 |
def __init__(self):
|
| 390 |
self.llm = OptimizedFireworksClient()
|
| 391 |
self.search = AsyncBraveSearch()
|
| 392 |
-
self.cache = SmartCache()
|
| 393 |
self.reasoning = LightweightReasoningChain()
|
| 394 |
self.quality_checker = QualityChecker()
|
| 395 |
self.streaming = OptimizedStreaming()
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
self.compact_prompts = self._init_compact_prompts()
|
| 399 |
|
| 400 |
# ๋ณ๋ ฌ ์ฒ๋ฆฌ ํ
|
| 401 |
self.executor = ThreadPoolExecutor(max_workers=4)
|
| 402 |
|
| 403 |
-
def _init_compact_prompts(self) -> Dict:
|
| 404 |
-
"""์์ถ๋ ๊ณ ํจ์จ ํ๋กฌํํธ"""
|
| 405 |
-
|
| 406 |
-
|
|
|
|
| 407 |
์ฆ์๋ถ์: ํต์ฌ์๋+ํ์์ ๋ณด+๋ต๋ณ๊ตฌ์กฐ
|
| 408 |
์ถ๋ ฅ: 5๊ฐ ํต์ฌํฌ์ธํธ(๊ฐ 1๋ฌธ์ฅ)
|
| 409 |
์ถ๋ก ์ฒด๊ณ ๋ช
์""",
|
| 410 |
-
|
| 411 |
-
|
| 412 |
์
๋ ฅ๊ตฌ์กฐ ๋ฐ๋ผ ์ฐฝ์์ ํ์ฅ
|
| 413 |
์ค์ฉ์์+ํ์ ์ ๊ทผ+๊ตฌ์ฒด์กฐ์ธ
|
| 414 |
๋ถํ์์ค๋ช
์ ๊ฑฐ""",
|
| 415 |
-
|
| 416 |
-
|
| 417 |
์ ์๊ฒํ : ์ ํ์ฑ/๋
ผ๋ฆฌ์ฑ/์ค์ฉ์ฑ
|
| 418 |
๊ฐ์ ํฌ์ธํธ 3๊ฐ๋ง
|
| 419 |
๊ฐ 2๋ฌธ์ฅ ์ด๋ด""",
|
| 420 |
-
|
| 421 |
-
|
| 422 |
๋ชจ๋ ์๊ฒฌ ์ข
ํฉโ์ต์ ๋ต๋ณ
|
| 423 |
๋ช
ํ๊ตฌ์กฐ+์ค์ฉ์ ๋ณด+์ฐฝ์๊ท ํ
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
}
|
|
|
|
|
|
|
| 426 |
|
| 427 |
async def parallel_process_agents(
|
| 428 |
self,
|
| 429 |
query: str,
|
| 430 |
search_results: List[Dict],
|
| 431 |
-
show_progress: bool = True
|
|
|
|
| 432 |
) -> AsyncGenerator[Tuple[str, str], None]:
|
| 433 |
-
"""๋ณ๋ ฌ ์ฒ๋ฆฌ ํ์ดํ๋ผ์ธ"""
|
| 434 |
|
| 435 |
start_time = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
search_context = self._format_search_results(search_results)
|
| 437 |
accumulated_response = ""
|
| 438 |
agent_thoughts = ""
|
| 439 |
|
| 440 |
-
# ์บ์ ํ์ธ
|
| 441 |
-
cached = self.cache.get(query)
|
| 442 |
-
if cached:
|
| 443 |
-
yield cached["response"], "โจ ์บ์์์ ์ฆ์ ๋ก๋"
|
| 444 |
-
return
|
| 445 |
-
|
| 446 |
# ์ถ๋ก ํจํด ๊ฒฐ์
|
| 447 |
-
reasoning_pattern = self.
|
| 448 |
|
| 449 |
try:
|
| 450 |
# === 1๋จ๊ณ: ๊ฐ๋
์ + ๊ฒ์ ๋ณ๋ ฌ ์คํ ===
|
| 451 |
if show_progress:
|
| 452 |
-
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
yield accumulated_response, agent_thoughts
|
| 455 |
|
| 456 |
-
# ๊ฐ๋
์ ํ๋กฌํํธ
|
| 457 |
-
|
|
|
|
| 458 |
์ง๋ฌธ: {query}
|
| 459 |
๊ฒ์๊ฒฐ๊ณผ: {search_context}
|
| 460 |
์ถ๋ก ํจํด: {reasoning_pattern}
|
| 461 |
-
์ฆ์ ํต์ฌ๊ตฌ์กฐ 5๊ฐ ์ ์"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
|
| 463 |
supervisor_response = ""
|
| 464 |
supervisor_task = self.llm.chat_stream_async(
|
|
@@ -474,23 +682,54 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 474 |
async for chunk in self.streaming.buffer_and_yield(supervisor_task):
|
| 475 |
supervisor_response += chunk
|
| 476 |
if show_progress and len(supervisor_response) < 300:
|
| 477 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
yield accumulated_response, agent_thoughts
|
| 479 |
|
| 480 |
# === 2๋จ๊ณ: ์ฐฝ์์ฑ + ๋นํ ์ค๋น ๋ณ๋ ฌ ===
|
| 481 |
if show_progress:
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
yield accumulated_response, agent_thoughts
|
| 484 |
|
| 485 |
-
# ์ฐฝ์์ฑ ์์ฑ ์์
|
| 486 |
-
|
|
|
|
| 487 |
์ง๋ฌธ: {query}
|
| 488 |
๊ฐ๋
์๊ตฌ์กฐ: {supervisor_response}
|
| 489 |
๊ฒ์๊ฒฐ๊ณผ: {search_context}
|
| 490 |
-
์ฐฝ์์ +์ค์ฉ์ ๋ต๋ณ ์ฆ์์์ฑ"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
|
| 492 |
creative_response = ""
|
| 493 |
-
creative_partial = ""
|
| 494 |
critic_started = False
|
| 495 |
critic_response = ""
|
| 496 |
|
|
@@ -512,11 +751,27 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 512 |
if len(creative_partial) > 500 and not critic_started:
|
| 513 |
critic_started = True
|
| 514 |
|
| 515 |
-
# ๋นํ์ ๋น๋๊ธฐ ์์
|
| 516 |
-
|
|
|
|
| 517 |
์๋ณธ์ง๋ฌธ: {query}
|
| 518 |
์ฐฝ์์ฑ๋ต๋ณ(์ผ๋ถ): {creative_partial}
|
| 519 |
-
์ ์๊ฒํ โ๊ฐ์ ์ 3๊ฐ"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
|
| 521 |
critic_task = asyncio.create_task(
|
| 522 |
self._run_critic_async(critic_prompt)
|
|
@@ -524,7 +779,13 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 524 |
|
| 525 |
if show_progress:
|
| 526 |
display_creative = creative_response[:400] + "..." if len(creative_response) > 400 else creative_response
|
| 527 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 528 |
yield accumulated_response, agent_thoughts
|
| 529 |
|
| 530 |
# ๋นํ์ ๊ฒฐ๊ณผ ๋๊ธฐ
|
|
@@ -532,41 +793,76 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 532 |
critic_response = await critic_task
|
| 533 |
|
| 534 |
if show_progress:
|
| 535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
yield accumulated_response, agent_thoughts
|
| 537 |
|
| 538 |
# === 3๋จ๊ณ: ํ์ง ์ฒดํฌ ๋ฐ ์กฐ๊ธฐ ์ข
๋ฃ ===
|
| 539 |
quality_score, need_more = self.quality_checker.evaluate_response(
|
| 540 |
-
creative_response, query
|
| 541 |
)
|
| 542 |
|
| 543 |
if not need_more and quality_score > 0.85:
|
| 544 |
# ํ์ง์ด ์ถฉ๋ถํ ๋์ผ๋ฉด ๋ฐ๋ก ๋ฐํ
|
| 545 |
-
accumulated_response = creative_response
|
| 546 |
|
| 547 |
if show_progress:
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
|
| 556 |
yield accumulated_response, agent_thoughts
|
| 557 |
return
|
| 558 |
|
| 559 |
# === 4๋จ๊ณ: ์ต์ข
ํตํฉ (์คํธ๋ฆฌ๋ฐ) ===
|
| 560 |
if show_progress:
|
| 561 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
yield accumulated_response, agent_thoughts
|
| 563 |
|
| 564 |
-
|
|
|
|
|
|
|
| 565 |
์ง๋ฌธ: {query}
|
| 566 |
์ฐฝ์์ฑ๋ต๋ณ: {creative_response}
|
| 567 |
๋นํํผ๋๋ฐฑ: {critic_response}
|
| 568 |
๊ฐ๋
์๊ตฌ์กฐ: {supervisor_response}
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 570 |
|
| 571 |
final_task = self.llm.chat_stream_async(
|
| 572 |
messages=[
|
|
@@ -579,28 +875,39 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 579 |
|
| 580 |
# ์ต์ข
๋ต๋ณ ์คํธ๋ฆฌ๋ฐ
|
| 581 |
accumulated_response = ""
|
| 582 |
-
|
|
|
|
| 583 |
accumulated_response += chunk
|
| 584 |
-
|
|
|
|
|
|
|
| 585 |
|
| 586 |
-
#
|
| 587 |
-
|
| 588 |
-
accumulated_response += f"\n\n---\nโก ์ฒ๋ฆฌ ์๊ฐ: {processing_time:.1f}์ด"
|
| 589 |
|
| 590 |
-
#
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
"
|
| 594 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
|
| 596 |
yield accumulated_response, agent_thoughts
|
| 597 |
|
| 598 |
except Exception as e:
|
| 599 |
-
error_msg =
|
| 600 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
|
| 602 |
async def _run_critic_async(self, prompt: str) -> str:
|
| 603 |
-
"""๋นํ์ ๋น๋๊ธฐ ์คํ"""
|
| 604 |
try:
|
| 605 |
response = ""
|
| 606 |
async for chunk in self.llm.chat_stream_async(
|
|
@@ -613,27 +920,37 @@ class SpeedOptimizedMultiAgentSystem:
|
|
| 613 |
):
|
| 614 |
response += chunk
|
| 615 |
return response
|
| 616 |
-
except:
|
| 617 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
|
| 619 |
def _format_search_results(self, results: List[Dict]) -> str:
|
| 620 |
"""๊ฒ์ ๊ฒฐ๊ณผ ์์ถ ํฌ๋งท"""
|
| 621 |
if not results:
|
| 622 |
-
return "
|
| 623 |
|
| 624 |
formatted = []
|
| 625 |
-
for i, r in enumerate(results[:3], 1):
|
| 626 |
-
|
|
|
|
|
|
|
| 627 |
|
| 628 |
return " | ".join(formatted)
|
| 629 |
|
| 630 |
|
| 631 |
# ============================================================================
|
| 632 |
-
# Gradio UI (์ต์ ํ ๋ฒ์ )
|
| 633 |
# ============================================================================
|
| 634 |
|
| 635 |
def create_optimized_gradio_interface():
|
| 636 |
-
"""์ต์ ํ๋ Gradio ์ธํฐํ์ด์ค"""
|
| 637 |
|
| 638 |
# ์์คํ
์ด๊ธฐํ
|
| 639 |
system = SpeedOptimizedMultiAgentSystem()
|
|
@@ -643,57 +960,67 @@ def create_optimized_gradio_interface():
|
|
| 643 |
history: List[Dict],
|
| 644 |
use_search: bool,
|
| 645 |
show_agent_thoughts: bool,
|
| 646 |
-
search_count: int
|
|
|
|
| 647 |
):
|
| 648 |
-
"""์ต์ ํ๋ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ -
|
| 649 |
|
| 650 |
if not message:
|
| 651 |
yield history, "", ""
|
| 652 |
return
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
# ๋น๋๊ธฐ ํจ์๋ฅผ ๋๊ธฐ์ ์ผ๋ก ์คํ
|
| 655 |
try:
|
| 656 |
import nest_asyncio
|
| 657 |
nest_asyncio.apply()
|
| 658 |
except ImportError:
|
| 659 |
-
pass
|
| 660 |
-
|
| 661 |
-
def run_async_function(coro):
|
| 662 |
-
"""๋น๋๊ธฐ ํจ์๋ฅผ ๋๊ธฐ์ ์ผ๋ก ์คํํ๋ ํฌํผ"""
|
| 663 |
-
try:
|
| 664 |
-
loop = asyncio.get_event_loop()
|
| 665 |
-
if loop.is_running():
|
| 666 |
-
# ์ด๋ฏธ ์คํ ์ค์ธ ๋ฃจํ๊ฐ ์์ผ๋ฉด ์ ์ค๋ ๋์์ ์คํ
|
| 667 |
-
import concurrent.futures
|
| 668 |
-
with concurrent.futures.ThreadPoolExecutor() as executor:
|
| 669 |
-
future = executor.submit(asyncio.run, coro)
|
| 670 |
-
return future.result()
|
| 671 |
-
else:
|
| 672 |
-
return loop.run_until_complete(coro)
|
| 673 |
-
except RuntimeError:
|
| 674 |
-
# ๋ฃจํ๊ฐ ์์ผ๋ฉด ์๋ก ์์ฑ
|
| 675 |
-
return asyncio.run(coro)
|
| 676 |
|
| 677 |
try:
|
| 678 |
# ๊ฒ์ ์ํ (๋๊ธฐํ)
|
| 679 |
search_results = []
|
| 680 |
search_display = ""
|
| 681 |
|
|
|
|
|
|
|
|
|
|
| 682 |
if use_search:
|
| 683 |
# ๊ฒ์ ์ํ ํ์
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 684 |
history_with_message = history + [
|
| 685 |
{"role": "user", "content": message},
|
| 686 |
-
{"role": "assistant", "content":
|
| 687 |
]
|
| 688 |
yield history_with_message, "", ""
|
| 689 |
|
| 690 |
# ๋น๋๊ธฐ ๊ฒ์์ ๋๊ธฐ์ ์ผ๋ก ์คํ
|
| 691 |
-
|
| 692 |
-
system.search.search_async(message, count=search_count)
|
| 693 |
-
|
|
|
|
|
|
|
|
|
|
| 694 |
|
| 695 |
if search_results:
|
| 696 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 697 |
for i, result in enumerate(search_results[:3], 1):
|
| 698 |
search_display += f"**{i}. [{result['title'][:50]}]({result['url']})**\n"
|
| 699 |
search_display += f" {result['description'][:100]}...\n\n"
|
|
@@ -701,37 +1028,55 @@ def create_optimized_gradio_interface():
|
|
| 701 |
# ์ฌ์ฉ์ ๋ฉ์์ง ์ถ๊ฐ
|
| 702 |
current_history = history + [{"role": "user", "content": message}]
|
| 703 |
|
| 704 |
-
#
|
| 705 |
-
async def
|
| 706 |
-
|
| 707 |
async for response, thoughts in system.parallel_process_agents(
|
| 708 |
query=message,
|
| 709 |
search_results=search_results,
|
| 710 |
-
show_progress=show_agent_thoughts
|
|
|
|
| 711 |
):
|
| 712 |
-
|
| 713 |
-
return responses
|
| 714 |
|
| 715 |
-
#
|
| 716 |
-
|
|
|
|
| 717 |
|
| 718 |
-
#
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
|
| 725 |
except Exception as e:
|
| 726 |
error_history = history + [
|
| 727 |
{"role": "user", "content": message},
|
| 728 |
-
{"role": "assistant", "content": f"โ
|
| 729 |
]
|
| 730 |
yield error_history, "", ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 731 |
|
| 732 |
# Gradio ์ธํฐํ์ด์ค
|
| 733 |
with gr.Blocks(
|
| 734 |
-
title="โก Speed-Optimized Multi-Agent System",
|
| 735 |
theme=gr.themes.Soft(),
|
| 736 |
css="""
|
| 737 |
.gradio-container {
|
|
@@ -741,50 +1086,57 @@ def create_optimized_gradio_interface():
|
|
| 741 |
"""
|
| 742 |
) as demo:
|
| 743 |
gr.Markdown("""
|
| 744 |
-
# โก
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
- ๐
|
| 749 |
-
-
|
| 750 |
-
-
|
| 751 |
-
-
|
|
|
|
| 752 |
""")
|
| 753 |
|
| 754 |
with gr.Row():
|
| 755 |
with gr.Column(scale=3):
|
| 756 |
chatbot = gr.Chatbot(
|
| 757 |
height=500,
|
| 758 |
-
label="๐ฌ
|
| 759 |
type="messages"
|
| 760 |
)
|
| 761 |
|
| 762 |
msg = gr.Textbox(
|
| 763 |
-
label="
|
| 764 |
-
placeholder="
|
| 765 |
lines=3
|
| 766 |
)
|
| 767 |
|
| 768 |
with gr.Row():
|
| 769 |
-
submit = gr.Button("โก
|
| 770 |
-
clear = gr.Button("๐
|
| 771 |
|
| 772 |
-
with gr.Accordion("๐ค
|
| 773 |
agent_thoughts = gr.Markdown()
|
| 774 |
|
| 775 |
-
with gr.Accordion("๐
|
| 776 |
search_sources = gr.Markdown()
|
| 777 |
|
| 778 |
with gr.Column(scale=1):
|
| 779 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
|
| 781 |
use_search = gr.Checkbox(
|
| 782 |
-
label="๐
|
| 783 |
value=True
|
| 784 |
)
|
| 785 |
|
| 786 |
show_agent_thoughts = gr.Checkbox(
|
| 787 |
-
label="๐ง
|
| 788 |
value=True
|
| 789 |
)
|
| 790 |
|
|
@@ -793,33 +1145,40 @@ def create_optimized_gradio_interface():
|
|
| 793 |
maximum=10,
|
| 794 |
value=5,
|
| 795 |
step=1,
|
| 796 |
-
label="
|
| 797 |
)
|
| 798 |
|
| 799 |
gr.Markdown("""
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
- โ
|
| 804 |
-
-
|
| 805 |
-
- โ
|
| 806 |
-
- โ
|
| 807 |
-
- โ
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
-
|
|
|
|
|
|
|
| 813 |
""")
|
| 814 |
|
| 815 |
-
# ๋ณต์กํ ์ง๋ฌธ ์์
|
| 816 |
gr.Examples(
|
| 817 |
examples=[
|
|
|
|
| 818 |
"AI ๊ธฐ์ ์ด ํฅํ 10๋
๊ฐ ํ๊ตญ ๊ฒฝ์ ์ ๋ฏธ์น ์ํฅ์ ๋ค๊ฐ๋๋ก ๋ถ์ํ๊ณ ๋์ ์ ๋ต์ ์ ์ํด์ค",
|
| 819 |
"์คํํธ์
์ด ๋๊ธฐ์
๊ณผ ๊ฒฝ์ํ๊ธฐ ์ํ ํ์ ์ ์ธ ์ ๋ต์ ๋จ๊ณ๋ณ๋ก ์๋ฆฝํด์ค",
|
| 820 |
-
|
| 821 |
-
"
|
| 822 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
],
|
| 824 |
inputs=msg
|
| 825 |
)
|
|
@@ -827,7 +1186,7 @@ def create_optimized_gradio_interface():
|
|
| 827 |
# ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
|
| 828 |
submit.click(
|
| 829 |
process_query_optimized,
|
| 830 |
-
inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count],
|
| 831 |
outputs=[chatbot, agent_thoughts, search_sources]
|
| 832 |
).then(
|
| 833 |
lambda: "",
|
|
@@ -837,7 +1196,7 @@ def create_optimized_gradio_interface():
|
|
| 837 |
|
| 838 |
msg.submit(
|
| 839 |
process_query_optimized,
|
| 840 |
-
inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count],
|
| 841 |
outputs=[chatbot, agent_thoughts, search_sources]
|
| 842 |
).then(
|
| 843 |
lambda: "",
|
|
@@ -861,25 +1220,25 @@ def create_optimized_gradio_interface():
|
|
| 861 |
if __name__ == "__main__":
|
| 862 |
print("""
|
| 863 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 864 |
-
โ
|
| 865 |
โ โ
|
| 866 |
-
โ
|
| 867 |
โ โ
|
| 868 |
-
โ
|
| 869 |
-
โ โข
|
| 870 |
-
โ โข
|
| 871 |
-
โ โข
|
| 872 |
-
โ โข
|
| 873 |
-
โ โข
|
| 874 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 875 |
""")
|
| 876 |
|
| 877 |
# API ํค ํ์ธ
|
| 878 |
if not os.getenv("FIREWORKS_API_KEY"):
|
| 879 |
-
print("\nโ ๏ธ FIREWORKS_API_KEY
|
| 880 |
|
| 881 |
if not os.getenv("BRAVE_SEARCH_API_KEY"):
|
| 882 |
-
print("\nโ ๏ธ BRAVE_SEARCH_API_KEY
|
| 883 |
|
| 884 |
# Gradio ์ฑ ์คํ
|
| 885 |
demo = create_optimized_gradio_interface()
|
|
@@ -887,8 +1246,8 @@ if __name__ == "__main__":
|
|
| 887 |
is_hf_spaces = os.getenv("SPACE_ID") is not None
|
| 888 |
|
| 889 |
if is_hf_spaces:
|
| 890 |
-
print("\n๐ค Hugging Face Spaces
|
| 891 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 892 |
else:
|
| 893 |
-
print("\n๐ป
|
| 894 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
| 1 |
"""
|
| 2 |
โก Speed-Optimized Multi-Agent RAG System for Complex Questions
|
| 3 |
+
๋ณ๋ ฌ ์ฒ๋ฆฌ, ๋์ ํ์ดํ๋ผ์ธ์ผ๋ก ๋ณต์กํ ์ง๋ฌธ๋ ๋น ๋ฅด๊ฒ ์ฒ๋ฆฌ
|
| 4 |
+
Enhanced with multi-language support and improved error handling
|
| 5 |
+
(์บ์ฑ ๊ธฐ๋ฅ ์ ๊ฑฐ ๋ฒ์ )
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
|
|
|
| 10 |
import time
|
| 11 |
import asyncio
|
| 12 |
import hashlib
|
| 13 |
+
import re
|
| 14 |
+
import sys
|
| 15 |
from typing import Optional, List, Dict, Any, Tuple, Generator, AsyncGenerator
|
| 16 |
from datetime import datetime, timedelta
|
| 17 |
from enum import Enum
|
|
|
|
| 63 |
|
| 64 |
|
| 65 |
# ============================================================================
|
| 66 |
+
# ์ธ์ด ๊ฐ์ง ์ ํธ๋ฆฌํฐ
|
| 67 |
# ============================================================================
|
| 68 |
|
| 69 |
+
class LanguageDetector:
|
| 70 |
+
"""์ธ์ด ๊ฐ์ง ๋ฐ ์ฒ๋ฆฌ ์ ํธ๋ฆฌํฐ"""
|
| 71 |
|
| 72 |
+
@staticmethod
|
| 73 |
+
def detect_language(text: str) -> str:
|
| 74 |
+
"""๊ฐ๋จํ ์ธ์ด ๊ฐ์ง"""
|
| 75 |
+
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# ํ๊ธ ํจํด
|
| 78 |
+
korean_pattern = re.compile('[๊ฐ-ํฃ]+')
|
| 79 |
+
# ์ผ๋ณธ์ด ํจํด (ํ๋ผ๊ฐ๋, ๊ฐํ์นด๋)
|
| 80 |
+
japanese_pattern = re.compile('[ใ-ใ]+|[ใก-ใดใผ]+')
|
| 81 |
+
# ์ค๊ตญ์ด ํจํด
|
| 82 |
+
chinese_pattern = re.compile('[\u4e00-\u9fff]+')
|
| 83 |
+
|
| 84 |
+
# ํ
์คํธ ๊ธธ์ด ๋๋น ๊ฐ ์ธ์ด ๋ฌธ์ ๋น์จ ๊ณ์ฐ
|
| 85 |
+
text_length = len(text)
|
| 86 |
+
if text_length == 0:
|
| 87 |
+
return 'en'
|
| 88 |
|
| 89 |
+
korean_chars = len(korean_pattern.findall(text))
|
| 90 |
+
japanese_chars = len(japanese_pattern.findall(text))
|
| 91 |
+
chinese_chars = len(chinese_pattern.findall(text))
|
| 92 |
+
|
| 93 |
+
# ํ๊ธ ๋น์จ์ด 10% ์ด์์ด๋ฉด ํ๊ตญ์ด
|
| 94 |
+
if korean_chars > 0 and (korean_chars / text_length > 0.1):
|
| 95 |
+
return 'ko'
|
| 96 |
+
# ์ผ๋ณธ์ด ๋ฌธ์๊ฐ ์์ผ๋ฉด ์ผ๋ณธ์ด
|
| 97 |
+
elif japanese_chars > 0:
|
| 98 |
+
return 'ja'
|
| 99 |
+
# ์ค๊ตญ์ด ๋ฌธ์๊ฐ ์์ผ๋ฉด ์ค๊ตญ์ด
|
| 100 |
+
elif chinese_chars > 0:
|
| 101 |
+
return 'zh'
|
| 102 |
+
else:
|
| 103 |
+
return 'en'
|
| 104 |
|
| 105 |
|
| 106 |
# ============================================================================
|
| 107 |
+
# ๋ณ๋ ฌ ์ฒ๋ฆฌ ์ต์ ํ Brave Search (๊ฐ์ ๋จ)
|
| 108 |
# ============================================================================
|
| 109 |
|
| 110 |
class AsyncBraveSearch:
|
| 111 |
+
"""๋น๋๊ธฐ Brave ๊ฒ์ ํด๋ผ์ด์ธํธ with retry logic"""
|
| 112 |
|
| 113 |
def __init__(self, api_key: Optional[str] = None):
|
| 114 |
self.api_key = api_key or os.getenv("BRAVE_SEARCH_API_KEY")
|
| 115 |
self.base_url = "https://api.search.brave.com/res/v1/web/search"
|
| 116 |
+
self.max_retries = 3
|
| 117 |
|
| 118 |
+
async def search_async(self, query: str, count: int = 5, lang: str = 'ko') -> List[Dict]:
|
| 119 |
+
"""๋น๋๊ธฐ ๊ฒ์ with retry"""
|
| 120 |
if not self.api_key:
|
| 121 |
return []
|
| 122 |
|
|
|
|
| 125 |
"X-Subscription-Token": self.api_key
|
| 126 |
}
|
| 127 |
|
| 128 |
+
# ์ธ์ด๋ณ ํ๋ผ๋ฏธํฐ ์ค์
|
| 129 |
+
lang_params = {
|
| 130 |
+
'ko': {"search_lang": "ko", "country": "KR"},
|
| 131 |
+
'en': {"search_lang": "en", "country": "US"},
|
| 132 |
+
'ja': {"search_lang": "ja", "country": "JP"},
|
| 133 |
+
'zh': {"search_lang": "zh", "country": "CN"}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
params = {
|
| 137 |
"q": query,
|
| 138 |
"count": count,
|
| 139 |
"text_decorations": False,
|
| 140 |
+
**lang_params.get(lang, lang_params['en'])
|
|
|
|
| 141 |
}
|
| 142 |
|
| 143 |
+
for attempt in range(self.max_retries):
|
| 144 |
+
try:
|
| 145 |
+
async with aiohttp.ClientSession() as session:
|
| 146 |
+
async with session.get(
|
| 147 |
+
self.base_url,
|
| 148 |
+
headers=headers,
|
| 149 |
+
params=params,
|
| 150 |
+
timeout=aiohttp.ClientTimeout(total=5)
|
| 151 |
+
) as response:
|
| 152 |
+
if response.status == 200:
|
| 153 |
+
data = await response.json()
|
| 154 |
+
|
| 155 |
+
results = []
|
| 156 |
+
if "web" in data and "results" in data["web"]:
|
| 157 |
+
for item in data["web"]["results"][:count]:
|
| 158 |
+
results.append({
|
| 159 |
+
"title": item.get("title", ""),
|
| 160 |
+
"url": item.get("url", ""),
|
| 161 |
+
"description": item.get("description", ""),
|
| 162 |
+
"age": item.get("age", "")
|
| 163 |
+
})
|
| 164 |
+
|
| 165 |
+
return results
|
| 166 |
+
elif response.status == 429: # Rate limit
|
| 167 |
+
await asyncio.sleep(2 ** attempt)
|
| 168 |
+
continue
|
| 169 |
+
except aiohttp.ClientError as e:
|
| 170 |
+
if attempt < self.max_retries - 1:
|
| 171 |
+
await asyncio.sleep(2 ** attempt) # Exponential backoff
|
| 172 |
+
continue
|
| 173 |
+
except Exception:
|
| 174 |
+
pass
|
| 175 |
|
| 176 |
return []
|
| 177 |
+
|
| 178 |
+
async def batch_search(self, queries: List[str], lang: str = 'ko') -> List[List[Dict]]:
|
| 179 |
+
"""์ฌ๋ฌ ๊ฒ์์ ๋ฐฐ์น๋ก ์ฒ๋ฆฌ"""
|
| 180 |
+
tasks = [self.search_async(q, lang=lang) for q in queries]
|
| 181 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 182 |
+
# ์์ธ ์ฒ๋ฆฌ
|
| 183 |
+
return [r if not isinstance(r, Exception) else [] for r in results]
|
| 184 |
|
| 185 |
|
| 186 |
# ============================================================================
|
| 187 |
+
# ์ต์ ํ๋ Fireworks ํด๋ผ์ด์ธํธ (๊ฐ์ ๋จ)
|
| 188 |
# ============================================================================
|
| 189 |
|
| 190 |
class OptimizedFireworksClient:
|
| 191 |
+
"""์ต์ ํ๋ LLM ํด๋ผ์ด์ธํธ with language support"""
|
| 192 |
|
| 193 |
def __init__(self, api_key: Optional[str] = None):
|
| 194 |
self.api_key = api_key or os.getenv("FIREWORKS_API_KEY")
|
|
|
|
| 204 |
|
| 205 |
# ํญ์ ์ต๊ณ ์ฑ๋ฅ ๋ชจ๋ธ ์ฌ์ฉ (๋ณต์กํ ์ง๋ฌธ ์ ์ )
|
| 206 |
self.model = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
|
| 207 |
+
self.max_retries = 3
|
| 208 |
+
|
| 209 |
+
def compress_prompt(self, text: str, max_length: int = 2000) -> str:
|
| 210 |
+
"""ํ๋กฌํํธ ์์ถ"""
|
| 211 |
+
if len(text) <= max_length:
|
| 212 |
+
return text
|
| 213 |
+
|
| 214 |
+
# ์ค์ํ ๋ถ๋ถ ์ฐ์ ์์๋ก ์๋ฅด๊ธฐ
|
| 215 |
+
sentences = text.split('.')
|
| 216 |
+
compressed = []
|
| 217 |
+
current_length = 0
|
| 218 |
+
|
| 219 |
+
for sentence in sentences:
|
| 220 |
+
if current_length + len(sentence) > max_length:
|
| 221 |
+
break
|
| 222 |
+
compressed.append(sentence)
|
| 223 |
+
current_length += len(sentence)
|
| 224 |
+
|
| 225 |
+
return '.'.join(compressed)
|
| 226 |
|
| 227 |
async def chat_stream_async(
|
| 228 |
self,
|
| 229 |
messages: List[Dict],
|
| 230 |
**kwargs
|
| 231 |
) -> AsyncGenerator[str, None]:
|
| 232 |
+
"""๋น๋๊ธฐ ์คํธ๋ฆฌ๋ฐ ๋ํ with retry"""
|
| 233 |
|
| 234 |
payload = {
|
| 235 |
"model": self.model,
|
|
|
|
| 241 |
"stream": True
|
| 242 |
}
|
| 243 |
|
| 244 |
+
for attempt in range(self.max_retries):
|
| 245 |
+
try:
|
| 246 |
+
async with aiohttp.ClientSession() as session:
|
| 247 |
+
async with session.post(
|
| 248 |
+
self.base_url,
|
| 249 |
+
headers={**self.headers, "Accept": "text/event-stream"},
|
| 250 |
+
json=payload,
|
| 251 |
+
timeout=aiohttp.ClientTimeout(total=30)
|
| 252 |
+
) as response:
|
| 253 |
+
async for line in response.content:
|
| 254 |
+
line_str = line.decode('utf-8').strip()
|
| 255 |
+
if line_str.startswith("data: "):
|
| 256 |
+
data_str = line_str[6:]
|
| 257 |
+
if data_str == "[DONE]":
|
| 258 |
+
break
|
| 259 |
+
try:
|
| 260 |
+
data = json.loads(data_str)
|
| 261 |
+
if "choices" in data and len(data["choices"]) > 0:
|
| 262 |
+
delta = data["choices"][0].get("delta", {})
|
| 263 |
+
if "content" in delta:
|
| 264 |
+
yield delta["content"]
|
| 265 |
+
except json.JSONDecodeError:
|
| 266 |
+
continue
|
| 267 |
+
return # Success
|
| 268 |
+
except aiohttp.ClientError as e:
|
| 269 |
+
if attempt < self.max_retries - 1:
|
| 270 |
+
await asyncio.sleep(2 ** attempt)
|
| 271 |
+
continue
|
| 272 |
+
else:
|
| 273 |
+
yield f"Error after {self.max_retries} attempts: {str(e)}"
|
| 274 |
+
except Exception as e:
|
| 275 |
+
yield f"Unexpected error: {str(e)}"
|
| 276 |
+
break
|
| 277 |
|
| 278 |
|
| 279 |
# ============================================================================
|
| 280 |
+
# ๊ฒฝ๋ํ๋ ์ถ๋ก ์ฒด์ธ (๋ค๊ตญ์ด ์ง์)
|
| 281 |
# ============================================================================
|
| 282 |
|
| 283 |
class LightweightReasoningChain:
|
|
|
|
| 285 |
|
| 286 |
def __init__(self):
|
| 287 |
self.templates = {
|
| 288 |
+
"ko": {
|
| 289 |
+
"problem_solving": {
|
| 290 |
+
"steps": ["๋ฌธ์ ๋ถํด", "ํต์ฌ ์์ธ", "ํด๊ฒฐ ๋ฐฉ์", "๊ตฌํ ์ ๋ต"],
|
| 291 |
+
"prompt": "์ฒด๊ณ์ ์ผ๋ก ๋จ๊ณ๋ณ๋ก ๋ถ์ํ๊ณ ํด๊ฒฐ์ฑ
์ ์ ์ํ์ธ์."
|
| 292 |
+
},
|
| 293 |
+
"creative_thinking": {
|
| 294 |
+
"steps": ["๊ธฐ์กด ์ ๊ทผ", "์ฐฝ์์ ๋์", "ํ์ ํฌ์ธํธ", "์คํ ๋ฐฉ๋ฒ"],
|
| 295 |
+
"prompt": "๊ธฐ์กด ๋ฐฉ์์ ๋์ด์ ์ฐฝ์์ ์ด๊ณ ํ์ ์ ์ธ ์ ๊ทผ์ ์ ์ํ์ธ์."
|
| 296 |
+
},
|
| 297 |
+
"critical_analysis": {
|
| 298 |
+
"steps": ["ํํฉ ํ๊ฐ", "๊ฐ์ /์ฝ์ ", "๊ธฐํ/์ํ", "๊ฐ์ ๋ฐฉํฅ"],
|
| 299 |
+
"prompt": "๋นํ์ ๊ด์ ์์ ์ฒ ์ ํ ๋ถ์ํ๊ณ ๊ฐ์ ์ ์ ๋์ถํ์ธ์."
|
| 300 |
+
}
|
| 301 |
},
|
| 302 |
+
"en": {
|
| 303 |
+
"problem_solving": {
|
| 304 |
+
"steps": ["Problem Breakdown", "Key Factors", "Solutions", "Implementation Strategy"],
|
| 305 |
+
"prompt": "Systematically analyze step by step and provide solutions."
|
| 306 |
+
},
|
| 307 |
+
"creative_thinking": {
|
| 308 |
+
"steps": ["Traditional Approach", "Creative Alternatives", "Innovation Points", "Execution Method"],
|
| 309 |
+
"prompt": "Provide creative and innovative approaches beyond conventional methods."
|
| 310 |
+
},
|
| 311 |
+
"critical_analysis": {
|
| 312 |
+
"steps": ["Current Assessment", "Strengths/Weaknesses", "Opportunities/Threats", "Improvement Direction"],
|
| 313 |
+
"prompt": "Thoroughly analyze from a critical perspective and derive improvements."
|
| 314 |
+
}
|
| 315 |
}
|
| 316 |
}
|
| 317 |
|
| 318 |
+
def get_reasoning_structure(self, query_type: str, lang: str = 'ko') -> Dict:
|
| 319 |
"""์ฟผ๋ฆฌ ์ ํ์ ๋ง๋ ์ถ๋ก ๊ตฌ์กฐ ๋ฐํ"""
|
| 320 |
+
lang_templates = self.templates.get(lang, self.templates['en'])
|
| 321 |
+
return lang_templates.get(query_type, lang_templates["problem_solving"])
|
| 322 |
+
|
| 323 |
+
def get_reasoning_pattern(self, query: str, lang: str = 'ko') -> Optional[Dict]:
|
| 324 |
+
"""์ฟผ๋ฆฌ์ ์ ํฉํ ์ถ๋ก ํจํด ๋ฐํ"""
|
| 325 |
+
query_lower = query.lower()
|
| 326 |
+
|
| 327 |
+
# ์ธ์ด๋ณ ํค์๋ ๋งคํ
|
| 328 |
+
pattern_keywords = {
|
| 329 |
+
'ko': {
|
| 330 |
+
'problem_solving': ['ํด๊ฒฐ', '๋ฐฉ๋ฒ', '์ ๋ต', '๊ณํ'],
|
| 331 |
+
'creative_thinking': ['์ฐฝ์์ ', 'ํ์ ์ ', '์๋ก์ด', '์์ด๋์ด'],
|
| 332 |
+
'critical_analysis': ['๋ถ์', 'ํ๊ฐ', '๋น๊ต', '์ํฅ']
|
| 333 |
+
},
|
| 334 |
+
'en': {
|
| 335 |
+
'problem_solving': ['solve', 'solution', 'strategy', 'plan'],
|
| 336 |
+
'creative_thinking': ['creative', 'innovative', 'novel', 'idea'],
|
| 337 |
+
'critical_analysis': ['analyze', 'evaluate', 'compare', 'impact']
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
keywords = pattern_keywords.get(lang, pattern_keywords['en'])
|
| 342 |
+
|
| 343 |
+
for pattern_type, words in keywords.items():
|
| 344 |
+
if any(word in query_lower for word in words):
|
| 345 |
+
return self.get_reasoning_structure(pattern_type, lang)
|
| 346 |
+
|
| 347 |
+
return self.get_reasoning_structure('problem_solving', lang)
|
| 348 |
|
| 349 |
|
| 350 |
# ============================================================================
|
| 351 |
+
# ์กฐ๊ธฐ ์ข
๋ฃ ๋ฉ์ปค๋์ฆ (๊ฐ์ ๋จ)
|
| 352 |
# ============================================================================
|
| 353 |
|
| 354 |
class QualityChecker:
|
|
|
|
| 363 |
"clarity": 0.2
|
| 364 |
}
|
| 365 |
|
| 366 |
+
def evaluate_response(self, response: str, query: str, lang: str = 'ko') -> Tuple[float, bool]:
|
| 367 |
+
"""์๋ต ํ์ง ํ๊ฐ (์ธ์ด๋ณ)"""
|
| 368 |
scores = {}
|
| 369 |
|
| 370 |
+
# ์ธ์ด๋ณ ์ต์ ๊ธธ์ด ๊ธฐ์ค
|
| 371 |
+
min_length = {'ko': 500, 'en': 400, 'ja': 400, 'zh': 300}
|
| 372 |
+
target_length = min_length.get(lang, 400)
|
| 373 |
+
|
| 374 |
# ๊ธธ์ด ํ๊ฐ
|
| 375 |
+
scores["length"] = min(len(response) / target_length, 1.0)
|
| 376 |
|
| 377 |
+
# ๊ตฌ์กฐ ํ๊ฐ (์ธ์ด๋ณ ๋ง์ปค)
|
| 378 |
+
structure_markers = {
|
| 379 |
+
'ko': ["1.", "2.", "โข", "-", "์ฒซ์งธ", "๋์งธ", "๊ฒฐ๋ก ", "์์ฝ"],
|
| 380 |
+
'en': ["1.", "2.", "โข", "-", "First", "Second", "Conclusion", "Summary"],
|
| 381 |
+
'ja': ["1.", "2.", "โข", "-", "็ฌฌไธ", "็ฌฌไบ", "็ต่ซ", "่ฆ็ด"],
|
| 382 |
+
'zh': ["1.", "2.", "โข", "-", "็ฌฌไธ", "็ฌฌไบ", "็ป่ฎบ", "ๆป็ป"]
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
markers = structure_markers.get(lang, structure_markers['en'])
|
| 386 |
+
scores["structure"] = sum(1 for m in markers if m in response) / len(markers)
|
| 387 |
|
| 388 |
# ์์ ์ฑ ํ๊ฐ (์ฟผ๋ฆฌ ํค์๋ ํฌํจ ์ฌ๋ถ)
|
| 389 |
query_words = set(query.split())
|
|
|
|
| 391 |
scores["completeness"] = len(query_words & response_words) / max(len(query_words), 1)
|
| 392 |
|
| 393 |
# ๋ช
ํ์ฑ ํ๊ฐ (๋ฌธ์ฅ ๊ตฌ์กฐ)
|
| 394 |
+
sentence_delimiters = {
|
| 395 |
+
'ko': '.',
|
| 396 |
+
'en': '.',
|
| 397 |
+
'ja': 'ใ',
|
| 398 |
+
'zh': 'ใ'
|
| 399 |
+
}
|
| 400 |
+
delimiter = sentence_delimiters.get(lang, '.')
|
| 401 |
+
sentences = response.split(delimiter)
|
| 402 |
avg_sentence_length = sum(len(s.split()) for s in sentences) / max(len(sentences), 1)
|
| 403 |
+
scores["clarity"] = min(avg_sentence_length / 20, 1.0)
|
| 404 |
|
| 405 |
# ๊ฐ์ค ํ๊ท ๊ณ์ฐ
|
| 406 |
total_score = sum(
|
|
|
|
| 414 |
|
| 415 |
|
| 416 |
# ============================================================================
|
| 417 |
+
# ์คํธ๋ฆฌ๋ฐ ์ต์ ํ (๊ฐ์ ๋จ)
|
| 418 |
# ============================================================================
|
| 419 |
|
| 420 |
class OptimizedStreaming:
|
| 421 |
+
"""์คํธ๋ฆฌ๋ฐ ๋ฒํผ ์ต์ ํ with adaptive buffering"""
|
| 422 |
|
| 423 |
+
def __init__(self, chunk_size: int = 20, flush_interval: float = 0.05):
|
| 424 |
self.chunk_size = chunk_size
|
| 425 |
self.flush_interval = flush_interval
|
| 426 |
self.buffer = ""
|
| 427 |
self.last_flush = time.time()
|
| 428 |
+
self.adaptive_size = chunk_size
|
| 429 |
|
| 430 |
async def buffer_and_yield(
|
| 431 |
self,
|
| 432 |
+
stream: AsyncGenerator[str, None],
|
| 433 |
+
adaptive: bool = True
|
| 434 |
) -> AsyncGenerator[str, None]:
|
| 435 |
+
"""๋ฒํผ๋ง๋ ์คํธ๋ฆฌ๋ฐ with adaptive sizing"""
|
| 436 |
|
| 437 |
+
chunk_count = 0
|
| 438 |
async for chunk in stream:
|
| 439 |
self.buffer += chunk
|
| 440 |
current_time = time.time()
|
| 441 |
+
chunk_count += 1
|
| 442 |
|
| 443 |
+
# Adaptive chunk size based on stream speed
|
| 444 |
+
if adaptive and chunk_count % 10 == 0:
|
| 445 |
+
time_diff = current_time - self.last_flush
|
| 446 |
+
if time_diff < 0.02: # Too fast, increase buffer
|
| 447 |
+
self.adaptive_size = min(self.adaptive_size + 5, 100)
|
| 448 |
+
elif time_diff > 0.1: # Too slow, decrease buffer
|
| 449 |
+
self.adaptive_size = max(self.adaptive_size - 5, 10)
|
| 450 |
+
|
| 451 |
+
if (len(self.buffer) >= self.adaptive_size or
|
| 452 |
current_time - self.last_flush >= self.flush_interval):
|
| 453 |
|
| 454 |
yield self.buffer
|
|
|
|
| 461 |
|
| 462 |
|
| 463 |
# ============================================================================
|
| 464 |
+
# ์๋ต ํ์ฒ๋ฆฌ ์ ํธ๋ฆฌํฐ
|
| 465 |
+
# ============================================================================
|
| 466 |
+
|
| 467 |
+
class ResponseCleaner:
|
| 468 |
+
"""์๋ต ์ ๋ฆฌ ๋ฐ ํฌ๋งทํ
"""
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def clean_response(response: str) -> str:
|
| 472 |
+
"""๋ถํ์ํ ๋งํฌ์
์ ๊ฑฐ ๊ฐํ"""
|
| 473 |
+
# ๋งํฌ๋ค์ด ํค๋ ์ ๊ฑฐ
|
| 474 |
+
response = re.sub(r'^#{1,6}\s+', '', response, flags=re.MULTILINE)
|
| 475 |
+
|
| 476 |
+
# ๋ถํ์ํ ๊ตฌ๋ถ์ ์ ๊ฑฐ
|
| 477 |
+
response = re.sub(r'\*{2,}|_{2,}|-{3,}', '', response)
|
| 478 |
+
|
| 479 |
+
# ์ค๋ณต ๊ณต๋ฐฑ ์ ๊ฑฐ
|
| 480 |
+
response = re.sub(r'\n{3,}', '\n\n', response)
|
| 481 |
+
|
| 482 |
+
# ํน์ ํจํด ์ ๊ฑฐ
|
| 483 |
+
unwanted_patterns = [
|
| 484 |
+
r'\| --- # ๐ฑ \*\*์ต์ข
ํตํฉ ๋ต๋ณ:',
|
| 485 |
+
r'\*\*โ์ค๋ฅ: ---',
|
| 486 |
+
r'^\s*\*\*\[.*?\]\*\*\s*', # [ํ๊ทธ] ํ์ ์ ๊ฑฐ
|
| 487 |
+
r'^\s*###\s*', # ### ์ ๊ฑฐ
|
| 488 |
+
r'^\s*##\s*', # ## ์ ๊ฑฐ
|
| 489 |
+
r'^\s*#\s*' # # ์ ๊ฑฐ
|
| 490 |
+
]
|
| 491 |
+
|
| 492 |
+
for pattern in unwanted_patterns:
|
| 493 |
+
response = re.sub(pattern, '', response, flags=re.MULTILINE)
|
| 494 |
+
|
| 495 |
+
return response.strip()
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
# ============================================================================
|
| 499 |
+
# ํตํฉ ์ต์ ํ ๋ฉํฐ ์์ด์ ํธ ์์คํ
(์บ์ฑ ์ ๊ฑฐ ๋ฒ์ )
|
| 500 |
# ============================================================================
|
| 501 |
|
| 502 |
class SpeedOptimizedMultiAgentSystem:
|
| 503 |
+
"""์๋ ์ต์ ํ๋ ๋ฉํฐ ์์ด์ ํธ ์์คํ
(์บ์ฑ ์์)"""
|
| 504 |
|
| 505 |
def __init__(self):
|
| 506 |
self.llm = OptimizedFireworksClient()
|
| 507 |
self.search = AsyncBraveSearch()
|
|
|
|
| 508 |
self.reasoning = LightweightReasoningChain()
|
| 509 |
self.quality_checker = QualityChecker()
|
| 510 |
self.streaming = OptimizedStreaming()
|
| 511 |
+
self.language_detector = LanguageDetector()
|
| 512 |
+
self.response_cleaner = ResponseCleaner()
|
|
|
|
| 513 |
|
| 514 |
# ๋ณ๋ ฌ ์ฒ๋ฆฌ ํ
|
| 515 |
self.executor = ThreadPoolExecutor(max_workers=4)
|
| 516 |
|
| 517 |
+
def _init_compact_prompts(self, lang: str = 'ko') -> Dict:
|
| 518 |
+
"""์์ถ๋ ๊ณ ํจ์จ ํ๋กฌํํธ (์ธ์ด๋ณ)"""
|
| 519 |
+
prompts = {
|
| 520 |
+
'ko': {
|
| 521 |
+
AgentRole.SUPERVISOR: """[๊ฐ๋
์-๊ตฌ์กฐ์ค๊ณ]
|
| 522 |
์ฆ์๋ถ์: ํต์ฌ์๋+ํ์์ ๋ณด+๋ต๋ณ๊ตฌ์กฐ
|
| 523 |
์ถ๋ ฅ: 5๊ฐ ํต์ฌํฌ์ธํธ(๊ฐ 1๋ฌธ์ฅ)
|
| 524 |
์ถ๋ก ์ฒด๊ณ ๋ช
์""",
|
| 525 |
+
|
| 526 |
+
AgentRole.CREATIVE: """[์ฐฝ์์ฑ์์ฑ์]
|
| 527 |
์
๋ ฅ๊ตฌ์กฐ ๋ฐ๋ผ ์ฐฝ์์ ํ์ฅ
|
| 528 |
์ค์ฉ์์+ํ์ ์ ๊ทผ+๊ตฌ์ฒด์กฐ์ธ
|
| 529 |
๋ถํ์์ค๋ช
์ ๊ฑฐ""",
|
| 530 |
+
|
| 531 |
+
AgentRole.CRITIC: """[๋นํ์-๊ฒ์ฆ]
|
| 532 |
์ ์๊ฒํ : ์ ํ์ฑ/๋
ผ๋ฆฌ์ฑ/์ค์ฉ์ฑ
|
| 533 |
๊ฐ์ ํฌ์ธํธ 3๊ฐ๋ง
|
| 534 |
๊ฐ 2๋ฌธ์ฅ ์ด๋ด""",
|
| 535 |
+
|
| 536 |
+
AgentRole.FINALIZER: """[์ต์ข
ํตํฉ]
|
| 537 |
๋ชจ๋ ์๊ฒฌ ์ข
ํฉโ์ต์ ๋ต๋ณ
|
| 538 |
๋ช
ํ๊ตฌ์กฐ+์ค์ฉ์ ๋ณด+์ฐฝ์๊ท ํ
|
| 539 |
+
๋ฐ๋ก ํต์ฌ ๋ด์ฉ๋ถํฐ ์์. ๋ถํ์ํ ํค๋๋ ๋งํฌ์
์์ด. ๋งํฌ๋ค์ด ํค๋(#, ##, ###) ์ฌ์ฉ ๊ธ์ง."""
|
| 540 |
+
},
|
| 541 |
+
'en': {
|
| 542 |
+
AgentRole.SUPERVISOR: """[Supervisor-Structure]
|
| 543 |
+
Immediate analysis: core intent+required info+answer structure
|
| 544 |
+
Output: 5 key points (1 sentence each)
|
| 545 |
+
Clear reasoning framework""",
|
| 546 |
+
|
| 547 |
+
AgentRole.CREATIVE: """[Creative Generator]
|
| 548 |
+
Follow structure, expand creatively
|
| 549 |
+
Practical examples+innovative approach+specific advice
|
| 550 |
+
Remove unnecessary explanations""",
|
| 551 |
+
|
| 552 |
+
AgentRole.CRITIC: """[Critic-Verification]
|
| 553 |
+
Quick review: accuracy/logic/practicality
|
| 554 |
+
Only 3 improvement points
|
| 555 |
+
Max 2 sentences each""",
|
| 556 |
+
|
| 557 |
+
AgentRole.FINALIZER: """[Final Integration]
|
| 558 |
+
Synthesize all inputsโoptimal answer
|
| 559 |
+
Clear structure+practical info+creative balance
|
| 560 |
+
Start with core content directly. No unnecessary headers or markup. No markdown headers (#, ##, ###)."""
|
| 561 |
+
},
|
| 562 |
+
'ja': {
|
| 563 |
+
AgentRole.SUPERVISOR: """[็ฃ็ฃ่
-ๆง้ ่จญ่จ]
|
| 564 |
+
ๅณๆๅๆ๏ผๆ ธๅฟๆๅณ+ๅฟ
่ฆๆ
ๅ ฑ+ๅ็ญๆง้
|
| 565 |
+
ๅบๅ๏ผ5ใคใฎๆ ธๅฟใใคใณใ๏ผๅ1ๆ๏ผ
|
| 566 |
+
ๆจ่ซไฝ็ณปๆ็คบ""",
|
| 567 |
+
|
| 568 |
+
AgentRole.CREATIVE: """[ๅต้ ๆง็ๆ่
]
|
| 569 |
+
ๅ
ฅๅๆง้ ใซๅพใฃใฆๅต้ ็ๆกๅผต
|
| 570 |
+
ๅฎ็จไพ+้ฉๆฐ็ใขใใญใผใ+ๅ
ทไฝ็ใขใใใคใน
|
| 571 |
+
ไธ่ฆใช่ชฌๆๅ้ค""",
|
| 572 |
+
|
| 573 |
+
AgentRole.CRITIC: """[ๆน่ฉ่
-ๆค่จผ]
|
| 574 |
+
่ฟ
้ใฌใใฅใผ๏ผๆญฃ็ขบๆง/่ซ็ๆง/ๅฎ็จๆง
|
| 575 |
+
ๆนๅใใคใณใ3ใคใฎใฟ
|
| 576 |
+
ๅ2ๆไปฅๅ
""",
|
| 577 |
+
|
| 578 |
+
AgentRole.FINALIZER: """[ๆ็ต็ตฑๅ]
|
| 579 |
+
ๅ
จๆ่ฆ็ตฑๅโๆ้ฉๅ็ญ
|
| 580 |
+
ๆ็ขบๆง้ +ๅฎ็จๆ
ๅ ฑ+ๅต้ ๆงใใฉใณใน
|
| 581 |
+
ๆ ธๅฟๅ
ๅฎนใใ็ดๆฅ้ๅงใไธ่ฆใชใใใใผใใใผใฏใขใใใชใใใใผใฏใใฆใณใใใใผ๏ผ#ใ##ใ###๏ผไฝฟ็จ็ฆๆญขใ"""
|
| 582 |
+
},
|
| 583 |
+
'zh': {
|
| 584 |
+
AgentRole.SUPERVISOR: """[ไธป็ฎก-็ปๆ่ฎพ่ฎก]
|
| 585 |
+
็ซๅณๅๆ๏ผๆ ธๅฟๆๅพ+ๆ้ไฟกๆฏ+็ญๆก็ปๆ
|
| 586 |
+
่พๅบ๏ผ5ไธชๆ ธๅฟ่ฆ็น๏ผๆฏไธช1ๅฅ๏ผ
|
| 587 |
+
ๆจ็ไฝ็ณปๆ็กฎ""",
|
| 588 |
+
|
| 589 |
+
AgentRole.CREATIVE: """[ๅๆ็ๆๅจ]
|
| 590 |
+
ๆ็ปๆๅ้ ๆงๆฉๅฑ
|
| 591 |
+
ๅฎ็จ็คบไพ+ๅๆฐๆนๆณ+ๅ
ทไฝๅปบ่ฎฎ
|
| 592 |
+
ๅ ้คไธๅฟ
่ฆ็่งฃ้""",
|
| 593 |
+
|
| 594 |
+
AgentRole.CRITIC: """[่ฏ่ฎบๅฎถ-้ช่ฏ]
|
| 595 |
+
ๅฟซ้ๅฎกๆฅ๏ผๅ็กฎๆง/้ป่พๆง/ๅฎ็จๆง
|
| 596 |
+
ไป
3ไธชๆน่ฟ็น
|
| 597 |
+
ๆฏไธชๆๅค2ๅฅ""",
|
| 598 |
+
|
| 599 |
+
AgentRole.FINALIZER: """[ๆ็ปๆดๅ]
|
| 600 |
+
็ปผๅๆๆๆ่งโๆไฝณ็ญๆก
|
| 601 |
+
ๆธ
ๆฐ็ปๆ+ๅฎ็จไฟกๆฏ+ๅๆๅนณ่กก
|
| 602 |
+
็ดๆฅไปๆ ธๅฟๅ
ๅฎนๅผๅงใๆ ้ไธๅฟ
่ฆ็ๆ ้ขๆๆ ่ฎฐใ็ฆๆญขไฝฟ็จMarkdownๆ ้ข๏ผ#ใ##ใ###๏ผใ"""
|
| 603 |
+
}
|
| 604 |
}
|
| 605 |
+
|
| 606 |
+
return prompts.get(lang, prompts['en'])
|
| 607 |
|
| 608 |
async def parallel_process_agents(
|
| 609 |
self,
|
| 610 |
query: str,
|
| 611 |
search_results: List[Dict],
|
| 612 |
+
show_progress: bool = True,
|
| 613 |
+
lang: str = None
|
| 614 |
) -> AsyncGenerator[Tuple[str, str], None]:
|
| 615 |
+
"""๋ณ๋ ฌ ์ฒ๋ฆฌ ํ์ดํ๋ผ์ธ (์บ์ฑ ์์)"""
|
| 616 |
|
| 617 |
start_time = time.time()
|
| 618 |
+
|
| 619 |
+
# ์ธ์ด ์๋ ๊ฐ์ง
|
| 620 |
+
if lang is None:
|
| 621 |
+
lang = self.language_detector.detect_language(query)
|
| 622 |
+
|
| 623 |
+
# ์ธ์ด๋ณ ํ๋กฌํํธ ์ค์
|
| 624 |
+
self.compact_prompts = self._init_compact_prompts(lang)
|
| 625 |
+
|
| 626 |
search_context = self._format_search_results(search_results)
|
| 627 |
accumulated_response = ""
|
| 628 |
agent_thoughts = ""
|
| 629 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 630 |
# ์ถ๋ก ํจํด ๊ฒฐ์
|
| 631 |
+
reasoning_pattern = self.reasoning.get_reasoning_pattern(query, lang)
|
| 632 |
|
| 633 |
try:
|
| 634 |
# === 1๋จ๊ณ: ๊ฐ๋
์ + ๊ฒ์ ๋ณ๋ ฌ ์คํ ===
|
| 635 |
if show_progress:
|
| 636 |
+
progress_msg = {
|
| 637 |
+
'ko': "๐ ๋ณ๋ ฌ ์ฒ๋ฆฌ ์์\n๐ ๊ฐ๋
์ ๋ถ์ + ๐ ์ถ๊ฐ ๊ฒ์ ๋์ ์งํ...\n\n",
|
| 638 |
+
'en': "๐ Starting parallel processing\n๐ Supervisor analysis + ๐ Additional search in progress...\n\n",
|
| 639 |
+
'ja': "๐ ไธฆๅๅฆ็้ๅง\n๐ ็ฃ็ฃ่
ๅๆ + ๐ ่ฟฝๅ ๆค็ดขๅๆ้ฒ่กไธญ...\n\n",
|
| 640 |
+
'zh': "๐ ๅผๅงๅนถ่กๅค็\n๐ ไธป็ฎกๅๆ + ๐ ้ๅ ๆ็ดขๅๆถ่ฟ่ก...\n\n"
|
| 641 |
+
}
|
| 642 |
+
agent_thoughts = progress_msg.get(lang, progress_msg['en'])
|
| 643 |
yield accumulated_response, agent_thoughts
|
| 644 |
|
| 645 |
+
# ๊ฐ๋
์ ํ๋กฌํํธ (์ธ์ด๋ณ)
|
| 646 |
+
supervisor_prompt_templates = {
|
| 647 |
+
'ko': f"""
|
| 648 |
์ง๋ฌธ: {query}
|
| 649 |
๊ฒ์๊ฒฐ๊ณผ: {search_context}
|
| 650 |
์ถ๋ก ํจํด: {reasoning_pattern}
|
| 651 |
+
์ฆ์ ํต์ฌ๊ตฌ์กฐ 5๊ฐ ์ ์""",
|
| 652 |
+
'en': f"""
|
| 653 |
+
Question: {query}
|
| 654 |
+
Search results: {search_context}
|
| 655 |
+
Reasoning pattern: {reasoning_pattern}
|
| 656 |
+
Immediately provide 5 key structures""",
|
| 657 |
+
'ja': f"""
|
| 658 |
+
่ณชๅ: {query}
|
| 659 |
+
ๆค็ดข็ตๆ: {search_context}
|
| 660 |
+
ๆจ่ซใใฟใผใณ: {reasoning_pattern}
|
| 661 |
+
ๅณๅบงใซ5ใคใฎๆ ธๅฟๆง้ ใๆ็คบ""",
|
| 662 |
+
'zh': f"""
|
| 663 |
+
้ฎ้ข: {query}
|
| 664 |
+
ๆ็ดข็ปๆ: {search_context}
|
| 665 |
+
ๆจ็ๆจกๅผ: {reasoning_pattern}
|
| 666 |
+
็ซๅณๆไพ5ไธชๆ ธๅฟ็ปๆ"""
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
supervisor_prompt = supervisor_prompt_templates.get(lang, supervisor_prompt_templates['en'])
|
| 670 |
|
| 671 |
supervisor_response = ""
|
| 672 |
supervisor_task = self.llm.chat_stream_async(
|
|
|
|
| 682 |
async for chunk in self.streaming.buffer_and_yield(supervisor_task):
|
| 683 |
supervisor_response += chunk
|
| 684 |
if show_progress and len(supervisor_response) < 300:
|
| 685 |
+
supervisor_label = {
|
| 686 |
+
'ko': "๐ ๊ฐ๋
์ ๋ถ์",
|
| 687 |
+
'en': "๐ Supervisor Analysis",
|
| 688 |
+
'ja': "๐ ็ฃ็ฃ่
ๅๆ",
|
| 689 |
+
'zh': "๐ ไธป็ฎกๅๆ"
|
| 690 |
+
}
|
| 691 |
+
agent_thoughts = f"{supervisor_label.get(lang, supervisor_label['en'])}\n{supervisor_response[:300]}...\n\n"
|
| 692 |
yield accumulated_response, agent_thoughts
|
| 693 |
|
| 694 |
# === 2๋จ๊ณ: ์ฐฝ์์ฑ + ๋นํ ์ค๋น ๋ณ๋ ฌ ===
|
| 695 |
if show_progress:
|
| 696 |
+
creative_msg = {
|
| 697 |
+
'ko': "๐จ ์ฐฝ์์ฑ ์์ฑ์ + ๐ ๋นํ์ ์ค๋น...\n\n",
|
| 698 |
+
'en': "๐จ Creative Generator + ๐ Critic preparing...\n\n",
|
| 699 |
+
'ja': "๐จ ๅต้ ๆง็ๆ่
+ ๐ ๆน่ฉ่
ๆบๅไธญ...\n\n",
|
| 700 |
+
'zh': "๐จ ๅๆ็ๆๅจ + ๐ ่ฏ่ฎบๅฎถๅๅคไธญ...\n\n"
|
| 701 |
+
}
|
| 702 |
+
agent_thoughts += creative_msg.get(lang, creative_msg['en'])
|
| 703 |
yield accumulated_response, agent_thoughts
|
| 704 |
|
| 705 |
+
# ์ฐฝ์์ฑ ์์ฑ ์์ (์ธ์ด๋ณ)
|
| 706 |
+
creative_prompt_templates = {
|
| 707 |
+
'ko': f"""
|
| 708 |
์ง๋ฌธ: {query}
|
| 709 |
๊ฐ๋
์๊ตฌ์กฐ: {supervisor_response}
|
| 710 |
๊ฒ์๊ฒฐ๊ณผ: {search_context}
|
| 711 |
+
์ฐฝ์์ +์ค์ฉ์ ๋ต๋ณ ์ฆ์์์ฑ""",
|
| 712 |
+
'en': f"""
|
| 713 |
+
Question: {query}
|
| 714 |
+
Supervisor structure: {supervisor_response}
|
| 715 |
+
Search results: {search_context}
|
| 716 |
+
Generate creative+practical answer immediately""",
|
| 717 |
+
'ja': f"""
|
| 718 |
+
่ณชๅ: {query}
|
| 719 |
+
็ฃ็ฃ่
ๆง้ : {supervisor_response}
|
| 720 |
+
ๆค็ดข็ตๆ: {search_context}
|
| 721 |
+
ๅต้ ็+ๅฎ็จ็ๅ็ญๅณๅบง็ๆ""",
|
| 722 |
+
'zh': f"""
|
| 723 |
+
้ฎ้ข: {query}
|
| 724 |
+
ไธป็ฎก็ปๆ: {supervisor_response}
|
| 725 |
+
ๆ็ดข็ปๆ: {search_context}
|
| 726 |
+
็ซๅณ็ๆๅๆ+ๅฎ็จ็ญๆก"""
|
| 727 |
+
}
|
| 728 |
+
|
| 729 |
+
creative_prompt = creative_prompt_templates.get(lang, creative_prompt_templates['en'])
|
| 730 |
|
| 731 |
creative_response = ""
|
| 732 |
+
creative_partial = ""
|
| 733 |
critic_started = False
|
| 734 |
critic_response = ""
|
| 735 |
|
|
|
|
| 751 |
if len(creative_partial) > 500 and not critic_started:
|
| 752 |
critic_started = True
|
| 753 |
|
| 754 |
+
# ๋นํ์ ๋น๋๊ธฐ ์์ (์ธ์ด๋ณ)
|
| 755 |
+
critic_prompt_templates = {
|
| 756 |
+
'ko': f"""
|
| 757 |
์๋ณธ์ง๋ฌธ: {query}
|
| 758 |
์ฐฝ์์ฑ๋ต๋ณ(์ผ๋ถ): {creative_partial}
|
| 759 |
+
์ ์๊ฒํ โ๊ฐ์ ์ 3๊ฐ""",
|
| 760 |
+
'en': f"""
|
| 761 |
+
Original question: {query}
|
| 762 |
+
Creative answer (partial): {creative_partial}
|
| 763 |
+
Quick reviewโ3 improvements""",
|
| 764 |
+
'ja': f"""
|
| 765 |
+
ๅ
ใฎ่ณชๅ: {query}
|
| 766 |
+
ๅต้ ็ๅ็ญ๏ผไธ้จ๏ผ: {creative_partial}
|
| 767 |
+
่ฟ
้ใฌใใฅใผโๆนๅ็น3ใค""",
|
| 768 |
+
'zh': f"""
|
| 769 |
+
ๅๅง้ฎ้ข: {query}
|
| 770 |
+
ๅๆ็ญๆก๏ผ้จๅ๏ผ: {creative_partial}
|
| 771 |
+
ๅฟซ้ๅฎกๆฅโ3ไธชๆน่ฟ็น"""
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
critic_prompt = critic_prompt_templates.get(lang, critic_prompt_templates['en'])
|
| 775 |
|
| 776 |
critic_task = asyncio.create_task(
|
| 777 |
self._run_critic_async(critic_prompt)
|
|
|
|
| 779 |
|
| 780 |
if show_progress:
|
| 781 |
display_creative = creative_response[:400] + "..." if len(creative_response) > 400 else creative_response
|
| 782 |
+
creative_label = {
|
| 783 |
+
'ko': "๐จ ์ฐฝ์์ฑ ์์ฑ์",
|
| 784 |
+
'en': "๐จ Creative Generator",
|
| 785 |
+
'ja': "๐จ ๅต้ ๆง็ๆ่
",
|
| 786 |
+
'zh': "๐จ ๅๆ็ๆๅจ"
|
| 787 |
+
}
|
| 788 |
+
agent_thoughts = f"{creative_label.get(lang, creative_label['en'])}\n{display_creative}\n\n"
|
| 789 |
yield accumulated_response, agent_thoughts
|
| 790 |
|
| 791 |
# ๋นํ์ ๊ฒฐ๊ณผ ๋๊ธฐ
|
|
|
|
| 793 |
critic_response = await critic_task
|
| 794 |
|
| 795 |
if show_progress:
|
| 796 |
+
critic_label = {
|
| 797 |
+
'ko': "๐ ๋นํ์ ๊ฒํ ",
|
| 798 |
+
'en': "๐ Critic Review",
|
| 799 |
+
'ja': "๐ ๆน่ฉ่
ใฌใใฅใผ",
|
| 800 |
+
'zh': "๐ ่ฏ่ฎบๅฎถๅฎกๆฅ"
|
| 801 |
+
}
|
| 802 |
+
agent_thoughts += f"{critic_label.get(lang, critic_label['en'])}\n{critic_response[:200]}...\n\n"
|
| 803 |
yield accumulated_response, agent_thoughts
|
| 804 |
|
| 805 |
# === 3๋จ๊ณ: ํ์ง ์ฒดํฌ ๋ฐ ์กฐ๊ธฐ ์ข
๋ฃ ===
|
| 806 |
quality_score, need_more = self.quality_checker.evaluate_response(
|
| 807 |
+
creative_response, query, lang
|
| 808 |
)
|
| 809 |
|
| 810 |
if not need_more and quality_score > 0.85:
|
| 811 |
# ํ์ง์ด ์ถฉ๋ถํ ๋์ผ๋ฉด ๋ฐ๋ก ๋ฐํ
|
| 812 |
+
accumulated_response = self.response_cleaner.clean_response(creative_response)
|
| 813 |
|
| 814 |
if show_progress:
|
| 815 |
+
quality_msg = {
|
| 816 |
+
'ko': f"โ
ํ์ง ์ถฉ์กฑ (์ ์: {quality_score:.2f})\n์กฐ๊ธฐ ์๋ฃ!\n",
|
| 817 |
+
'en': f"โ
Quality met (score: {quality_score:.2f})\nEarly completion!\n",
|
| 818 |
+
'ja': f"โ
ๅ่ณชๆบ่ถณ (ในใณใข: {quality_score:.2f})\nๆฉๆๅฎไบ!\n",
|
| 819 |
+
'zh': f"โ
่ดจ้ๆปก่ถณ (ๅๆฐ: {quality_score:.2f})\nๆๅๅฎๆ!\n"
|
| 820 |
+
}
|
| 821 |
+
agent_thoughts += quality_msg.get(lang, quality_msg['en'])
|
| 822 |
|
| 823 |
yield accumulated_response, agent_thoughts
|
| 824 |
return
|
| 825 |
|
| 826 |
# === 4๋จ๊ณ: ์ต์ข
ํตํฉ (์คํธ๋ฆฌ๋ฐ) ===
|
| 827 |
if show_progress:
|
| 828 |
+
final_msg = {
|
| 829 |
+
'ko': "โ
์ต์ข
ํตํฉ ์ค...\n\n",
|
| 830 |
+
'en': "โ
Final integration in progress...\n\n",
|
| 831 |
+
'ja': "โ
ๆ็ต็ตฑๅไธญ...\n\n",
|
| 832 |
+
'zh': "โ
ๆ็ปๆดๅไธญ...\n\n"
|
| 833 |
+
}
|
| 834 |
+
agent_thoughts += final_msg.get(lang, final_msg['en'])
|
| 835 |
yield accumulated_response, agent_thoughts
|
| 836 |
|
| 837 |
+
# ์ต์ข
ํ๋กฌํํธ (์ธ์ด๋ณ)
|
| 838 |
+
final_prompt_templates = {
|
| 839 |
+
'ko': f"""
|
| 840 |
์ง๋ฌธ: {query}
|
| 841 |
์ฐฝ์์ฑ๋ต๋ณ: {creative_response}
|
| 842 |
๋นํํผ๋๋ฐฑ: {critic_response}
|
| 843 |
๊ฐ๋
์๊ตฌ์กฐ: {supervisor_response}
|
| 844 |
+
์ต์ข
ํตํฉโ์๋ฒฝ๋ต๋ณ. ๋งํฌ๋ค์ด ํค๋(#, ##, ###) ์ฌ์ฉ ๊ธ์ง.""",
|
| 845 |
+
'en': f"""
|
| 846 |
+
Question: {query}
|
| 847 |
+
Creative answer: {creative_response}
|
| 848 |
+
Critic feedback: {critic_response}
|
| 849 |
+
Supervisor structure: {supervisor_response}
|
| 850 |
+
Final integrationโperfect answer. No markdown headers (#, ##, ###).""",
|
| 851 |
+
'ja': f"""
|
| 852 |
+
่ณชๅ: {query}
|
| 853 |
+
ๅต้ ็ๅ็ญ: {creative_response}
|
| 854 |
+
ๆน่ฉใใฃใผใใใใฏ: {critic_response}
|
| 855 |
+
็ฃ็ฃ่
ๆง้ : {supervisor_response}
|
| 856 |
+
ๆ็ต็ตฑๅโๅฎ็งใชๅ็ญใใใผใฏใใฆใณใใใใผ๏ผ#ใ##ใ###๏ผไฝฟ็จ็ฆๆญขใ""",
|
| 857 |
+
'zh': f"""
|
| 858 |
+
้ฎ้ข: {query}
|
| 859 |
+
ๅๆ็ญๆก: {creative_response}
|
| 860 |
+
่ฏ่ฎบๅ้ฆ: {critic_response}
|
| 861 |
+
ไธป็ฎก็ปๆ: {supervisor_response}
|
| 862 |
+
ๆ็ปๆดๅโๅฎ็พ็ญๆกใ็ฆๆญขไฝฟ็จMarkdownๆ ้ข๏ผ#ใ##ใ###๏ผใ"""
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
final_prompt = final_prompt_templates.get(lang, final_prompt_templates['en'])
|
| 866 |
|
| 867 |
final_task = self.llm.chat_stream_async(
|
| 868 |
messages=[
|
|
|
|
| 875 |
|
| 876 |
# ์ต์ข
๋ต๋ณ ์คํธ๋ฆฌ๋ฐ
|
| 877 |
accumulated_response = ""
|
| 878 |
+
|
| 879 |
+
async for chunk in final_task:
|
| 880 |
accumulated_response += chunk
|
| 881 |
+
# ์ค์๊ฐ ์ ๋ฆฌ
|
| 882 |
+
cleaned_response = self.response_cleaner.clean_response(accumulated_response)
|
| 883 |
+
yield cleaned_response, agent_thoughts
|
| 884 |
|
| 885 |
+
# ์ต์ข
์ ๋ฆฌ
|
| 886 |
+
accumulated_response = self.response_cleaner.clean_response(accumulated_response)
|
|
|
|
| 887 |
|
| 888 |
+
# ์ฒ๋ฆฌ ์๊ฐ ์ถ๊ฐ (์ธ์ด๋ณ)
|
| 889 |
+
processing_time = time.time() - start_time
|
| 890 |
+
time_msg = {
|
| 891 |
+
'ko': f"\n\n---\nโก ์ฒ๋ฆฌ ์๊ฐ: {processing_time:.1f}์ด",
|
| 892 |
+
'en': f"\n\n---\nโก Processing time: {processing_time:.1f} seconds",
|
| 893 |
+
'ja': f"\n\n---\nโก ๅฆ็ๆ้: {processing_time:.1f}็ง",
|
| 894 |
+
'zh': f"\n\n---\nโก ๅค็ๆถ้ด: {processing_time:.1f}็ง"
|
| 895 |
+
}
|
| 896 |
+
accumulated_response += time_msg.get(lang, time_msg['en'])
|
| 897 |
|
| 898 |
yield accumulated_response, agent_thoughts
|
| 899 |
|
| 900 |
except Exception as e:
|
| 901 |
+
error_msg = {
|
| 902 |
+
'ko': f"โ ์ค๋ฅ ๋ฐ์: {str(e)}",
|
| 903 |
+
'en': f"โ Error occurred: {str(e)}",
|
| 904 |
+
'ja': f"โ ใจใฉใผ็บ็: {str(e)}",
|
| 905 |
+
'zh': f"โ ๅ็้่ฏฏ: {str(e)}"
|
| 906 |
+
}
|
| 907 |
+
yield error_msg.get(lang, error_msg['en']), agent_thoughts
|
| 908 |
|
| 909 |
async def _run_critic_async(self, prompt: str) -> str:
|
| 910 |
+
"""๋นํ์ ๋น๋๊ธฐ ์คํ with error handling"""
|
| 911 |
try:
|
| 912 |
response = ""
|
| 913 |
async for chunk in self.llm.chat_stream_async(
|
|
|
|
| 920 |
):
|
| 921 |
response += chunk
|
| 922 |
return response
|
| 923 |
+
except Exception as e:
|
| 924 |
+
# ์ธ์ด ๊ฐ์ง
|
| 925 |
+
lang = 'ko' if '์ง๋ฌธ' in prompt else 'en'
|
| 926 |
+
error_msg = {
|
| 927 |
+
'ko': "๋นํ ์ฒ๋ฆฌ ์ค ์ค๋ฅ",
|
| 928 |
+
'en': "Error during critic processing",
|
| 929 |
+
'ja': "ๆน่ฉๅฆ็ไธญใฎใจใฉใผ",
|
| 930 |
+
'zh': "่ฏ่ฎบๅค็ไธญๅบ้"
|
| 931 |
+
}
|
| 932 |
+
return error_msg.get(lang, error_msg['en'])
|
| 933 |
|
| 934 |
def _format_search_results(self, results: List[Dict]) -> str:
|
| 935 |
"""๊ฒ์ ๊ฒฐ๊ณผ ์์ถ ํฌ๋งท"""
|
| 936 |
if not results:
|
| 937 |
+
return "No search results"
|
| 938 |
|
| 939 |
formatted = []
|
| 940 |
+
for i, r in enumerate(results[:3], 1):
|
| 941 |
+
title = r.get('title', '')[:50]
|
| 942 |
+
desc = r.get('description', '')[:100]
|
| 943 |
+
formatted.append(f"[{i}]{title}:{desc}")
|
| 944 |
|
| 945 |
return " | ".join(formatted)
|
| 946 |
|
| 947 |
|
| 948 |
# ============================================================================
|
| 949 |
+
# Gradio UI (์ต์ ํ ๋ฒ์ - ์บ์ฑ ์ ๊ฑฐ)
|
| 950 |
# ============================================================================
|
| 951 |
|
| 952 |
def create_optimized_gradio_interface():
|
| 953 |
+
"""์ต์ ํ๋ Gradio ์ธํฐํ์ด์ค (์บ์ฑ ์์)"""
|
| 954 |
|
| 955 |
# ์์คํ
์ด๊ธฐํ
|
| 956 |
system = SpeedOptimizedMultiAgentSystem()
|
|
|
|
| 960 |
history: List[Dict],
|
| 961 |
use_search: bool,
|
| 962 |
show_agent_thoughts: bool,
|
| 963 |
+
search_count: int,
|
| 964 |
+
language_mode: str
|
| 965 |
):
|
| 966 |
+
"""์ต์ ํ๋ ์ฟผ๋ฆฌ ์ฒ๋ฆฌ - ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ๋ฒ์ """
|
| 967 |
|
| 968 |
if not message:
|
| 969 |
yield history, "", ""
|
| 970 |
return
|
| 971 |
|
| 972 |
+
# ์ธ์ด ์ค์
|
| 973 |
+
if language_mode == "Auto":
|
| 974 |
+
lang = None # ์๋ ๊ฐ์ง
|
| 975 |
+
else:
|
| 976 |
+
lang_map = {"Korean": "ko", "English": "en", "Japanese": "ja", "Chinese": "zh"}
|
| 977 |
+
lang = lang_map.get(language_mode, None)
|
| 978 |
+
|
| 979 |
# ๋น๋๊ธฐ ํจ์๋ฅผ ๋๊ธฐ์ ์ผ๋ก ์คํ
|
| 980 |
try:
|
| 981 |
import nest_asyncio
|
| 982 |
nest_asyncio.apply()
|
| 983 |
except ImportError:
|
| 984 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 985 |
|
| 986 |
try:
|
| 987 |
# ๊ฒ์ ์ํ (๋๊ธฐํ)
|
| 988 |
search_results = []
|
| 989 |
search_display = ""
|
| 990 |
|
| 991 |
+
# ์ธ์ด ์๋ ๊ฐ์ง (ํ์ํ ๊ฒฝ์ฐ)
|
| 992 |
+
detected_lang = lang or system.language_detector.detect_language(message)
|
| 993 |
+
|
| 994 |
if use_search:
|
| 995 |
# ๊ฒ์ ์ํ ํ์
|
| 996 |
+
processing_msg = {
|
| 997 |
+
'ko': "โก ๊ณ ์ ์ฒ๋ฆฌ ์ค...",
|
| 998 |
+
'en': "โก High-speed processing...",
|
| 999 |
+
'ja': "โก ้ซ้ๅฆ็ไธญ...",
|
| 1000 |
+
'zh': "โก ้ซ้ๅค็ไธญ..."
|
| 1001 |
+
}
|
| 1002 |
history_with_message = history + [
|
| 1003 |
{"role": "user", "content": message},
|
| 1004 |
+
{"role": "assistant", "content": processing_msg.get(detected_lang, processing_msg['en'])}
|
| 1005 |
]
|
| 1006 |
yield history_with_message, "", ""
|
| 1007 |
|
| 1008 |
# ๋น๋๊ธฐ ๊ฒ์์ ๋๊ธฐ์ ์ผ๋ก ์คํ
|
| 1009 |
+
async def search_wrapper():
|
| 1010 |
+
return await system.search.search_async(message, count=search_count, lang=detected_lang)
|
| 1011 |
+
|
| 1012 |
+
loop = asyncio.new_event_loop()
|
| 1013 |
+
asyncio.set_event_loop(loop)
|
| 1014 |
+
search_results = loop.run_until_complete(search_wrapper())
|
| 1015 |
|
| 1016 |
if search_results:
|
| 1017 |
+
ref_label = {
|
| 1018 |
+
'ko': "๐ ์ฐธ๊ณ ์๋ฃ",
|
| 1019 |
+
'en': "๐ References",
|
| 1020 |
+
'ja': "๐ ๅ่่ณๆ",
|
| 1021 |
+
'zh': "๐ ๅ๏ฟฝ๏ฟฝ๏ฟฝ่ตๆ"
|
| 1022 |
+
}
|
| 1023 |
+
search_display = f"{ref_label.get(detected_lang, ref_label['en'])}\n\n"
|
| 1024 |
for i, result in enumerate(search_results[:3], 1):
|
| 1025 |
search_display += f"**{i}. [{result['title'][:50]}]({result['url']})**\n"
|
| 1026 |
search_display += f" {result['description'][:100]}...\n\n"
|
|
|
|
| 1028 |
# ์ฌ์ฉ์ ๋ฉ์์ง ์ถ๊ฐ
|
| 1029 |
current_history = history + [{"role": "user", "content": message}]
|
| 1030 |
|
| 1031 |
+
# ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ์ ์ํ ๋น๋๊ธฐ ์ฒ๋ฆฌ
|
| 1032 |
+
async def stream_responses():
|
| 1033 |
+
"""์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ ์ ๋๋ ์ดํฐ"""
|
| 1034 |
async for response, thoughts in system.parallel_process_agents(
|
| 1035 |
query=message,
|
| 1036 |
search_results=search_results,
|
| 1037 |
+
show_progress=show_agent_thoughts,
|
| 1038 |
+
lang=detected_lang
|
| 1039 |
):
|
| 1040 |
+
yield response, thoughts
|
|
|
|
| 1041 |
|
| 1042 |
+
# ์ ์ด๋ฒคํธ ๋ฃจํ์์ ์ค์๊ฐ ์คํธ๋ฆฌ๋ฐ
|
| 1043 |
+
loop = asyncio.new_event_loop()
|
| 1044 |
+
asyncio.set_event_loop(loop)
|
| 1045 |
|
| 1046 |
+
# ๋น๋๊ธฐ ์ ๋๋ ์ดํฐ๋ฅผ ๋๊ธฐ์ ์ผ๋ก ์ํ
|
| 1047 |
+
gen = stream_responses()
|
| 1048 |
+
|
| 1049 |
+
while True:
|
| 1050 |
+
try:
|
| 1051 |
+
# ๋ค์ ํญ๋ชฉ ๊ฐ์ ธ์ค๊ธฐ
|
| 1052 |
+
task = asyncio.ensure_future(gen.__anext__(), loop=loop)
|
| 1053 |
+
response, thoughts = loop.run_until_complete(task)
|
| 1054 |
+
|
| 1055 |
+
# ์ค์๊ฐ ์
๋ฐ์ดํธ
|
| 1056 |
+
updated_history = current_history + [
|
| 1057 |
+
{"role": "assistant", "content": response}
|
| 1058 |
+
]
|
| 1059 |
+
yield updated_history, thoughts, search_display
|
| 1060 |
+
|
| 1061 |
+
except StopAsyncIteration:
|
| 1062 |
+
break
|
| 1063 |
|
| 1064 |
except Exception as e:
|
| 1065 |
error_history = history + [
|
| 1066 |
{"role": "user", "content": message},
|
| 1067 |
+
{"role": "assistant", "content": f"โ Error: {str(e)}"}
|
| 1068 |
]
|
| 1069 |
yield error_history, "", ""
|
| 1070 |
+
finally:
|
| 1071 |
+
# ๋ฃจํ ์ ๋ฆฌ
|
| 1072 |
+
try:
|
| 1073 |
+
loop.close()
|
| 1074 |
+
except:
|
| 1075 |
+
pass
|
| 1076 |
|
| 1077 |
# Gradio ์ธํฐํ์ด์ค
|
| 1078 |
with gr.Blocks(
|
| 1079 |
+
title="โก Speed-Optimized Multi-Agent System (No Cache)",
|
| 1080 |
theme=gr.themes.Soft(),
|
| 1081 |
css="""
|
| 1082 |
.gradio-container {
|
|
|
|
| 1086 |
"""
|
| 1087 |
) as demo:
|
| 1088 |
gr.Markdown("""
|
| 1089 |
+
# โก Enhanced Multi-Agent RAG System (์บ์ฑ ์ ๊ฑฐ ๋ฒ์ )
|
| 1090 |
+
**Complex questions processed within 5-8 seconds | Multi-language support**
|
| 1091 |
+
|
| 1092 |
+
**Optimization Features:**
|
| 1093 |
+
- ๐ Parallel Processing: Concurrent agent execution
|
| 1094 |
+
- โก Stream Buffering: Network optimization
|
| 1095 |
+
- ๐ฏ Early Termination: Complete immediately when quality is met
|
| 1096 |
+
- ๐ Multi-language: Auto-detect Korean/English/Japanese/Chinese
|
| 1097 |
+
- โ **Caching Disabled**: ์บ์ฑ ๊ธฐ๋ฅ ์ ๊ฑฐ๋จ
|
| 1098 |
""")
|
| 1099 |
|
| 1100 |
with gr.Row():
|
| 1101 |
with gr.Column(scale=3):
|
| 1102 |
chatbot = gr.Chatbot(
|
| 1103 |
height=500,
|
| 1104 |
+
label="๐ฌ Chat",
|
| 1105 |
type="messages"
|
| 1106 |
)
|
| 1107 |
|
| 1108 |
msg = gr.Textbox(
|
| 1109 |
+
label="Enter complex question",
|
| 1110 |
+
placeholder="Enter complex questions requiring analysis, strategy, or creative solutions...",
|
| 1111 |
lines=3
|
| 1112 |
)
|
| 1113 |
|
| 1114 |
with gr.Row():
|
| 1115 |
+
submit = gr.Button("โก High-Speed Process", variant="primary")
|
| 1116 |
+
clear = gr.Button("๐ Reset")
|
| 1117 |
|
| 1118 |
+
with gr.Accordion("๐ค Agent Processing", open=False):
|
| 1119 |
agent_thoughts = gr.Markdown()
|
| 1120 |
|
| 1121 |
+
with gr.Accordion("๐ Search Sources", open=False):
|
| 1122 |
search_sources = gr.Markdown()
|
| 1123 |
|
| 1124 |
with gr.Column(scale=1):
|
| 1125 |
+
gr.Markdown("**โ๏ธ Settings**")
|
| 1126 |
+
|
| 1127 |
+
language_mode = gr.Radio(
|
| 1128 |
+
choices=["Auto", "Korean", "English", "Japanese", "Chinese"],
|
| 1129 |
+
value="Auto",
|
| 1130 |
+
label="๐ Language Mode"
|
| 1131 |
+
)
|
| 1132 |
|
| 1133 |
use_search = gr.Checkbox(
|
| 1134 |
+
label="๐ Use Web Search",
|
| 1135 |
value=True
|
| 1136 |
)
|
| 1137 |
|
| 1138 |
show_agent_thoughts = gr.Checkbox(
|
| 1139 |
+
label="๐ง Show Processing",
|
| 1140 |
value=True
|
| 1141 |
)
|
| 1142 |
|
|
|
|
| 1145 |
maximum=10,
|
| 1146 |
value=5,
|
| 1147 |
step=1,
|
| 1148 |
+
label="Search Results Count"
|
| 1149 |
)
|
| 1150 |
|
| 1151 |
gr.Markdown("""
|
| 1152 |
+
**โก Optimization Status**
|
| 1153 |
+
|
| 1154 |
+
**Active Optimizations:**
|
| 1155 |
+
- โ
Parallel Processing
|
| 1156 |
+
- โ ~~Smart Caching~~ (์ ๊ฑฐ๋จ)
|
| 1157 |
+
- โ
Buffer Streaming
|
| 1158 |
+
- โ
Early Termination
|
| 1159 |
+
- โ
Compressed Prompts
|
| 1160 |
+
- โ
Multi-language Support
|
| 1161 |
+
- โ
Error Recovery
|
| 1162 |
+
|
| 1163 |
+
**Expected Processing Time:**
|
| 1164 |
+
- Simple Query: 3-5 seconds
|
| 1165 |
+
- Complex Query: 5-8 seconds
|
| 1166 |
+
- Very Complex: 8-12 seconds
|
| 1167 |
""")
|
| 1168 |
|
| 1169 |
+
# ๋ณต์กํ ์ง๋ฌธ ์์ (๋ค๊ตญ์ด)
|
| 1170 |
gr.Examples(
|
| 1171 |
examples=[
|
| 1172 |
+
# Korean
|
| 1173 |
"AI ๊ธฐ์ ์ด ํฅํ 10๋
๊ฐ ํ๊ตญ ๊ฒฝ์ ์ ๋ฏธ์น ์ํฅ์ ๋ค๊ฐ๋๋ก ๋ถ์ํ๊ณ ๋์ ์ ๋ต์ ์ ์ํด์ค",
|
| 1174 |
"์คํํธ์
์ด ๋๊ธฐ์
๊ณผ ๊ฒฝ์ํ๊ธฐ ์ํ ํ์ ์ ์ธ ์ ๋ต์ ๋จ๊ณ๋ณ๋ก ์๋ฆฝํด์ค",
|
| 1175 |
+
# English
|
| 1176 |
+
"Analyze the multifaceted impact of quantum computing on current encryption systems and propose alternatives",
|
| 1177 |
+
"Design 5 innovative business models for climate change mitigation with practical implementation details",
|
| 1178 |
+
# Japanese
|
| 1179 |
+
"ใกใฟใใผในๆไปฃใฎๆ่ฒ้ฉๆฐๆนๆกใๅฎ่ฃ
ๅฏ่ฝใชใฌใใซใงๆๆกใใฆใใ ใใ",
|
| 1180 |
+
# Chinese
|
| 1181 |
+
"ๅๆไบบๅทฅๆบ่ฝๅฏนๆชๆฅๅๅนดๅ
จ็็ปๆต็ๅฝฑๅๅนถๆๅบๅบๅฏน็ญ็ฅ"
|
| 1182 |
],
|
| 1183 |
inputs=msg
|
| 1184 |
)
|
|
|
|
| 1186 |
# ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
|
| 1187 |
submit.click(
|
| 1188 |
process_query_optimized,
|
| 1189 |
+
inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count, language_mode],
|
| 1190 |
outputs=[chatbot, agent_thoughts, search_sources]
|
| 1191 |
).then(
|
| 1192 |
lambda: "",
|
|
|
|
| 1196 |
|
| 1197 |
msg.submit(
|
| 1198 |
process_query_optimized,
|
| 1199 |
+
inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count, language_mode],
|
| 1200 |
outputs=[chatbot, agent_thoughts, search_sources]
|
| 1201 |
).then(
|
| 1202 |
lambda: "",
|
|
|
|
| 1220 |
if __name__ == "__main__":
|
| 1221 |
print("""
|
| 1222 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 1223 |
+
โ โก Speed-Optimized Multi-Agent System (No Cache) โก โ
|
| 1224 |
โ โ
|
| 1225 |
+
โ High-speed AI system processing complex questions โ
|
| 1226 |
โ โ
|
| 1227 |
+
โ Features: โ
|
| 1228 |
+
โ โข Multi-language support (KO/EN/JA/ZH) โ
|
| 1229 |
+
โ โข Improved error recovery โ
|
| 1230 |
+
โ โข NO CACHING (์บ์ฑ ๊ธฐ๋ฅ ์ ๊ฑฐ๋จ) โ
|
| 1231 |
+
โ โข Adaptive stream buffering โ
|
| 1232 |
+
โ โข Response cleaning & formatting โ
|
| 1233 |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 1234 |
""")
|
| 1235 |
|
| 1236 |
# API ํค ํ์ธ
|
| 1237 |
if not os.getenv("FIREWORKS_API_KEY"):
|
| 1238 |
+
print("\nโ ๏ธ FIREWORKS_API_KEY is not set.")
|
| 1239 |
|
| 1240 |
if not os.getenv("BRAVE_SEARCH_API_KEY"):
|
| 1241 |
+
print("\nโ ๏ธ BRAVE_SEARCH_API_KEY is not set.")
|
| 1242 |
|
| 1243 |
# Gradio ์ฑ ์คํ
|
| 1244 |
demo = create_optimized_gradio_interface()
|
|
|
|
| 1246 |
is_hf_spaces = os.getenv("SPACE_ID") is not None
|
| 1247 |
|
| 1248 |
if is_hf_spaces:
|
| 1249 |
+
print("\n๐ค Running in optimized mode on Hugging Face Spaces (No Cache)...")
|
| 1250 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 1251 |
else:
|
| 1252 |
+
print("\n๐ป Running in optimized mode on local environment (No Cache)...")
|
| 1253 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|