""" ๐ŸŒพ Mulberry ํ˜‘์ƒ ์—”์ง„ - FastAPI Production Version ์‹คํ–‰ ๊ฐ€๋Šฅํ•œ REST API ์„œ๋ฒ„ Endpoints: - POST /api/negotiate - ๊ฐ€๊ฒฉ ํ˜‘์ƒ - POST /api/agent/create - ์—์ด์ „ํŠธ ์ƒ์„ฑ - GET /api/agent/{id} - ์—์ด์ „ํŠธ ์กฐํšŒ - GET /api/transactions - ๊ฑฐ๋ž˜ ๋‚ด์—ญ - GET /api/stats - ํ†ต๊ณ„ """ from fastapi import FastAPI, HTTPException, Depends, Header from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel, Field from typing import Optional, List, Dict, Any from datetime import datetime import os from dotenv import load_dotenv # ๋‚ด๋ถ€ ๋ชจ๋“ˆ from agent_passport import AgentPassport from negotiation_engine import NegotiationEngine from data.inje_data import get_items, get_households, get_agent_profile # MongoDB (optional - ๋‚˜์ค‘์— ์ถ”๊ฐ€) try: from pymongo import MongoClient MONGO_AVAILABLE = True except ImportError: MONGO_AVAILABLE = False load_dotenv() # FastAPI ์•ฑ ์ƒ์„ฑ app = FastAPI( title="Mulberry Negotiation Engine API", description="AI-powered price negotiation system for food desert solutions", version="2.0.0" ) # CORS ์„ค์ • app.add_middleware( CORSMiddleware, allow_origins=["*"], # Production์—์„œ๋Š” ํŠน์ • ๋„๋ฉ”์ธ์œผ๋กœ ์ œํ•œ allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ํ˜‘์ƒ ์—”์ง„ ์ธ์Šคํ„ด์Šค engine = NegotiationEngine() # MongoDB ์—ฐ๊ฒฐ (optional) mongo_client = None db = None if MONGO_AVAILABLE: MONGODB_URI = os.getenv('MONGODB_URI') if MONGODB_URI: try: mongo_client = MongoClient(MONGODB_URI) db = mongo_client['mulberry_negotiation'] print("โœ… MongoDB connected") except Exception as e: print(f"โš ๏ธ MongoDB connection failed: {e}") # API Key ์ธ์ฆ API_KEY = os.getenv('API_KEY', 'mulberry-demo-key-2026') def verify_api_key(x_api_key: str = Header(None)): """API Key ๊ฒ€์ฆ""" if x_api_key != API_KEY: raise HTTPException(status_code=401, detail="Invalid API Key") return x_api_key # ==================== Pydantic Models ==================== class AgentCreate(BaseModel): """์—์ด์ „ํŠธ ์ƒ์„ฑ ์š”์ฒญ""" agent_name: str = Field(..., description="์—์ด์ „ํŠธ ์ด๋ฆ„") initial_region: str = Field(..., description="์ดˆ๊ธฐ ์ง€์—ญ") task_type: str = Field(..., description="์ž‘์—… ์œ ํ˜•") spirit_score: float = Field(3.0, ge=0, le=5, description="Spirit Score (0-5)") rapport_level: float = Field(0.5, ge=0, le=1, description="Rapport Level (0-1)") class NegotiateRequest(BaseModel): """ํ˜‘์ƒ ์š”์ฒญ""" item_name: str = Field(..., description="ํ’ˆ๋ชฉ๋ช…") base_price: int = Field(..., gt=0, description="๊ธฐ๋ณธ ๊ฐ€๊ฒฉ") current_quantity: int = Field(..., gt=0, description="ํ˜„์žฌ ์ˆ˜๋Ÿ‰") target_goal: int = Field(..., gt=0, description="๋ชฉํ‘œ ์ˆ˜๋Ÿ‰") demand_agent_id: Optional[str] = Field(None, description="์ˆ˜์š” ์—์ด์ „ํŠธ ID") supply_agent_id: Optional[str] = Field(None, description="๊ณต๊ธ‰ ์—์ด์ „ํŠธ ID") class NegotiateResponse(BaseModel): """ํ˜‘์ƒ ์‘๋‹ต""" success: bool negotiated_price: int original_price: int discount_amount: int discount_rate: float total_savings: int mulberry_revenue: float community_share: float net_benefit: float details: Dict[str, Any] transaction_id: str timestamp: str # ==================== API Endpoints ==================== @app.get("/") async def root(): """API ์ •๋ณด""" return { "name": "Mulberry Negotiation Engine API", "version": "2.0.0", "status": "operational", "description": "AI-powered price negotiation for food desert solutions", "endpoints": { "negotiate": "POST /api/negotiate", "create_agent": "POST /api/agent/create", "get_agent": "GET /api/agent/{agent_id}", "transactions": "GET /api/transactions", "stats": "GET /api/stats" }, "documentation": "/docs" } @app.get("/health") async def health_check(): """ํ—ฌ์Šค ์ฒดํฌ""" return { "status": "healthy", "timestamp": datetime.now().isoformat(), "mongodb": "connected" if db is not None else "not_connected", "engine": "operational" } @app.post("/api/negotiate", response_model=NegotiateResponse) async def negotiate( request: NegotiateRequest, api_key: str = Depends(verify_api_key) ): """ ๊ฐ€๊ฒฉ ํ˜‘์ƒ API Spirit Score ๊ธฐ๋ฐ˜์œผ๋กœ ์ž๋™ ํ˜‘์ƒํ•˜์—ฌ ์ตœ์  ๊ฐ€๊ฒฉ ๊ฒฐ์ • """ try: # ์—์ด์ „ํŠธ ์ƒ์„ฑ (๊ธฐ๋ณธ ํ”„๋กœํ•„ ์‚ฌ์šฉ) demand_profile = get_agent_profile('demand_agent') demand_agent = AgentPassport( agent_name=demand_profile['agent_name'], initial_region=demand_profile['initial_region'], task_type=demand_profile['task_type'] ) demand_agent.self_status_info['spirit_score'] = demand_profile['spirit_score'] demand_agent.update_rapport(demand_profile['rapport_level']) # ๊ณต๊ธ‰ ์—์ด์ „ํŠธ (ํ’ˆ๋ชฉ์— ๋”ฐ๋ผ ์„ ํƒ) if '์‚ฌ๊ณผ' in request.item_name: supply_profile = get_agent_profile('agent_inje_apple') elif 'ํ™ฉํƒœ' in request.item_name: supply_profile = get_agent_profile('agent_inje_hwangtae') elif '๊ฐ์ž' in request.item_name: supply_profile = get_agent_profile('agent_inje_potato') else: supply_profile = get_agent_profile('agent_inje_apple') # ๊ธฐ๋ณธ๊ฐ’ supply_agent = AgentPassport( agent_name=supply_profile['agent_name'], initial_region=supply_profile['initial_region'], task_type=supply_profile['task_type'] ) supply_agent.self_status_info['spirit_score'] = supply_profile['spirit_score'] supply_agent.update_rapport(supply_profile.get('rapport_level', 0.7)) # ํ˜‘์ƒ ์‹คํ–‰ negotiated_price, details = engine.negotiate_price( base_price=request.base_price, current_quantity=request.current_quantity, target_goal=request.target_goal, demand_agent=demand_agent, supply_agent=supply_agent ) # ๊ฒฝ์ œ์  ์ž„ํŒฉํŠธ ๊ณ„์‚ฐ discount_amount = request.base_price - negotiated_price discount_rate = (discount_amount / request.base_price) * 100 total_savings = discount_amount * request.current_quantity mulberry_revenue = total_savings * 0.03 community_share = total_savings * 0.10 net_benefit = total_savings - mulberry_revenue # ๊ฑฐ๋ž˜ ID ์ƒ์„ฑ transaction_id = f"TX_{datetime.now().strftime('%Y%m%d%H%M%S')}" # MongoDB์— ์ €์žฅ (์žˆ์œผ๋ฉด) if db is not None: try: db.transactions.insert_one({ 'transaction_id': transaction_id, 'item_name': request.item_name, 'base_price': request.base_price, 'negotiated_price': negotiated_price, 'quantity': request.current_quantity, 'total_savings': total_savings, 'demand_agent': demand_agent.passport_id, 'supply_agent': supply_agent.passport_id, 'timestamp': datetime.now(), 'details': details }) except Exception as e: print(f"MongoDB save error: {e}") return NegotiateResponse( success=True, negotiated_price=negotiated_price, original_price=request.base_price, discount_amount=discount_amount, discount_rate=round(discount_rate, 2), total_savings=total_savings, mulberry_revenue=round(mulberry_revenue, 2), community_share=round(community_share, 2), net_benefit=round(net_benefit, 2), details=details, transaction_id=transaction_id, timestamp=datetime.now().isoformat() ) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/api/agent/create") async def create_agent( agent: AgentCreate, api_key: str = Depends(verify_api_key) ): """์—์ด์ „ํŠธ ์ƒ์„ฑ""" try: new_agent = AgentPassport( agent_name=agent.agent_name, initial_region=agent.initial_region, task_type=agent.task_type ) new_agent.self_status_info['spirit_score'] = agent.spirit_score new_agent.update_rapport(agent.rapport_level) # MongoDB์— ์ €์žฅ (์žˆ์œผ๋ฉด) if db is not None: try: db.agents.insert_one({ 'agent_id': new_agent.passport_id, 'agent_name': agent.agent_name, 'region': agent.initial_region, 'task_type': agent.task_type, 'spirit_score': agent.spirit_score, 'rapport_level': agent.rapport_level, 'created_at': datetime.now() }) except Exception as e: print(f"MongoDB save error: {e}") return { 'success': True, 'agent_id': new_agent.passport_id, 'agent_name': agent.agent_name, 'spirit_score': agent.spirit_score, 'message': 'Agent created successfully' } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/agent/{agent_id}") async def get_agent( agent_id: str, api_key: str = Depends(verify_api_key) ): """์—์ด์ „ํŠธ ์กฐํšŒ""" if db is None: raise HTTPException(status_code=503, detail="MongoDB not connected") try: agent = db.agents.find_one({'agent_id': agent_id}, {'_id': 0}) if not agent: raise HTTPException(status_code=404, detail="Agent not found") return { 'success': True, 'agent': agent } except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/transactions") async def get_transactions( limit: int = 50, api_key: str = Depends(verify_api_key) ): """๊ฑฐ๋ž˜ ๋‚ด์—ญ ์กฐํšŒ""" if db is None: return { 'success': True, 'count': 0, 'transactions': [], 'message': 'MongoDB not connected - no persistent storage' } try: transactions = list( db.transactions .find({}, {'_id': 0}) .sort('timestamp', -1) .limit(limit) ) return { 'success': True, 'count': len(transactions), 'transactions': transactions } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/stats") async def get_stats(api_key: str = Depends(verify_api_key)): """ํ†ต๊ณ„ ์กฐํšŒ""" if db is None: return { 'success': True, 'stats': { 'total_transactions': 0, 'total_savings': 0, 'avg_discount_rate': 0, 'message': 'MongoDB not connected - no persistent storage' } } try: total_transactions = db.transactions.count_documents({}) pipeline = [ { '$group': { '_id': None, 'total_savings': {'$sum': '$total_savings'}, 'avg_discount': {'$avg': { '$multiply': [ {'$divide': [ {'$subtract': ['$base_price', '$negotiated_price']}, '$base_price' ]}, 100 ] }} } } ] result = list(db.transactions.aggregate(pipeline)) if result: stats = result[0] total_savings = stats.get('total_savings', 0) avg_discount = stats.get('avg_discount', 0) else: total_savings = 0 avg_discount = 0 return { 'success': True, 'stats': { 'total_transactions': total_transactions, 'total_savings': int(total_savings), 'avg_discount_rate': round(avg_discount, 2), 'mulberry_revenue': round(total_savings * 0.03, 2), 'community_share': round(total_savings * 0.10, 2) } } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/items") async def get_available_items(): """์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ํ’ˆ๋ชฉ ๋ชฉ๋ก""" items = get_items() return { 'success': True, 'count': len(items), 'items': [ { 'name': item['name'], 'base_price': item['base_price'], 'unit': item['unit'] } for item in items ] } @app.get("/api/demo/inje") async def demo_inje_data(): """์ธ์ œ๊ตฐ ๋ฐ๋ชจ ๋ฐ์ดํ„ฐ""" items = get_items() households = get_households() return { 'success': True, 'items': items, 'households': households, 'region': '์ธ์ œ๊ตฐ ์„œํ™”๋ฉด', 'description': '5๊ฐœ ํ’ˆ๋ชฉ, 8๊ฐ€๊ตฌ ๊ณต๋™๊ตฌ๋งค ํ˜‘์ƒ' } if __name__ == "__main__": import uvicorn uvicorn.run( app, host="0.0.0.0", port=int(os.getenv('PORT', 7860)), # HF Spaces uses 7860 log_level="info" )