rag / app.py
aiqtech's picture
Update app.py
bbe1d5b verified
raw
history blame
27 kB
"""
Multi-Agent RAG-Enhanced LLM System
κ°λ…μž(Supervisor) -> μ°½μ˜μ„± μƒμ„±μž(Creative) -> λΉ„ν‰μž(Critic) -> κ°λ…μž(Final)
4단계 νŒŒμ΄ν”„λΌμΈμ„ ν†΅ν•œ κ³ ν’ˆμ§ˆ λ‹΅λ³€ 생성 μ‹œμŠ€ν…œ
"""
import os
import json
import asyncio
import time
from typing import Optional, List, Dict, Any, Tuple
from contextlib import asynccontextmanager
from datetime import datetime
from enum import Enum
import requests
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
import gradio as gr
from dotenv import load_dotenv
# ν™˜κ²½λ³€μˆ˜ λ‘œλ“œ
load_dotenv()
# ============================================================================
# 데이터 λͺ¨λΈ μ •μ˜
# ============================================================================
class AgentRole(Enum):
"""μ—μ΄μ „νŠΈ μ—­ν•  μ •μ˜"""
SUPERVISOR = "supervisor"
CREATIVE = "creative"
CRITIC = "critic"
FINALIZER = "finalizer"
class Message(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
messages: List[Message]
model: str = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
max_tokens: int = Field(default=4096, ge=1, le=8192)
temperature: float = Field(default=0.6, ge=0, le=2)
top_p: float = Field(default=1.0, ge=0, le=1)
top_k: int = Field(default=40, ge=1, le=100)
use_search: bool = Field(default=True)
class AgentResponse(BaseModel):
role: AgentRole
content: str
metadata: Optional[Dict] = None
class FinalResponse(BaseModel):
final_answer: str
agent_responses: List[AgentResponse]
search_results: Optional[List[Dict]] = None
processing_time: float
# ============================================================================
# Brave Search ν΄λΌμ΄μ–ΈνŠΈ
# ============================================================================
class BraveSearchClient:
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv("BRAVE_SEARCH_API_KEY")
if not self.api_key:
print("⚠️ Warning: Brave Search API key not found. Search disabled.")
self.base_url = "https://api.search.brave.com/res/v1/web/search"
self.headers = {
"Accept": "application/json",
"X-Subscription-Token": self.api_key
} if self.api_key else {}
def search(self, query: str, count: int = 5) -> List[Dict]:
"""μ›Ή 검색 μˆ˜ν–‰"""
if not self.api_key:
return []
params = {
"q": query,
"count": count,
"text_decorations": False,
"search_lang": "ko",
"country": "KR"
}
try:
response = requests.get(
self.base_url,
headers=self.headers,
params=params,
timeout=10
)
response.raise_for_status()
data = response.json()
results = []
if "web" in data and "results" in data["web"]:
for item in data["web"]["results"][:count]:
results.append({
"title": item.get("title", ""),
"url": item.get("url", ""),
"description": item.get("description", ""),
"age": item.get("age", "")
})
return results
except Exception as e:
print(f"Search error: {str(e)}")
return []
# ============================================================================
# Fireworks LLM ν΄λΌμ΄μ–ΈνŠΈ
# ============================================================================
class FireworksClient:
def __init__(self, api_key: Optional[str] = None):
self.api_key = api_key or os.getenv("FIREWORKS_API_KEY")
if not self.api_key:
raise ValueError("FIREWORKS_API_KEY is required!")
self.base_url = "https://api.fireworks.ai/inference/v1/chat/completions"
self.headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
def chat(self, messages: List[Dict], **kwargs) -> str:
"""LLMκ³Ό λŒ€ν™”"""
payload = {
"model": kwargs.get("model", "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"),
"messages": messages,
"max_tokens": kwargs.get("max_tokens", 4096),
"temperature": kwargs.get("temperature", 0.7),
"top_p": kwargs.get("top_p", 1.0),
"top_k": kwargs.get("top_k", 40)
}
try:
response = requests.post(
self.base_url,
headers=self.headers,
data=json.dumps(payload),
timeout=60
)
response.raise_for_status()
data = response.json()
if "choices" in data and len(data["choices"]) > 0:
return data["choices"][0]["message"]["content"]
return "응닡을 생성할 수 μ—†μŠ΅λ‹ˆλ‹€."
except Exception as e:
return f"였λ₯˜ λ°œμƒ: {str(e)}"
# ============================================================================
# λ©€ν‹° μ—μ΄μ „νŠΈ μ‹œμŠ€ν…œ
# ============================================================================
class MultiAgentSystem:
"""4단계 λ©€ν‹° μ—μ΄μ „νŠΈ 처리 μ‹œμŠ€ν…œ"""
def __init__(self, llm_client: FireworksClient, search_client: BraveSearchClient):
self.llm = llm_client
self.search = search_client
self.agent_configs = self._initialize_agent_configs()
def _initialize_agent_configs(self) -> Dict:
"""각 μ—μ΄μ „νŠΈλ³„ μ„€μ • μ΄ˆκΈ°ν™”"""
return {
AgentRole.SUPERVISOR: {
"temperature": 0.3,
"system_prompt": """당신은 κ°λ…μž μ—μ΄μ „νŠΈμž…λ‹ˆλ‹€.
μ‚¬μš©μžμ˜ 질문과 검색 κ²°κ³Όλ₯Ό λΆ„μ„ν•˜μ—¬ λ‹΅λ³€μ˜ 전체적인 λ°©ν–₯μ„±κ³Ό ꡬ쑰λ₯Ό μ œμ‹œν•΄μ•Ό ν•©λ‹ˆλ‹€.
μ—­ν• :
1. 질문의 핡심 μ˜λ„ νŒŒμ•…
2. 검색 κ²°κ³Όμ—μ„œ 핡심 정보 μΆ”μΆœ
3. 닡변이 포함해야 ν•  μ£Όμš” μš”μ†Œλ“€ μ •μ˜
4. 논리적 흐름과 ꡬ쑰 μ œμ‹œ
좜λ ₯ ν˜•μ‹:
- 질문 뢄석: [핡심 μ˜λ„]
- μ£Όμš” 포함 사항: [ν•­λͺ©λ“€]
- λ‹΅λ³€ ꡬ쑰: [논리적 흐름]
- 검색 κ²°κ³Ό ν™œμš© λ°©μ•ˆ: [μ–΄λ–€ 정보λ₯Ό μ–΄λ–»κ²Œ ν™œμš©ν• μ§€]"""
},
AgentRole.CREATIVE: {
"temperature": 0.9,
"system_prompt": """당신은 μ°½μ˜μ„± μƒμ„±μž μ—μ΄μ „νŠΈμž…λ‹ˆλ‹€.
κ°λ…μžμ˜ 지침을 λ°”νƒ•μœΌλ‘œ 창의적이고 ν₯미둜운 닡변을 생성해야 ν•©λ‹ˆλ‹€.
μ—­ν• :
1. κ°λ…μžμ˜ ꡬ쑰λ₯Ό λ”°λ₯΄λ˜ 창의적으둜 ν™•μž₯
2. μ˜ˆμ‹œ, λΉ„μœ , μŠ€ν† λ¦¬ν…”λ§ ν™œμš©
3. μ‚¬μš©μž κ΄€μ μ—μ„œ μ΄ν•΄ν•˜κΈ° μ‰¬μš΄ μ„€λͺ… μΆ”κ°€
4. μ‹€μš©μ μ΄κ³  ꡬ체적인 μ‘°μ–Έ 포함
5. 독창적인 관점과 톡찰 제곡
μ£Όμ˜μ‚¬ν•­:
- 정확성을 ν•΄μΉ˜μ§€ μ•ŠλŠ” μ„ μ—μ„œ μ°½μ˜μ„± 발휘
- 검색 κ²°κ³Όλ₯Ό 창의적으둜 μž¬κ΅¬μ„±
- μ‚¬μš©μž μ°Έμ—¬λ₯Ό μœ λ„ν•˜λŠ” λ‚΄μš© 포함"""
},
AgentRole.CRITIC: {
"temperature": 0.2,
"system_prompt": """당신은 λΉ„ν‰μž μ—μ΄μ „νŠΈμž…λ‹ˆλ‹€.
μ°½μ˜μ„± μƒμ„±μžμ˜ 닡변을 κ²€ν† ν•˜κ³  κ°œμ„ μ μ„ μ œμ‹œν•΄μ•Ό ν•©λ‹ˆλ‹€.
μ—­ν• :
1. 사싀 관계 검증
2. 논리적 일관성 확인
3. μ˜€ν•΄μ˜ μ†Œμ§€κ°€ μžˆλŠ” ν‘œν˜„ 지적
4. λˆ„λ½λœ μ€‘μš” 정보 확인
5. κ°œμ„  λ°©ν–₯ ꡬ체적 μ œμ‹œ
평가 κΈ°μ€€:
- μ •ν™•μ„±: 사싀과 λ°μ΄ν„°μ˜ μ •ν™•μ„±
- μ™„μ „μ„±: μ§ˆλ¬Έμ— λŒ€ν•œ μΆ©λΆ„ν•œ λ‹΅λ³€ μ—¬λΆ€
- λͺ…ν™•μ„±: μ΄ν•΄ν•˜κΈ° μ‰¬μš΄ μ„€λͺ…인지
- μœ μš©μ„±: μ‹€μ œλ‘œ 도움이 λ˜λŠ” 정보인지
- μ‹ λ’°μ„±: 검증 κ°€λŠ₯ν•œ 좜처 포함 μ—¬λΆ€
좜λ ₯ ν˜•μ‹:
βœ… 긍정적 μΈ‘λ©΄: [잘된 점듀]
⚠️ κ°œμ„  ν•„μš”: [문제점과 κ°œμ„  λ°©μ•ˆ]
πŸ’‘ μΆ”κ°€ μ œμ•ˆ: [보완할 λ‚΄μš©]"""
},
AgentRole.FINALIZER: {
"temperature": 0.5,
"system_prompt": """당신은 μ΅œμ’… κ°λ…μžμž…λ‹ˆλ‹€.
λͺ¨λ“  μ—μ΄μ „νŠΈμ˜ μ˜κ²¬μ„ μ’…ν•©ν•˜μ—¬ μ΅œμ’… 닡변을 생성해야 ν•©λ‹ˆλ‹€.
μ—­ν• :
1. μ°½μ˜μ„± μƒμ„±μžμ˜ 닡변을 기반으둜
2. λΉ„ν‰μžμ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬
3. κ°λ…μžμ˜ 초기 ꡬ쑰λ₯Ό μœ μ§€ν•˜λ©°
4. 논리적이고 μ΄ν•΄ν•˜κΈ° μ‰¬μš΄ μ΅œμ’… λ‹΅λ³€ 생성
μ΅œμ’… λ‹΅λ³€ κΈ°μ€€:
- μ •ν™•μ„±κ³Ό μ°½μ˜μ„±μ˜ κ· ν˜•
- λͺ…ν™•ν•œ ꡬ쑰와 논리적 흐름
- μ‹€μš©μ μ΄κ³  μœ μš©ν•œ 정보
- μ‚¬μš©μž μΉœν™”μ μΈ 톀
- 검색 κ²°κ³Ό 좜처 λͺ…μ‹œ
λ°˜λ“œμ‹œ 포함할 μš”μ†Œ:
1. 핡심 λ‹΅λ³€ (직접적인 응닡)
2. 상세 μ„€λͺ… (λ°°κ²½κ³Ό λ§₯락)
3. μ‹€μš©μ  μ‘°μ–Έ (ν•΄λ‹Ή μ‹œ)
4. μ°Έκ³  자료 (검색 κ²°κ³Ό 기반)"""
}
}
def _format_search_results(self, results: List[Dict]) -> str:
"""검색 κ²°κ³Ό ν¬λ§·νŒ…"""
if not results:
return "검색 κ²°κ³Ό μ—†μŒ"
formatted = []
for i, result in enumerate(results, 1):
formatted.append(f"""
[검색결과 {i}]
제λͺ©: {result.get('title', 'N/A')}
URL: {result.get('url', 'N/A')}
λ‚΄μš©: {result.get('description', 'N/A')}
κ²Œμ‹œ: {result.get('age', 'N/A')}""")
return "\n".join(formatted)
async def process_with_agents(
self,
query: str,
search_results: List[Dict],
config: Dict
) -> FinalResponse:
"""λ©€ν‹° μ—μ΄μ „νŠΈ νŒŒμ΄ν”„λΌμΈ μ‹€ν–‰"""
start_time = time.time()
agent_responses = []
search_context = self._format_search_results(search_results)
# 1단계: κ°λ…μž - λ°©ν–₯μ„± μ œμ‹œ
supervisor_prompt = f"""
μ‚¬μš©μž 질문: {query}
검색 κ²°κ³Ό:
{search_context}
μœ„ 정보λ₯Ό λ°”νƒ•μœΌλ‘œ λ‹΅λ³€μ˜ λ°©ν–₯μ„±κ³Ό ꡬ쑰λ₯Ό μ œμ‹œν•˜μ„Έμš”."""
supervisor_response = self.llm.chat(
messages=[
{"role": "system", "content": self.agent_configs[AgentRole.SUPERVISOR]["system_prompt"]},
{"role": "user", "content": supervisor_prompt}
],
temperature=self.agent_configs[AgentRole.SUPERVISOR]["temperature"],
max_tokens=config.get("max_tokens", 1000)
)
agent_responses.append(AgentResponse(
role=AgentRole.SUPERVISOR,
content=supervisor_response
))
# 2단계: μ°½μ˜μ„± μƒμ„±μž - 창의적 λ‹΅λ³€ 생성
creative_prompt = f"""
μ‚¬μš©μž 질문: {query}
κ°λ…μž μ§€μΉ¨:
{supervisor_response}
검색 κ²°κ³Ό:
{search_context}
μœ„ μ§€μΉ¨κ³Ό 정보λ₯Ό λ°”νƒ•μœΌλ‘œ 창의적이고 μœ μš©ν•œ 닡변을 μƒμ„±ν•˜μ„Έμš”."""
creative_response = self.llm.chat(
messages=[
{"role": "system", "content": self.agent_configs[AgentRole.CREATIVE]["system_prompt"]},
{"role": "user", "content": creative_prompt}
],
temperature=self.agent_configs[AgentRole.CREATIVE]["temperature"],
max_tokens=config.get("max_tokens", 2000)
)
agent_responses.append(AgentResponse(
role=AgentRole.CREATIVE,
content=creative_response
))
# 3단계: λΉ„ν‰μž - κ²€ν†  및 κ°œμ„ μ  μ œμ‹œ
critic_prompt = f"""
원본 질문: {query}
μ°½μ˜μ„± μƒμ„±μžμ˜ λ‹΅λ³€:
{creative_response}
검색 κ²°κ³Ό:
{search_context}
μœ„ 닡변을 κ²€ν† ν•˜κ³  κ°œμ„ μ μ„ μ œμ‹œν•˜μ„Έμš”."""
critic_response = self.llm.chat(
messages=[
{"role": "system", "content": self.agent_configs[AgentRole.CRITIC]["system_prompt"]},
{"role": "user", "content": critic_prompt}
],
temperature=self.agent_configs[AgentRole.CRITIC]["temperature"],
max_tokens=config.get("max_tokens", 1000)
)
agent_responses.append(AgentResponse(
role=AgentRole.CRITIC,
content=critic_response
))
# 4단계: μ΅œμ’… κ°λ…μž - μ’…ν•© 및 μ΅œμ’… λ‹΅λ³€
final_prompt = f"""
μ‚¬μš©μž 질문: {query}
μ°½μ˜μ„± μƒμ„±μžμ˜ λ‹΅λ³€:
{creative_response}
λΉ„ν‰μžμ˜ ν”Όλ“œλ°±:
{critic_response}
초기 κ°λ…μž μ§€μΉ¨:
{supervisor_response}
검색 κ²°κ³Ό:
{search_context}
λͺ¨λ“  μ˜κ²¬μ„ μ’…ν•©ν•˜μ—¬ μ΅œμ’… 닡변을 μƒμ„±ν•˜μ„Έμš”.
λΉ„ν‰μžμ˜ ν”Όλ“œλ°±μ„ λ°˜μ˜ν•˜μ—¬ κ°œμ„ λœ 버전을 λ§Œλ“€μ–΄μ£Όμ„Έμš”."""
final_response = self.llm.chat(
messages=[
{"role": "system", "content": self.agent_configs[AgentRole.FINALIZER]["system_prompt"]},
{"role": "user", "content": final_prompt}
],
temperature=self.agent_configs[AgentRole.FINALIZER]["temperature"],
max_tokens=config.get("max_tokens", 3000)
)
agent_responses.append(AgentResponse(
role=AgentRole.FINALIZER,
content=final_response
))
processing_time = time.time() - start_time
return FinalResponse(
final_answer=final_response,
agent_responses=agent_responses,
search_results=search_results,
processing_time=processing_time
)
# ============================================================================
# Gradio UI
# ============================================================================
def create_gradio_interface(multi_agent_system: MultiAgentSystem, search_client: BraveSearchClient):
"""Gradio μΈν„°νŽ˜μ΄μŠ€ 생성"""
async def process_query(
message: str,
history: List[List[str]],
use_search: bool,
show_agent_thoughts: bool,
search_count: int,
temperature: float,
max_tokens: int
):
"""쿼리 처리 ν•¨μˆ˜"""
if not message:
return "", history, "", ""
try:
# 검색 μˆ˜ν–‰
search_results = []
if use_search and search_client.api_key:
search_results = search_client.search(message, count=search_count)
# μ„€μ •
config = {
"temperature": temperature,
"max_tokens": max_tokens
}
# λ©€ν‹° μ—μ΄μ „νŠΈ 처리
response = await multi_agent_system.process_with_agents(
query=message,
search_results=search_results,
config=config
)
# μ—μ΄μ „νŠΈ 사고 κ³Όμ • ν¬λ§·νŒ…
agent_thoughts = ""
if show_agent_thoughts:
agent_thoughts = "## πŸ€– μ—μ΄μ „νŠΈ 사고 κ³Όμ •\n\n"
for agent_resp in response.agent_responses:
role_emoji = {
AgentRole.SUPERVISOR: "πŸ‘”",
AgentRole.CREATIVE: "🎨",
AgentRole.CRITIC: "πŸ”",
AgentRole.FINALIZER: "βœ…"
}
role_name = {
AgentRole.SUPERVISOR: "κ°λ…μž (초기 ꡬ쑰화)",
AgentRole.CREATIVE: "μ°½μ˜μ„± μƒμ„±μž",
AgentRole.CRITIC: "λΉ„ν‰μž",
AgentRole.FINALIZER: "μ΅œμ’… κ°λ…μž"
}
agent_thoughts += f"### {role_emoji[agent_resp.role]} {role_name[agent_resp.role]}\n"
agent_thoughts += f"{agent_resp.content[:500]}...\n\n"
# 검색 κ²°κ³Ό ν¬λ§·νŒ…
search_display = ""
if search_results:
search_display = "## πŸ“š μ°Έκ³  자료\n\n"
for i, result in enumerate(search_results, 1):
search_display += f"**{i}. [{result['title']}]({result['url']})**\n"
search_display += f" {result['description'][:100]}...\n\n"
# 처리 μ‹œκ°„ μΆ”κ°€
final_answer = response.final_answer
final_answer += f"\n\n---\n⏱️ *처리 μ‹œκ°„: {response.processing_time:.2f}초*"
# νžˆμŠ€ν† λ¦¬ μ—…λ°μ΄νŠΈ
history.append([message, final_answer])
return "", history, agent_thoughts, search_display
except Exception as e:
error_msg = f"❌ 였λ₯˜ λ°œμƒ: {str(e)}"
history.append([message, error_msg])
return "", history, "", ""
# Gradio μΈν„°νŽ˜μ΄μŠ€
with gr.Blocks(
title="Multi-Agent RAG System",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1400px !important;
margin: auto !important;
}
#chatbot {
height: 600px !important;
}
"""
) as demo:
gr.Markdown("""
# 🧠 Multi-Agent RAG System
### 4단계 μ—μ΄μ „νŠΈ ν˜‘μ—…μ„ ν†΅ν•œ κ³ ν’ˆμ§ˆ λ‹΅λ³€ 생성
**처리 κ³Όμ •:** κ°λ…μž(ꡬ쑰화) β†’ μ°½μ˜μ„± μƒμ„±μž(창의적 λ‹΅λ³€) β†’ λΉ„ν‰μž(검증) β†’ μ΅œμ’… κ°λ…μž(μ’…ν•©)
""")
with gr.Row():
# 메인 μ±„νŒ… μ˜μ—­
with gr.Column(scale=3):
chatbot = gr.Chatbot(
height=500,
label="πŸ’¬ λŒ€ν™”",
elem_id="chatbot"
)
msg = gr.Textbox(
label="질문 μž…λ ₯",
placeholder="μ§ˆλ¬Έμ„ μž…λ ₯ν•˜μ„Έμš”... (λ©€ν‹° μ—μ΄μ „νŠΈκ°€ ν˜‘μ—…ν•˜μ—¬ λ‹΅λ³€ν•©λ‹ˆλ‹€)",
lines=3
)
with gr.Row():
submit = gr.Button("πŸš€ 전솑", variant="primary")
clear = gr.Button("πŸ”„ μ΄ˆκΈ°ν™”")
# μ—μ΄μ „νŠΈ 사고 κ³Όμ •
with gr.Accordion("πŸ€– μ—μ΄μ „νŠΈ 사고 κ³Όμ •", open=False):
agent_thoughts = gr.Markdown()
# 검색 κ²°κ³Ό
with gr.Accordion("πŸ“š 검색 μ†ŒμŠ€", open=False):
search_sources = gr.Markdown()
# μ„€μ • νŒ¨λ„
with gr.Column(scale=1):
gr.Markdown("### βš™οΈ μ„€μ •")
with gr.Group():
use_search = gr.Checkbox(
label="πŸ” μ›Ή 검색 μ‚¬μš©",
value=True
)
show_agent_thoughts = gr.Checkbox(
label="🧠 μ—μ΄μ „νŠΈ 사고과정 ν‘œμ‹œ",
value=True
)
search_count = gr.Slider(
minimum=1,
maximum=10,
value=5,
step=1,
label="검색 κ²°κ³Ό 수"
)
temperature = gr.Slider(
minimum=0,
maximum=1,
value=0.6,
step=0.1,
label="Temperature"
)
max_tokens = gr.Slider(
minimum=500,
maximum=4000,
value=2000,
step=100,
label="Max Tokens"
)
gr.Markdown("""
### πŸ“Š μ‹œμŠ€ν…œ 정보
**μ—μ΄μ „νŠΈ μ—­ν• :**
- πŸ‘” **κ°λ…μž**: ꡬ쑰 섀계
- 🎨 **μ°½μ˜μ„±**: 창의적 생성
- πŸ” **λΉ„ν‰μž**: 검증/κ°œμ„ 
- βœ… **μ΅œμ’…**: μ’…ν•©/μ™„μ„±
""")
# 예제
gr.Examples(
examples=[
"μ–‘μž μ»΄ν“¨ν„°μ˜ 원리λ₯Ό μ΄ˆλ“±ν•™μƒλ„ 이해할 수 있게 μ„€λͺ…ν•΄μ€˜",
"2024λ…„ AI 기술 νŠΈλ Œλ“œμ™€ 미래 전망은?",
"효과적인 ν”„λ‘œκ·Έλž˜λ° ν•™μŠ΅ 방법을 λ‹¨κ³„λ³„λ‘œ μ•Œλ €μ€˜",
"κΈ°ν›„ λ³€ν™”κ°€ ν•œκ΅­ κ²½μ œμ— λ―ΈμΉ˜λŠ” 영ν–₯ λΆ„μ„ν•΄μ€˜",
"μŠ€νƒ€νŠΈμ—… μ°½μ—… μ‹œ κ³ λ €ν•΄μ•Ό ν•  핡심 μš”μ†Œλ“€μ€?"
],
inputs=msg
)
# 이벀트 바인딩
submit.click(
process_query,
inputs=[msg, chatbot, use_search, show_agent_thoughts,
search_count, temperature, max_tokens],
outputs=[msg, chatbot, agent_thoughts, search_sources]
)
msg.submit(
process_query,
inputs=[msg, chatbot, use_search, show_agent_thoughts,
search_count, temperature, max_tokens],
outputs=[msg, chatbot, agent_thoughts, search_sources]
)
clear.click(
lambda: (None, None, None),
None,
[chatbot, agent_thoughts, search_sources]
)
return demo
# ============================================================================
# FastAPI μ•±
# ============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""μ•± 생λͺ…μ£ΌκΈ° 관리"""
print("\n" + "="*60)
print("πŸš€ Multi-Agent RAG System Starting...")
print("="*60)
yield
print("\nπŸ‘‹ Shutting down...")
app = FastAPI(
title="Multi-Agent RAG System API",
description="4-Stage Agent Collaboration System with RAG",
version="3.0.0",
lifespan=lifespan
)
# CORS μ„€μ •
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
# ν΄λΌμ΄μ–ΈνŠΈ μ΄ˆκΈ°ν™”
try:
llm_client = FireworksClient()
search_client = BraveSearchClient()
multi_agent_system = MultiAgentSystem(llm_client, search_client)
except Exception as e:
print(f"⚠️ Initialization error: {e}")
llm_client = None
search_client = None
multi_agent_system = None
# API μ—”λ“œν¬μΈνŠΈ
@app.get("/")
async def root():
"""루트 μ—”λ“œν¬μΈνŠΈ"""
return {
"name": "Multi-Agent RAG System",
"version": "3.0.0",
"status": "running",
"ui": "http://localhost:8000/ui",
"docs": "http://localhost:8000/docs"
}
@app.post("/api/chat")
async def chat_endpoint(request: ChatRequest):
"""λ©€ν‹° μ—μ΄μ „νŠΈ μ±„νŒ… API"""
if not multi_agent_system:
raise HTTPException(status_code=500, detail="System not initialized")
try:
# 검색 μˆ˜ν–‰
search_results = []
if request.use_search and search_client.api_key:
last_message = request.messages[-1].content if request.messages else ""
search_results = search_client.search(last_message, count=5)
# λ©€ν‹° μ—μ΄μ „νŠΈ 처리
response = await multi_agent_system.process_with_agents(
query=request.messages[-1].content,
search_results=search_results,
config={
"temperature": request.temperature,
"max_tokens": request.max_tokens
}
)
return response
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/health")
async def health_check():
"""ν—¬μŠ€ 체크"""
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"services": {
"llm": "ready" if llm_client else "not configured",
"search": "ready" if search_client and search_client.api_key else "not configured",
"multi_agent": "ready" if multi_agent_system else "not configured"
}
}
# Gradio 마운트
if multi_agent_system:
gradio_app = create_gradio_interface(multi_agent_system, search_client)
app = gr.mount_gradio_app(app, gradio_app, path="/ui")
# ============================================================================
# 메인 μ‹€ν–‰
# ============================================================================
if __name__ == "__main__":
print("""
╔══════════════════════════════════════════════════════════════╗
β•‘ 🧠 Multi-Agent RAG-Enhanced LLM System 🧠 β•‘
β•‘ β•‘
β•‘ κ°λ…μž β†’ μ°½μ˜μ„± μƒμ„±μž β†’ λΉ„ν‰μž β†’ μ΅œμ’… κ°λ…μž β•‘
β•‘ 4단계 ν˜‘μ—…μ„ ν†΅ν•œ κ³ ν’ˆμ§ˆ λ‹΅λ³€ 생성 β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
""")
# API ν‚€ 확인
if not os.getenv("FIREWORKS_API_KEY"):
print("\n⚠️ FIREWORKS_API_KEYκ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
key = input("Fireworks API Key μž…λ ₯: ").strip()
if key:
os.environ["FIREWORKS_API_KEY"] = key
llm_client = FireworksClient(key)
if not os.getenv("BRAVE_SEARCH_API_KEY"):
print("\n⚠️ BRAVE_SEARCH_API_KEYκ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.")
print(" (선택사항: 검색 κΈ°λŠ₯을 μ‚¬μš©ν•˜λ €λ©΄ μž…λ ₯)")
key = input("Brave Search API Key μž…λ ₯ (Enter=κ±΄λ„ˆλ›°κΈ°): ").strip()
if key:
os.environ["BRAVE_SEARCH_API_KEY"] = key
search_client = BraveSearchClient(key)
# μ‹œμŠ€ν…œ μž¬μ΄ˆκΈ°ν™”
if llm_client:
multi_agent_system = MultiAgentSystem(llm_client, search_client)
gradio_app = create_gradio_interface(multi_agent_system, search_client)
app = gr.mount_gradio_app(app, gradio_app, path="/ui")
print("\n" + "="*60)
print("βœ… μ‹œμŠ€ν…œ μ€€λΉ„ μ™„λ£Œ!")
print("="*60)
print("\nπŸ“ 접속 μ£Όμ†Œ:")
print(" 🎨 Gradio UI: http://localhost:8000/ui")
print(" πŸ“š API Docs: http://localhost:8000/docs")
print(" πŸ”§ Chat API: POST http://localhost:8000/api/chat")
print("\nπŸ’‘ Ctrl+Cλ₯Ό 눌러 μ’…λ£Œ")
print("="*60 + "\n")
uvicorn.run(
app,
host="0.0.0.0",
port=8000,
reload=False,
log_level="info"
)