Spaces:
Runtime error
Runtime error
File size: 14,519 Bytes
0cebd53 07e38d1 0cebd53 6902fd6 0cebd53 07e38d1 6902fd6 07e38d1 9f48b57 07e38d1 0cebd53 9f48b57 0cebd53 9f48b57 07e38d1 9f48b57 07e38d1 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 d053617 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 07e38d1 9f48b57 07e38d1 8b37214 9f48b57 07e38d1 9f48b57 07e38d1 9f48b57 07e38d1 9f48b57 07e38d1 9f48b57 07e38d1 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 9f48b57 0cebd53 5836210 0cebd53 9f48b57 983eb14 7972b58 6902fd6 983eb14 6902fd6 c3c64ac 983eb14 c3c64ac 983eb14 6902fd6 c3c64ac 983eb14 6902fd6 c3c64ac 6902fd6 c3c64ac 6902fd6 c3c64ac 983eb14 6902fd6 983eb14 6902fd6 983eb14 6902fd6 983eb14 6902fd6 983eb14 067f6ee 983eb14 07e38d1 9f48b57 3247d29 | 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | import json
import os
import logging
import asyncio
import re
import httpx
import lead_client
from datetime import datetime
from typing import Dict, Any, List
from fastapi import FastAPI, HTTPException, Request, Response
from pydantic import BaseModel
from google import genai
from google.genai import types
from fastapi.middleware.cors import CORSMiddleware
from baserow_client import BaserowClient
from client_configs import get_config # β config registry
# βββββββββββββββββββββββββββββββββββββββββββββ
# 1. LOGGING
# βββββββββββββββββββββββββββββββββββββββββββββ
log_filename = f"logs/server_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
os.makedirs("logs", exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.FileHandler(log_filename), logging.StreamHandler()],
)
logger = logging.getLogger("gemini-server")
sessions: Dict[str, List[types.Content]] = {}
session_data: Dict[str, Dict[str, Any]] = {}
baserow_client = BaserowClient()
# βββββββββββββββββββββββββββββββββββββββββββββ
# 2. TOOLS
# βββββββββββββββββββββββββββββββββββββββββββββ
def calculate_square_footage(length: float, width: float, floors: float, mobile_no: str) -> Dict[str, Any]:
"""Calculates total square footage from plot dimensions and floors (house construction)."""
logger.info(f"Tool: calculate_square_footage | {length}x{width}, {floors} floors, user={mobile_no}")
sqft_per_floor = length * width
total_sqft = sqft_per_floor * floors
session_data.setdefault(mobile_no, {}).update({"floors": floors, "sqft": sqft_per_floor})
return {"length": length, "width": width, "floors": floors,
"sqft_per_floor": sqft_per_floor, "total_sqft": total_sqft}
def calculate_construction_estimate(sqft: float, rate_per_sqft: float, mobile_no: str) -> Dict[str, Any]:
"""Calculates a preliminary house construction estimate using the rate provided by the knowledge base."""
logger.info(f"Tool: calculate_construction_estimate | {sqft} sqft @ Rs.{rate_per_sqft}, user={mobile_no}")
estimate = sqft * rate_per_sqft
prev = session_data.get(mobile_no, {})
session_data[mobile_no] = {**prev, "estimate": estimate, "sqft": sqft}
return {"sqft": sqft, "rate_per_sqft": rate_per_sqft, "estimate": estimate, "currency": "INR"}
def calculate_apartment_cost(super_built_up_area: float, rate_per_sqft: float, mobile_no: str) -> Dict[str, Any]:
"""Calculates indicative apartment base cost using the rate provided by the knowledge base."""
logger.info(f"Tool: calculate_apartment_cost | {super_built_up_area} sqft @ Rs.{rate_per_sqft}, user={mobile_no}")
base_cost = super_built_up_area * rate_per_sqft
session_data.setdefault(mobile_no, {}).update({"sqft": super_built_up_area, "estimate": base_cost})
return {
"super_built_up_area": super_built_up_area,
"rate_per_sqft": rate_per_sqft,
"base_cost": base_cost,
"note": "Additional charges (parking, GST, stamp duty, registration, etc.) are extra.",
"currency": "INR",
}
def calculate_interior_estimate(sqft: float, scope: str, min_rate: float, max_rate: float, mobile_no: str) -> Dict[str, Any]:
"""
Calculates a preliminary interior design estimate range based on rates provided by the knowledge base.
scope: 'full_home' | 'kitchen_only' | 'specific_rooms'
"""
logger.info(f"Tool: calculate_interior_estimate | {sqft} sqft, scope={scope}, rates={min_rate}-{max_rate}, user={mobile_no}")
low, high = sqft * min_rate, sqft * max_rate
session_data.setdefault(mobile_no, {}).update({"sqft": sqft, "estimate": (low + high) / 2})
return {"sqft": sqft, "scope": scope,
"estimate_range": {"min": low, "max": high},
"currency": "INR", "note": "Detailed quote requires a home visit."}
TOOL_REGISTRY: Dict[str, Any] = {
"calculate_square_footage": calculate_square_footage,
"calculate_construction_estimate": calculate_construction_estimate,
"calculate_apartment_cost": calculate_apartment_cost,
"calculate_interior_estimate": calculate_interior_estimate,
}
# βββββββββββββββββββββββββββββββββββββββββββββ
# 3. SYSTEM PROMPT BUILDER
# βββββββββββββββββββββββββββββββββββββββββββββ
def build_system_prompt(config: Dict[str, Any], mobile_no: str) -> str:
return f"""
### ROLE
You are "{config['bot_name']}", a professional sales assistant for this company.
Your goal: understand the customer's requirements, provide accurate information and
estimates using ONLY the verified facts below, and guide them toward a consultation.
---
### VERIFIED KNOWLEDGE BASE
{config['knowledge_base']}
---
### BEHAVIOUR INSTRUCTIONS
{config['behaviour']}
### GENERAL RULES
- NEVER invent or guess any price, area, or specification.
- Keep responses concise, warm, and professional.
- After every estimate, offer: "{config['closing_offer']}"
- If a site visit or call is needed, share contacts: {config['contacts']}
- The customer's mobile number is {mobile_no}. Pass it to tools when required.
"""
# βββββββββββββββββββββββββββββββββββββββββββββ
# 4. SAVE WITH RETRY
# βββββββββββββββββββββββββββββββββββββββββββββ
def save_with_retry(mobile: str, org_id: str = "", retries: int = 3) -> bool:
for attempt in range(retries):
try:
logger.info(f"π€ Attempt {attempt+1}: Saving lead {mobile}")
raw_history = sessions.get(mobile, [])
serializable_history = [
c.model_dump() if hasattr(c, "model_dump") else str(c)
for c in raw_history
]
sd = session_data.get(mobile, {})
data = {
"mobile": mobile,
"org_id": org_id,
"chat_history": str(serializable_history),
"created_at": datetime.now().isoformat(),
}
for field in ("floors", "sqft", "estimate"):
if field in sd:
data[field] = sd[field]
elem = baserow_client.find_estimate(mobile)
if elem:
baserow_client.update_estimate(elem["id"], data=data)
else:
baserow_client.insert_estimate(data=data)
logger.info("β
Saved to Baserow")
return True
except Exception as e:
logger.error(f"β Save failed (attempt {attempt+1}): {e}")
asyncio.sleep(1)
return False
# βββββββββββββββββββββββββββββββββββββββββββββ
# 5. APP & MODEL
# βββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(title="BuildCalc AI Server")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Replace with specific origins in production, e.g., ["http://localhost:3000"]
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ChatRequest(BaseModel):
message: str
user_id: str # consumer's mobile number
class ChatResponse(BaseModel):
response: str
status: str
gemini_client = genai.Client(api_key="AIzaSyBnCSTsoNp3TKCE7bEtxeOX8Nl_GE-gybU")
MODEL_ID = "gemini-3.1-flash-lite-preview"
# βββββββββββββββββββββββββββββββββββββββββββββ
# 6. CORE CHAT LOOP
# βββββββββββββββββββββββββββββββββββββββββββββ
def run_chat_loop(user_input: str, mobile_no: str) -> str:
# a. Validate consumer & fetch their org
lead = lead_client.check_user_exists(mobile_no) # must return dict with 'org' field
if not lead:
raise HTTPException(status_code=400, detail="User not found. Please register first.")
# b. Load company config from consumer's org
org_id = lead.get("org", "")
config = get_config(org_id)
if not config:
logger.error(f"No config for org='{org_id}', user={mobile_no}")
raise HTTPException(status_code=500,
detail=f"Company config not found for '{org_id}'. Contact support.")
logger.info(f"Config loaded | org={org_id}, type={config['client_type']}, user={mobile_no}")
# c. Resolve tools allowed for this company
enabled_tools = [
TOOL_REGISTRY[name]
for name in config.get("enabled_tools", [])
if name in TOOL_REGISTRY
]
# d. Build / restore session
if mobile_no not in sessions:
sessions[mobile_no] = []
chat = gemini_client.chats.create(
model=MODEL_ID,
config=types.GenerateContentConfig(
tools=enabled_tools,
system_instruction=build_system_prompt(config, mobile_no),
),
history=sessions[mobile_no],
)
# e. Send & persist
response = chat.send_message(user_input)
sessions[mobile_no] = chat.get_history()
save_with_retry(mobile=mobile_no, org_id=org_id)
return response.text
# βββββββββββββββββββββββββββββββββββββββββββββ
# 7. ENDPOINTS
# βββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(request: ChatRequest):
logger.info(f"Chat request | user={request.user_id}")
try:
text = run_chat_loop(request.message, request.user_id)
return ChatResponse(response=text, status="success")
except HTTPException:
raise
except Exception as e:
logger.error(f"Unhandled error: {e}")
raise HTTPException(status_code=500, detail="Internal AI Engine Error")
@app.post("/lead")
def capture_lead(user: lead_client.User):
logger.info(f"Lead capture | mobile={user.mobile}, org={user.org}")
if lead_client.check_user_exists(user.mobile):
return {"status": "existing_user", "mobile": user.mobile,
"name": user.name, "go_to_chat": True}
# Guard: reject unknown orgs before saving
if not get_config(user.org):
return {"status": "error",
"message": f"Unknown org '{user.org}'. Onboard this company first.",
"go_to_chat": False}
saved = lead_client.save_user(user.name, user.mobile, user.org)
if saved:
return {"status": "new_user", "message": "User saved",
"mobile": user.mobile, "name": user.name, "go_to_chat": True}
return {"status": "error", "message": "Failed to save user", "go_to_chat": False}
# Credentials from your Wati API Docs page
WATI_API_ENDPOINT = "https://live-mt-server.wati.io/10131646"
WATI_BEARER_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InRoZW9waW5pb25iZW5jaEBnbWFpbC5jb20iLCJuYW1laWQiOiJ0aGVvcGluaW9uYmVuY2hAZ21haWwuY29tIiwiZW1haWwiOiJ0aGVvcGluaW9uYmVuY2hAZ21haWwuY29tIiwiYXV0aF90aW1lIjoiMDQvMTAvMjAyNiAxMzo0ODo1MCIsInRlbmFudF9pZCI6IjEwMTMxNjQ2IiwiZGJfbmFtZSI6Im10LXByb2QtVGVuYW50cyIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6IkFETUlOSVNUUkFUT1IiLCJleHAiOjI1MzQwMjMwMDgwMCwiaXNzIjoiQ2xhcmVfQUkiLCJhdWQiOiJDbGFyZV9BSSJ9.MagDJHh_ir1qKztFx29MqtEMDwX9FIKwmhDZsCVcnGY" # Copy full token from your screen
@app.post("/webhook")
async def handle_wati_webhook(request: Request):
data = await request.json()
# --- FIX START: CHECK FOR BOT-SENT MESSAGES ---
# Check if the message is outgoing (sent by you) to prevent loops
# Note: 'origin' or 'owner' field names vary by Wati webhook version
if data.get("origin") == "sent" or data.get("owner") is True:
return {"status": "ignored_self_message"}
# Only process 'Message Received' type events
if data.get("eventType") != "message":
return {"status": "ignored_other_event"}
# --- FIX END ---
user_mobile = data.get("waId")
user_text = data.get("text")
user_name = data.get("senderName", "New User")
if not user_mobile or not user_text:
return {"status": "ignored_empty_content"}
try:
# Logic for Org ID extraction
org_id = "mathapathi"
match = re.search(r"\[REF:(\w+)\]", user_text)
if match:
org_id = match.group(1)
user_text = user_text.replace(match.group(0), "").strip()
# Automated Lead Registration
if not lead_client.check_user_exists(user_mobile):
lead_client.save_user(user_name, user_mobile, org_id)
# Trigger Chat Logic
ai_response_text = run_chat_loop(user_text, user_mobile)
# Send response back
await send_wati_session_message(user_mobile, ai_response_text)
except Exception as e:
logger.error(f"Wati Webhook Error: {e}")
return {"status": "success"}
async def send_wati_session_message(to_number: str, text: str):
"""Sends a reply back to the user via Wati Session API."""
# Note: Use sendSessionMessage for 24-hour window replies
url = f"{WATI_API_ENDPOINT}/api/v1/sendSessionMessage/{to_number}"
headers = {
"Authorization": f"Bearer {WATI_BEARER_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"messageText": text
}
async with httpx.AsyncClient() as client:
response = await client.post(url, params=payload, headers=headers)
logger.info(f"Wati Response: {response.status_code} - {response.text}")
return response.json()
if __name__ == "__main__":
import uvicorn
logger.info("Starting server...")
uvicorn.run(app, host="0.0.0.0", port=8000)
|