File size: 7,523 Bytes
d8a3c6f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
"""
๋ชจ๋ฐ์ผ ๋ฆฌ์กํธ ํ๋ฐํธ์์ ํธ์ถํ REST API ์๋ฒ (FastAPI)
์๋ํฌ์ธํธ:
- POST /api/advise : ์ข
ํฉ ์๋ด (๊ธ์ต+์ ๋ณด+๋ณต์ง)
- POST /api/qa : ์์ ์ง๋ฌธ/์ฑ๋ด ์๋ต
- GET /api/welfare/search : ๋ณต์ง์ ์ฑ
๊ฒ์
- GET /api/products/search : ๊ธ์ต์ํ RAG ๊ฒ์
- GET /health : ์ํ ์ ๊ฒ
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any
from agents.multi_agent_system import get_meeting_account_advisor
from agents.welfare_advisor import WelfareAdvisor
from agents.universal_info_advisor import get_universal_info_advisor
from models.rag_system import get_kb_rag
import pandas as pd
import uvicorn
app = FastAPI(title="KB ๊ธ์ต AI Advisor API", version="1.0.0")
# CORS (๋ฆฌ์กํธ/๋ชจ๋ฐ์ผ ์น์์ ํธ์ถ ํ์ฉ)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ํ๋ฐํธ์๋ ์ ์ ํ์ผ ์ ๊ณต (frontend/dist๊ฐ ์์ผ๋ฉด ์๋ ์๋น)
try:
import os
FRONT_DIST = os.path.join(os.path.dirname(__file__), "frontend", "dist")
if os.path.isdir(FRONT_DIST):
app.mount("/", StaticFiles(directory=FRONT_DIST, html=True), name="frontend")
except Exception:
pass
class UserInfo(BaseModel):
age_group: Optional[str] = None
family_type: Optional[str] = None
income_level: Optional[str] = None
region: Optional[str] = None
class AdviseRequest(BaseModel):
purpose: str = Field(..., description="์: ์คํ์ธ ์ดํ์ฐ์, ๊ฒฐํผ์ค๋น ๋ฑ")
duration_months: int = Field(..., ge=1, le=120)
target_amount: int = Field(..., ge=1)
detailed_purpose: Optional[str] = None
current_amount: Optional[int] = 0
user_info: Optional[UserInfo] = None
class AdviseResponse(BaseModel):
purpose_category: Optional[str]
financial_recommendation: Optional[str]
detailed_info: Optional[str]
welfare_recommendation: Optional[str]
comprehensive_advice: Optional[str]
progress_info: Optional[str] = None
class QARequest(BaseModel):
question: str
detailed_context: Optional[str] = None
class QAResponse(BaseModel):
answer: str
category: Optional[str] = None
@app.get("/health")
def health() -> Dict[str, Any]:
return {"status": "ok"}
@app.post("/api/advise", response_model=AdviseResponse)
def api_advise(req: AdviseRequest):
try:
advisor = get_meeting_account_advisor()
results = advisor.get_comprehensive_advice(
purpose=req.purpose,
duration_months=req.duration_months,
target_amount=req.target_amount,
detailed_purpose=req.detailed_purpose,
)
# ์งํ ํํฉ (current_amount ์ ๊ณต ์)
progress_info = None
if req.current_amount and req.current_amount > 0:
progress_info = advisor.get_savings_progress_tracking(
req.purpose,
req.duration_months,
req.target_amount,
req.current_amount,
)
# WelfareAdvisor์ ์ฌ์ฉ์ ์ ๋ณด ์ ๋ฌ์ด ํ์ํ ๊ฒฝ์ฐ๋ฅผ ์ํด ๋ณด์กฐ ํธ์ถ (์ ํ)
welfare_text = results.get("welfare_recommendation")
if (not welfare_text or "์์ต๋๋ค" in welfare_text) and req.user_info:
welfare = WelfareAdvisor().get_welfare_recommendations(
req.purpose, req.user_info.model_dump()
)
if welfare:
results["welfare_recommendation"] = welfare
return AdviseResponse(
purpose_category=results.get("purpose_category"),
financial_recommendation=results.get("financial_recommendation"),
detailed_info=results.get("detailed_info"),
welfare_recommendation=results.get("welfare_recommendation"),
comprehensive_advice=results.get("comprehensive_advice"),
progress_info=progress_info,
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/qa", response_model=QAResponse)
def api_qa(req: QARequest):
try:
advisor = get_universal_info_advisor()
info = advisor.get_comprehensive_info(
purpose=req.question,
detailed_purpose=req.detailed_context,
)
return QAResponse(
answer=info.get("comprehensive_info", "๋ต๋ณ์ ์์ฑํ์ง ๋ชปํ์ต๋๋ค."),
category=info.get("category"),
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/welfare/search")
def api_welfare_search(
keyword: Optional[str] = Query(None, description="์ ์ฑ
๋ช
/๋ด์ฉ/๋์ ๊ฒ์์ด"),
region: Optional[str] = Query(None, description="์ง์ญ๋ช
(์: ์์ธ, ๋ถ์ฐ)"),
page: int = Query(1, ge=1),
size: int = Query(10, ge=1, le=100),
):
try:
wa = WelfareAdvisor()
df = wa.welfare_data
if df.empty:
return {"total": 0, "items": []}
filtered = df.copy()
if keyword:
kw = keyword.strip()
mask = (
filtered["policy_name"].fillna("").str.contains(kw, case=False)
| filtered["service_content_detail"].fillna("").str.contains(kw, case=False)
| filtered["target_audience_description"].fillna("").str.contains(kw, case=False)
)
filtered = filtered[mask]
if region and region != "์ ์ฒด":
filtered = filtered[
(filtered["region_name"].fillna("").str.contains(region, case=False))
| (filtered["region_name"] == "์ ๊ตญ")
]
total = len(filtered)
start = (page - 1) * size
end = start + size
page_df = filtered.iloc[start:end]
items = []
for _, row in page_df.iterrows():
items.append(
{
"policy_name": row.get("policy_name", ""),
"governing_body": row.get("governing_body_name", ""),
"target_audience": row.get("target_audience_description", ""),
"service_content": row.get("service_content_detail", ""),
"region": row.get("region_name", "์ ๊ตญ"),
"application_link": row.get("application_link", ""),
"last_updated": row.get("last_updated", ""),
"tags": row.get("target_audience_tags", ""),
}
)
return {"total": total, "items": items}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/products/search")
def api_products_search(q: str = Query(..., description="๊ฒ์ ์ง์"), k: int = Query(5, ge=1, le=20)):
try:
rag = get_kb_rag()
results = rag.search_products(q, k=k) or []
return {"items": results}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run("api_server:app", host="0.0.0.0", port=8000, reload=True)
|