import os import sys import json import re import asyncio from fastapi import FastAPI, HTTPException from fastapi.responses import StreamingResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from langchain_core.messages import HumanMessage from agent.graph import app import redis.asyncio as redis from fastapi import Depends import builtins if os.getenv("DEBUG", "false").lower() != "true": builtins.print = lambda *args, **kwargs: None # Optional rate limiting — graceful fallback if fastapi-limiter is unavailable try: from fastapi_limiter import FastAPILimiter from fastapi_limiter.depends import RateLimiter RATE_LIMITER_AVAILABLE = True except ImportError: RATE_LIMITER_AVAILABLE = False print("⚠️ Warning: fastapi-limiter not available. Rate limiting disabled.") # Add backend directory to path to allow imports sys.path.append(os.path.dirname(os.path.abspath(__file__))) app_server = FastAPI(title="BPS Agent API") # Import routers from api import bps from routers import admin as admin_router # Allow CORS for frontend (Next.js usually runs on localhost:3000) app_server.add_middleware( CORSMiddleware, allow_origins=["https://bagustenan.vercel.app", 'http://localhost:3000'], # Allow all origins for dev. In prod, specify domain. allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Include Routers # app_server.include_router(upload.router, prefix="/api", tags=["Upload"]) app_server.include_router(bps.router, prefix="/api", tags=["BPS"]) app_server.include_router(admin_router.router, tags=["Admin"]) @app_server.on_event("startup") async def startup(): if not RATE_LIMITER_AVAILABLE: print("⚠️ Warning: fastapi-limiter not installed. Rate limiting disabled.") return redis_url = os.getenv("REDIS_URL", "redis://localhost:6379") try: r = redis.from_url(redis_url, encoding="utf-8", decode_responses=True) await FastAPILimiter.init(r) print(f"✅ Redis Rate Limiter initialized at {redis_url}") except Exception as e: print(f"⚠️ Warning: Redis not found. Rate limiting disabled. Error: {e}") def get_rate_limiter(): """Return RateLimiter dependency if available, otherwise a no-op dependency.""" if RATE_LIMITER_AVAILABLE: return Depends(RateLimiter(times=10, seconds=60)) # No-op dependency when rate limiting is disabled async def no_op(): pass return Depends(no_op) class ChatRequest(BaseModel): message: str thread_id: str = "default_thread" async def generate_stream(message: str, thread_id: str): """ Generator function that yields Server-Sent Events (SSE). """ config = {"configurable": {"thread_id": thread_id}, "recursion_limit": 50} inputs = {"messages": [HumanMessage(content=message)]} accumulated_llm_response = "" last_sent_position = 0 total_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0} try: # Use astream_events to get granular events (tokens, tool calls, etc.) # version="v2" is recommended for standardizing output async for event in app.astream_events(inputs, config=config, version="v2"): kind = event["event"] # 1. Streaming LLM Tokens (The typing effect) # Check for both standard and legacy event names if kind == "on_chat_model_stream" or kind == "on_llm_stream": # DEBUG: lihat dari node mana event ini berasal metadata = event.get("metadata", {}) node_name = metadata.get("langgraph_node", "") if node_name != "agent": continue data = event.get("data", {}) chunk = data.get("chunk") # Handle different chunk structures content = "" if hasattr(chunk, "content"): content = chunk.content elif isinstance(chunk, str): content = chunk elif isinstance(chunk, dict) and "content" in chunk: content = chunk["content"] if content: if isinstance(content, list): # Gabungkan item list menjadi string jika ada texts = [] for part in content: if isinstance(part, dict) and part.get("type") == "text": texts.append(part.get("text", "")) content = "".join(texts) elif isinstance(content, dict): content = content.get("text", "") if not isinstance(content, str): content = str(content) accumulated_llm_response += content # Send only the new part (from last_sent_position) new_content = accumulated_llm_response[last_sent_position:] if new_content: print(f" [TOKEN] Sending {len(new_content)} chars") yield f"data: {json.dumps({'type': 'token', 'content': new_content})}\n\n" last_sent_position = len(accumulated_llm_response) # 2. Tool Usage Indicators (To show 'Searching...' in UI) elif kind == "on_tool_start": yield f"data: {json.dumps({'type': 'tool_start', 'name': event['name']})}\n\n" elif kind == "on_tool_end": output = event["data"].get("output") output_str = str(output) # Truncate long outputs for UI cleanliness if len(output_str) > 200: output_str = output_str[:200] + "..." print(f" [TOOL END] {event['name']}: {output_str[:100]}") yield f"data: {json.dumps({'type': 'tool_end', 'name': event['name'], 'output': output_str})}\n\n" # 3. Token Usage elif kind == "on_chat_model_end": output = event["data"].get("output") usage = None # Try to get usage from standard usage_metadata (LangChain v0.2+) if hasattr(output, "usage_metadata") and output.usage_metadata: usage = output.usage_metadata # Fallback to response_metadata (Provider specific) elif hasattr(output, "response_metadata"): usage = output.response_metadata.get("token_usage") if usage: total_usage["prompt_tokens"] += usage.get("input_tokens", usage.get("prompt_tokens", 0)) total_usage["completion_tokens"] += usage.get("output_tokens", usage.get("completion_tokens", 0)) total_usage["total_tokens"] += usage.get("total_tokens", 0) yield f"data: {json.dumps({'type': 'usage', 'content': total_usage})}\n\n" # Signal that stream is complete yield "data: [DONE]\n\n" except Exception as e: error_str = str(e) print(f"Error during streaming: {error_str}") # Log for debugging retry_seconds = None # Cari retryDelay menggunakan regex # Extract JSON substring inside the curly brackets # 2) Fallback: if above failed, try to directly extract "Please retry in XXs" pattern from message text if retry_seconds is None: try: # pattern: "Please retry in 47.5626726s." or "Please retry in 47s" m2 = re.search(r'Please retry in\s*([0-9]+(?:\.[0-9]+)?)s', error_str) if m2: # take integer seconds (round down) retry_seconds = str(int(float(m2.group(1)))) except Exception as fallbackErr: print("Fallback parse failed:", fallbackErr) # 3) final fallback default value if retry_seconds is None: retry_seconds = "30" # sensible default if "429" in error_str or "ResourceExhausted" in error_str: friendly_error = ( f"⚠️ **Batas Kuota Tercapai**\n\n" f"Silakan coba lagi dalam **{retry_seconds} detik** ⏳" ) error_msg = json.dumps({"type": "error", "content": friendly_error}) else: friendly_error = f"⚠️ **Terjadi Kesalahan**\n\n{error_str}" error_msg = json.dumps({"type": "error", "content": friendly_error}) yield f"data: {error_msg}\n\n" @app_server.post("/chat", dependencies=[get_rate_limiter()]) async def chat_endpoint(request: ChatRequest): async def log_stream(): print(f"\n--- 🚀 STARTING NEW CHAT STREAM ---") print(f"Request: {request.message}") async for chunk in generate_stream(request.message, request.thread_id): print(f"TO UI -> {chunk.strip()}") yield chunk print(f"--- 🏁 STREAM END ---\n") return StreamingResponse( log_stream(), media_type="text/event-stream" ) @app_server.get("/") def root(): return {"status": "running", "message": "FastAPI on HF Spaces"} @app_server.get("/health") async def health_check(): return {"status": "ok"} # if __name__ == "__main__": # import uvicorn # print("Starting FastAPI Server...") # uvicorn.run(app_server, host="0.0.0.0", port=8000)