buildbot / app.py
chandrashekhar2002dubey's picture
Added messages
7972b58
Raw History Blame Contribute Delete
14.5 kB
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)