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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
β‘ Speed-Optimized Multi-Agent RAG System for Complex Questions
|
| 3 |
+
λ³λ ¬ μ²λ¦¬, μ€λ§νΈ μΊμ±, λμ νμ΄νλΌμΈμΌλ‘ 볡μ‘ν μ§λ¬Έλ λΉ λ₯΄κ² μ²λ¦¬
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
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
|
| 14 |
+
from collections import deque
|
| 15 |
+
import threading
|
| 16 |
+
import queue
|
| 17 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 18 |
+
import aiohttp
|
| 19 |
+
|
| 20 |
+
import requests
|
| 21 |
+
import gradio as gr
|
| 22 |
+
from pydantic import BaseModel, Field
|
| 23 |
+
from dotenv import load_dotenv
|
| 24 |
+
|
| 25 |
+
# νκ²½λ³μ λ‘λ
|
| 26 |
+
load_dotenv()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ============================================================================
|
| 30 |
+
# λ°μ΄ν° λͺ¨λΈ μ μ
|
| 31 |
+
# ============================================================================
|
| 32 |
+
|
| 33 |
+
class AgentRole(Enum):
|
| 34 |
+
"""μμ΄μ νΈ μν μ μ"""
|
| 35 |
+
SUPERVISOR = "supervisor"
|
| 36 |
+
CREATIVE = "creative"
|
| 37 |
+
CRITIC = "critic"
|
| 38 |
+
FINALIZER = "finalizer"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ExecutionMode(Enum):
|
| 42 |
+
"""μ€ν λͺ¨λ μ μ"""
|
| 43 |
+
PARALLEL = "parallel" # λ³λ ¬ μ²λ¦¬
|
| 44 |
+
SEQUENTIAL = "sequential" # μμ°¨ μ²λ¦¬
|
| 45 |
+
HYBRID = "hybrid" # νμ΄λΈλ¦¬λ
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Message(BaseModel):
|
| 49 |
+
role: str
|
| 50 |
+
content: str
|
| 51 |
+
timestamp: Optional[datetime] = None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AgentResponse(BaseModel):
|
| 55 |
+
role: AgentRole
|
| 56 |
+
content: str
|
| 57 |
+
processing_time: float
|
| 58 |
+
metadata: Optional[Dict] = None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ============================================================================
|
| 62 |
+
# μ€λ§νΈ μΊμ± μμ€ν
|
| 63 |
+
# ============================================================================
|
| 64 |
+
|
| 65 |
+
class SmartCache:
|
| 66 |
+
"""μ§λ₯ν μΊμ± μμ€ν
"""
|
| 67 |
+
|
| 68 |
+
def __init__(self, max_size: int = 100, ttl_hours: int = 24):
|
| 69 |
+
self.cache = {}
|
| 70 |
+
self.access_count = {}
|
| 71 |
+
self.timestamps = {}
|
| 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 |
+
for pattern_type, pattern_data in self.reasoning_patterns.items():
|
| 139 |
+
if any(keyword in query_lower for keyword in pattern_data["keywords"]):
|
| 140 |
+
return {
|
| 141 |
+
"type": pattern_type,
|
| 142 |
+
"structure": pattern_data["structure"]
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
return None
|
| 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 |
+
|
| 164 |
+
headers = {
|
| 165 |
+
"Accept": "application/json",
|
| 166 |
+
"X-Subscription-Token": self.api_key
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
params = {
|
| 170 |
+
"q": query,
|
| 171 |
+
"count": count,
|
| 172 |
+
"text_decorations": False,
|
| 173 |
+
"search_lang": "ko",
|
| 174 |
+
"country": "KR"
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
async with aiohttp.ClientSession() as session:
|
| 179 |
+
async with session.get(
|
| 180 |
+
self.base_url,
|
| 181 |
+
headers=headers,
|
| 182 |
+
params=params,
|
| 183 |
+
timeout=aiohttp.ClientTimeout(total=5)
|
| 184 |
+
) as response:
|
| 185 |
+
if response.status == 200:
|
| 186 |
+
data = await response.json()
|
| 187 |
+
|
| 188 |
+
results = []
|
| 189 |
+
if "web" in data and "results" in data["web"]:
|
| 190 |
+
for item in data["web"]["results"][:count]:
|
| 191 |
+
results.append({
|
| 192 |
+
"title": item.get("title", ""),
|
| 193 |
+
"url": item.get("url", ""),
|
| 194 |
+
"description": item.get("description", ""),
|
| 195 |
+
"age": item.get("age", "")
|
| 196 |
+
})
|
| 197 |
+
|
| 198 |
+
return results
|
| 199 |
+
except:
|
| 200 |
+
return []
|
| 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")
|
| 214 |
+
if not self.api_key:
|
| 215 |
+
raise ValueError("FIREWORKS_API_KEY is required!")
|
| 216 |
+
|
| 217 |
+
self.base_url = "https://api.fireworks.ai/inference/v1/chat/completions"
|
| 218 |
+
self.headers = {
|
| 219 |
+
"Accept": "application/json",
|
| 220 |
+
"Content-Type": "application/json",
|
| 221 |
+
"Authorization": f"Bearer {self.api_key}"
|
| 222 |
+
}
|
| 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,
|
| 236 |
+
"messages": messages,
|
| 237 |
+
"max_tokens": kwargs.get("max_tokens", 2000),
|
| 238 |
+
"temperature": kwargs.get("temperature", 0.7),
|
| 239 |
+
"top_p": kwargs.get("top_p", 1.0),
|
| 240 |
+
"top_k": kwargs.get("top_k", 40),
|
| 241 |
+
"stream": True
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
try:
|
| 245 |
+
async with aiohttp.ClientSession() as session:
|
| 246 |
+
async with session.post(
|
| 247 |
+
self.base_url,
|
| 248 |
+
headers={**self.headers, "Accept": "text/event-stream"},
|
| 249 |
+
json=payload,
|
| 250 |
+
timeout=aiohttp.ClientTimeout(total=30)
|
| 251 |
+
) as response:
|
| 252 |
+
async for line in response.content:
|
| 253 |
+
line_str = line.decode('utf-8').strip()
|
| 254 |
+
if line_str.startswith("data: "):
|
| 255 |
+
data_str = line_str[6:]
|
| 256 |
+
if data_str == "[DONE]":
|
| 257 |
+
break
|
| 258 |
+
try:
|
| 259 |
+
data = json.loads(data_str)
|
| 260 |
+
if "choices" in data and len(data["choices"]) > 0:
|
| 261 |
+
delta = data["choices"][0].get("delta", {})
|
| 262 |
+
if "content" in delta:
|
| 263 |
+
yield delta["content"]
|
| 264 |
+
except json.JSONDecodeError:
|
| 265 |
+
continue
|
| 266 |
+
except Exception as e:
|
| 267 |
+
yield f"μ€λ₯: {str(e)}"
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# ============================================================================
|
| 271 |
+
# κ²½λνλ μΆλ‘ 체μΈ
|
| 272 |
+
# ============================================================================
|
| 273 |
+
|
| 274 |
+
class LightweightReasoningChain:
|
| 275 |
+
"""λΉ λ₯Έ μΆλ‘ μ μν ν
νλ¦Ώ κΈ°λ° μμ€ν
"""
|
| 276 |
+
|
| 277 |
+
def __init__(self):
|
| 278 |
+
self.templates = {
|
| 279 |
+
"problem_solving": {
|
| 280 |
+
"steps": ["λ¬Έμ λΆν΄", "ν΅μ¬ μμΈ", "ν΄κ²° λ°©μ", "ꡬν μ λ΅"],
|
| 281 |
+
"prompt": "체κ³μ μΌλ‘ λ¨κ³λ³λ‘ λΆμνκ³ ν΄κ²°μ±
μ μ μνμΈμ."
|
| 282 |
+
},
|
| 283 |
+
"creative_thinking": {
|
| 284 |
+
"steps": ["κΈ°μ‘΄ μ κ·Ό", "μ°½μμ λμ", "νμ ν¬μΈνΈ", "μ€ν λ°©λ²"],
|
| 285 |
+
"prompt": "κΈ°μ‘΄ λ°©μμ λμ΄μ μ°½μμ μ΄κ³ νμ μ μΈ μ κ·Όμ μ μνμΈμ."
|
| 286 |
+
},
|
| 287 |
+
"critical_analysis": {
|
| 288 |
+
"steps": ["νν© νκ°", "κ°μ /μ½μ ", "κΈ°ν/μν", "κ°μ λ°©ν₯"],
|
| 289 |
+
"prompt": "λΉνμ κ΄μ μμ μ² μ ν λΆμνκ³ κ°μ μ μ λμΆνμΈμ."
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
def get_reasoning_structure(self, query_type: str) -> Dict:
|
| 294 |
+
"""쿼리 μ νμ λ§λ μΆλ‘ ꡬ쑰 λ°ν"""
|
| 295 |
+
# κΈ°λ³Έκ°μ problem_solving
|
| 296 |
+
return self.templates.get(query_type, self.templates["problem_solving"])
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
# ============================================================================
|
| 300 |
+
# μ‘°κΈ° μ’
λ£ λ©μ»€λμ¦
|
| 301 |
+
# ============================================================================
|
| 302 |
+
|
| 303 |
+
class QualityChecker:
|
| 304 |
+
"""νμ§ μ²΄ν¬ λ° μ‘°κΈ° μ’
λ£ κ²°μ """
|
| 305 |
+
|
| 306 |
+
def __init__(self, min_quality: float = 0.75):
|
| 307 |
+
self.min_quality = min_quality
|
| 308 |
+
self.quality_metrics = {
|
| 309 |
+
"length": 0.2,
|
| 310 |
+
"structure": 0.3,
|
| 311 |
+
"completeness": 0.3,
|
| 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) / 1000, 1.0) # 1000μ κΈ°μ€
|
| 321 |
+
|
| 322 |
+
# ꡬ쑰 νκ°
|
| 323 |
+
structure_markers = ["1.", "2.", "β’", "-", "첫째", "λμ§Έ", "κ²°λ‘ ", "μμ½"]
|
| 324 |
+
scores["structure"] = sum(1 for m in structure_markers if m in response) / len(structure_markers)
|
| 325 |
+
|
| 326 |
+
# μμ μ± νκ° (쿼리 ν€μλ ν¬ν¨ μ¬λΆ)
|
| 327 |
+
query_words = set(query.split())
|
| 328 |
+
response_words = set(response.split())
|
| 329 |
+
scores["completeness"] = len(query_words & response_words) / max(len(query_words), 1)
|
| 330 |
+
|
| 331 |
+
# λͺ
νμ± νκ° (λ¬Έμ₯ ꡬ쑰)
|
| 332 |
+
sentences = response.split('.')
|
| 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) # 20λ¨μ΄ κΈ°μ€
|
| 335 |
+
|
| 336 |
+
# κ°μ€ νκ· κ³μ°
|
| 337 |
+
total_score = sum(
|
| 338 |
+
scores[metric] * weight
|
| 339 |
+
for metric, weight in self.quality_metrics.items()
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
should_continue = total_score < self.min_quality
|
| 343 |
+
|
| 344 |
+
return total_score, should_continue
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# ============================================================================
|
| 348 |
+
# μ€νΈλ¦¬λ° μ΅μ ν
|
| 349 |
+
# ============================================================================
|
| 350 |
+
|
| 351 |
+
class OptimizedStreaming:
|
| 352 |
+
"""μ€νΈλ¦¬λ° λ²νΌ μ΅μ ν"""
|
| 353 |
+
|
| 354 |
+
def __init__(self, chunk_size: int = 100, flush_interval: float = 0.1):
|
| 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 |
+
if (len(self.buffer) >= self.chunk_size or
|
| 371 |
+
current_time - self.last_flush >= self.flush_interval):
|
| 372 |
+
|
| 373 |
+
yield self.buffer
|
| 374 |
+
self.buffer = ""
|
| 375 |
+
self.last_flush = current_time
|
| 376 |
+
|
| 377 |
+
# λ¨μ λ²νΌ νλ¬μ
|
| 378 |
+
if self.buffer:
|
| 379 |
+
yield self.buffer
|
| 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 |
+
return {
|
| 406 |
+
AgentRole.SUPERVISOR: """[κ°λ
μ-ꡬ쑰μ€κ³]
|
| 407 |
+
μ¦μλΆμ: ν΅μ¬μλ+νμμ 보+λ΅λ³κ΅¬μ‘°
|
| 408 |
+
μΆλ ₯: 5κ° ν΅μ¬ν¬μΈνΈ(κ° 1λ¬Έμ₯)
|
| 409 |
+
μΆλ‘ μ²΄κ³ λͺ
μ""",
|
| 410 |
+
|
| 411 |
+
AgentRole.CREATIVE: """[μ°½μμ±μμ±μ]
|
| 412 |
+
μ
λ ₯ꡬ쑰 λ°λΌ μ°½μμ νμ₯
|
| 413 |
+
μ€μ©μμ+νμ μ κ·Ό+ꡬ체쑰μΈ
|
| 414 |
+
λΆνμμ€λͺ
μ κ±°""",
|
| 415 |
+
|
| 416 |
+
AgentRole.CRITIC: """[λΉνμ-κ²μ¦]
|
| 417 |
+
μ μκ²ν : μ νμ±/λ
Όλ¦¬μ±/μ€μ©μ±
|
| 418 |
+
κ°μ ν¬μΈνΈ 3κ°λ§
|
| 419 |
+
κ° 2λ¬Έμ₯ μ΄λ΄""",
|
| 420 |
+
|
| 421 |
+
AgentRole.FINALIZER: """[μ΅μ’
ν΅ν©]
|
| 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.cache.get_reasoning_pattern(query)
|
| 448 |
+
|
| 449 |
+
try:
|
| 450 |
+
# === 1λ¨κ³: κ°λ
μ + κ²μ λ³λ ¬ μ€ν ===
|
| 451 |
+
if show_progress:
|
| 452 |
+
agent_thoughts = "### π λ³λ ¬ μ²λ¦¬ μμ\n"
|
| 453 |
+
agent_thoughts += "π κ°λ
μ λΆμ + π μΆκ° κ²μ λμ μ§ν...\n\n"
|
| 454 |
+
yield accumulated_response, agent_thoughts
|
| 455 |
+
|
| 456 |
+
# κ°λ
μ ν둬ννΈ
|
| 457 |
+
supervisor_prompt = f"""
|
| 458 |
+
μ§λ¬Έ: {query}
|
| 459 |
+
κ²μκ²°κ³Ό: {search_context}
|
| 460 |
+
μΆλ‘ ν¨ν΄: {reasoning_pattern}
|
| 461 |
+
μ¦μ ν΅μ¬κ΅¬μ‘° 5κ° μ μ"""
|
| 462 |
+
|
| 463 |
+
supervisor_response = ""
|
| 464 |
+
supervisor_task = self.llm.chat_stream_async(
|
| 465 |
+
messages=[
|
| 466 |
+
{"role": "system", "content": self.compact_prompts[AgentRole.SUPERVISOR]},
|
| 467 |
+
{"role": "user", "content": supervisor_prompt}
|
| 468 |
+
],
|
| 469 |
+
temperature=0.3,
|
| 470 |
+
max_tokens=500
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
# κ°λ
μ μ€νΈλ¦¬λ° (λ²νΌλ§)
|
| 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 |
+
agent_thoughts = f"### π κ°λ
μ λΆμ\n{supervisor_response[:300]}...\n\n"
|
| 478 |
+
yield accumulated_response, agent_thoughts
|
| 479 |
+
|
| 480 |
+
# === 2λ¨κ³: μ°½μμ± + λΉν μ€λΉ λ³λ ¬ ===
|
| 481 |
+
if show_progress:
|
| 482 |
+
agent_thoughts += "### π¨ μ°½μμ± μμ±μ + π λΉνμ μ€λΉ...\n\n"
|
| 483 |
+
yield accumulated_response, agent_thoughts
|
| 484 |
+
|
| 485 |
+
# μ°½μμ± μμ± μμ
|
| 486 |
+
creative_prompt = f"""
|
| 487 |
+
μ§λ¬Έ: {query}
|
| 488 |
+
κ°λ
μꡬ쑰: {supervisor_response}
|
| 489 |
+
κ²μκ²°κ³Ό: {search_context}
|
| 490 |
+
μ°½μμ +μ€μ©μ λ΅λ³ μ¦μμμ±"""
|
| 491 |
+
|
| 492 |
+
creative_response = ""
|
| 493 |
+
creative_partial = "" # λΉνμμ© λΆλΆ μλ΅
|
| 494 |
+
critic_started = False
|
| 495 |
+
critic_response = ""
|
| 496 |
+
|
| 497 |
+
creative_task = self.llm.chat_stream_async(
|
| 498 |
+
messages=[
|
| 499 |
+
{"role": "system", "content": self.compact_prompts[AgentRole.CREATIVE]},
|
| 500 |
+
{"role": "user", "content": creative_prompt}
|
| 501 |
+
],
|
| 502 |
+
temperature=0.8,
|
| 503 |
+
max_tokens=1500
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
# μ°½μμ± μ€νΈλ¦¬λ° + λΉνμ μ‘°κΈ° μμ
|
| 507 |
+
async for chunk in self.streaming.buffer_and_yield(creative_task):
|
| 508 |
+
creative_response += chunk
|
| 509 |
+
creative_partial += chunk
|
| 510 |
+
|
| 511 |
+
# μ°½μμ± μλ΅μ΄ 500μ λμΌλ©΄ λΉνμ μμ
|
| 512 |
+
if len(creative_partial) > 500 and not critic_started:
|
| 513 |
+
critic_started = True
|
| 514 |
+
|
| 515 |
+
# λΉνμ λΉλκΈ° μμ
|
| 516 |
+
critic_prompt = f"""
|
| 517 |
+
μλ³Έμ§λ¬Έ: {query}
|
| 518 |
+
μ°½μμ±λ΅λ³(μΌλΆ): {creative_partial}
|
| 519 |
+
μ μκ²ν βκ°μ μ 3κ°"""
|
| 520 |
+
|
| 521 |
+
critic_task = asyncio.create_task(
|
| 522 |
+
self._run_critic_async(critic_prompt)
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
if show_progress:
|
| 526 |
+
display_creative = creative_response[:400] + "..." if len(creative_response) > 400 else creative_response
|
| 527 |
+
agent_thoughts = f"### π¨ μ°½μμ± μμ±μ\n{display_creative}\n\n"
|
| 528 |
+
yield accumulated_response, agent_thoughts
|
| 529 |
+
|
| 530 |
+
# λΉνμ κ²°κ³Ό λκΈ°
|
| 531 |
+
if critic_started:
|
| 532 |
+
critic_response = await critic_task
|
| 533 |
+
|
| 534 |
+
if show_progress:
|
| 535 |
+
agent_thoughts += f"### π λΉνμ κ²ν \n{critic_response[:200]}...\n\n"
|
| 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 |
+
agent_thoughts += f"### β
νμ§ μΆ©μ‘± (μ μ: {quality_score:.2f})\nμ‘°κΈ° μλ£!\n"
|
| 549 |
+
|
| 550 |
+
# μΊμ μ μ₯
|
| 551 |
+
self.cache.set(query, {
|
| 552 |
+
"response": accumulated_response,
|
| 553 |
+
"timestamp": datetime.now()
|
| 554 |
+
})
|
| 555 |
+
|
| 556 |
+
yield accumulated_response, agent_thoughts
|
| 557 |
+
return
|
| 558 |
+
|
| 559 |
+
# === 4λ¨κ³: μ΅μ’
ν΅ν© (μ€νΈλ¦¬λ°) ===
|
| 560 |
+
if show_progress:
|
| 561 |
+
agent_thoughts += "### β
μ΅μ’
ν΅ν© μ€...\n\n"
|
| 562 |
+
yield accumulated_response, agent_thoughts
|
| 563 |
+
|
| 564 |
+
final_prompt = f"""
|
| 565 |
+
μ§λ¬Έ: {query}
|
| 566 |
+
μ°½μμ±λ΅λ³: {creative_response}
|
| 567 |
+
λΉννΌλλ°±: {critic_response}
|
| 568 |
+
κ°λ
μꡬ쑰: {supervisor_response}
|
| 569 |
+
μ΅μ’
ν΅ν©βμλ²½λ΅λ³"""
|
| 570 |
+
|
| 571 |
+
final_task = self.llm.chat_stream_async(
|
| 572 |
+
messages=[
|
| 573 |
+
{"role": "system", "content": self.compact_prompts[AgentRole.FINALIZER]},
|
| 574 |
+
{"role": "user", "content": final_prompt}
|
| 575 |
+
],
|
| 576 |
+
temperature=0.5,
|
| 577 |
+
max_tokens=2500
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
# μ΅μ’
λ΅λ³ μ€νΈλ¦¬λ°
|
| 581 |
+
accumulated_response = ""
|
| 582 |
+
async for chunk in self.streaming.buffer_and_yield(final_task):
|
| 583 |
+
accumulated_response += chunk
|
| 584 |
+
yield accumulated_response, agent_thoughts
|
| 585 |
+
|
| 586 |
+
# μ²λ¦¬ μκ° μΆκ°
|
| 587 |
+
processing_time = time.time() - start_time
|
| 588 |
+
accumulated_response += f"\n\n---\nβ‘ μ²λ¦¬ μκ°: {processing_time:.1f}μ΄"
|
| 589 |
+
|
| 590 |
+
# μΊμ μ μ₯
|
| 591 |
+
self.cache.set(query, {
|
| 592 |
+
"response": accumulated_response,
|
| 593 |
+
"timestamp": datetime.now()
|
| 594 |
+
})
|
| 595 |
+
|
| 596 |
+
yield accumulated_response, agent_thoughts
|
| 597 |
+
|
| 598 |
+
except Exception as e:
|
| 599 |
+
error_msg = f"β μ€λ₯ λ°μ: {str(e)}"
|
| 600 |
+
yield error_msg, agent_thoughts
|
| 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(
|
| 607 |
+
messages=[
|
| 608 |
+
{"role": "system", "content": self.compact_prompts[AgentRole.CRITIC]},
|
| 609 |
+
{"role": "user", "content": prompt}
|
| 610 |
+
],
|
| 611 |
+
temperature=0.2,
|
| 612 |
+
max_tokens=500
|
| 613 |
+
):
|
| 614 |
+
response += chunk
|
| 615 |
+
return response
|
| 616 |
+
except:
|
| 617 |
+
return "λΉν μ²λ¦¬ μ€ μ€λ₯"
|
| 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): # μμ 3κ°λ§
|
| 626 |
+
formatted.append(f"[{i}]{r.get('title','')[:50]}:{r.get('description','')[:100]}")
|
| 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()
|
| 640 |
+
|
| 641 |
+
def process_query_optimized(
|
| 642 |
+
message: str,
|
| 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 # nest_asyncioκ° μμ΄λ μ§ν
|
| 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 |
+
search_results = run_async_function(
|
| 692 |
+
system.search.search_async(message, count=search_count)
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
if search_results:
|
| 696 |
+
search_display = "## π μ°Έκ³ μλ£\n\n"
|
| 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"
|
| 700 |
+
|
| 701 |
+
# μ¬μ©μ λ©μμ§ μΆκ°
|
| 702 |
+
current_history = history + [{"role": "user", "content": message}]
|
| 703 |
+
|
| 704 |
+
# λ³λ ¬ μ²λ¦¬ μ€νμ λκΈ°μ μΌλ‘ μμ§
|
| 705 |
+
async def collect_responses():
|
| 706 |
+
responses = []
|
| 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 |
+
responses.append((response, thoughts))
|
| 713 |
+
return responses
|
| 714 |
+
|
| 715 |
+
# λͺ¨λ μλ΅ μμ§
|
| 716 |
+
all_responses = run_async_function(collect_responses())
|
| 717 |
+
|
| 718 |
+
# μμ§λ μλ΅μ yield
|
| 719 |
+
for response, thoughts in all_responses:
|
| 720 |
+
updated_history = current_history + [
|
| 721 |
+
{"role": "assistant", "content": response}
|
| 722 |
+
]
|
| 723 |
+
yield updated_history, thoughts, search_display
|
| 724 |
+
|
| 725 |
+
except Exception as e:
|
| 726 |
+
error_history = history + [
|
| 727 |
+
{"role": "user", "content": message},
|
| 728 |
+
{"role": "assistant", "content": f"β μ€λ₯: {str(e)}"}
|
| 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 {
|
| 738 |
+
max-width: 1400px !important;
|
| 739 |
+
margin: auto !important;
|
| 740 |
+
}
|
| 741 |
+
"""
|
| 742 |
+
) as demo:
|
| 743 |
+
gr.Markdown("""
|
| 744 |
+
# β‘ κ³ μ Multi-Agent RAG System
|
| 745 |
+
### 볡μ‘ν μ§λ¬Έλ 5μ΄ μ΄λ΄ μ²λ¦¬ λͺ©ν
|
| 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("β‘ κ³ μ μ²λ¦¬", variant="primary")
|
| 770 |
+
clear = gr.Button("π μ΄κΈ°ν")
|
| 771 |
+
|
| 772 |
+
with gr.Accordion("π€ μμ΄μ νΈ μ²λ¦¬ κ³Όμ ", open=False):
|
| 773 |
+
agent_thoughts = gr.Markdown()
|
| 774 |
+
|
| 775 |
+
with gr.Accordion("π κ²μ μμ€", open=False):
|
| 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 |
+
|
| 791 |
+
search_count = gr.Slider(
|
| 792 |
+
minimum=3,
|
| 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 |
+
- μΊμ ννΈ: < 1μ΄
|
| 811 |
+
- μΌλ° μ§λ¬Έ: 3-5μ΄
|
| 812 |
+
- 볡μ‘ν μ§λ¬Έ: 5-8μ΄
|
| 813 |
+
""")
|
| 814 |
+
|
| 815 |
+
# 볡μ‘ν μ§λ¬Έ μμ
|
| 816 |
+
gr.Examples(
|
| 817 |
+
examples=[
|
| 818 |
+
"AI κΈ°μ μ΄ ν₯ν 10λ
κ° νκ΅ κ²½μ μ λ―ΈμΉ μν₯μ λ€κ°λλ‘ λΆμνκ³ λμ μ λ΅μ μ μν΄μ€",
|
| 819 |
+
"μ€ννΈμ
μ΄ λκΈ°μ
κ³Ό κ²½μνκΈ° μν νμ μ μΈ μ λ΅μ λ¨κ³λ³λ‘ μ립ν΄μ€",
|
| 820 |
+
"κΈ°νλ³ν λμμ μν μ°½μμ μΈ λΉμ¦λμ€ λͺ¨λΈ 5κ°μ§λ₯Ό ꡬ체μ μΌλ‘ μ€κ³ν΄μ€",
|
| 821 |
+
"μμμ»΄ν¨ν°κ° νμ¬ μνΈν 체κ³μ λ―ΈμΉ μν₯κ³Ό λμμ κΈ°μ μ μΌλ‘ λΆμν΄μ€",
|
| 822 |
+
"λ©νλ²μ€ μλμ κ΅μ‘ νμ λ°©μμ μ€μ ꡬν κ°λ₯ν μμ€μΌλ‘ μ μν΄μ€"
|
| 823 |
+
],
|
| 824 |
+
inputs=msg
|
| 825 |
+
)
|
| 826 |
+
|
| 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: "",
|
| 834 |
+
None,
|
| 835 |
+
msg
|
| 836 |
+
)
|
| 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: "",
|
| 844 |
+
None,
|
| 845 |
+
msg
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
clear.click(
|
| 849 |
+
lambda: ([], "", ""),
|
| 850 |
+
None,
|
| 851 |
+
[chatbot, agent_thoughts, search_sources]
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
return demo
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
# ============================================================================
|
| 858 |
+
# λ©μΈ μ€ν
|
| 859 |
+
# ============================================================================
|
| 860 |
+
|
| 861 |
+
if __name__ == "__main__":
|
| 862 |
+
print("""
|
| 863 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 864 |
+
β β‘ Speed-Optimized Multi-Agent RAG System β‘ β
|
| 865 |
+
β β
|
| 866 |
+
β 볡μ‘ν μ§λ¬Έλ 5μ΄ μ΄λ΄ μ²λ¦¬νλ κ³ μ AI μμ€ν
β
|
| 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()
|
| 886 |
+
|
| 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)
|