import json import os import logging import asyncio import lead_client from datetime import datetime from typing import Dict, Any, List from fastapi import FastAPI, HTTPException from pydantic import BaseModel from dotenv import load_dotenv # Google Gen AI SDK (Latest Gemini 3.1 Support) from google import genai from google.genai import types from baserow_client import BaserowClient from dotenv import load_dotenv # load_dotenv() # 1. PER-START LOGGING CONFIGURATION # Creates a new log file every time the server starts 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() def save_with_retry(mobile, retries=3): for attempt in range(retries): try: logger.info(f"📤 Attempt {attempt+1}: Saving lead {mobile}") # --- THE FIX STARTS HERE --- raw_history = sessions.get(mobile, []) # Convert each Content object into a serializable dictionary serializable_history = [ content.model_dump() if hasattr(content, 'model_dump') else str(content) for content in raw_history ] # --- THE FIX ENDS HERE --- data = { "mobile": mobile, "chat_history": str(serializable_history), "created_at": datetime.now().isoformat() } if session_data.get(mobile): if 'floors' in session_data[mobile]: floors = session_data[mobile].get('floors') data['floors'] = floors else: floors = None if 'sqft' in session_data[mobile]: sqft = session_data[mobile].get('sqft') data['sqft'] = sqft else: sqft = None if 'estimate' in session_data[mobile]: estimate = session_data[mobile].get('estimate') data['estimate'] = estimate else: estimate = None # data = { # "mobile": mobile, # "floors": floors, # "sqft": sqft, # "estimate": estimate, # "chat_history": str(serializable_history), # "created_at": datetime.now().isoformat() # } elem = baserow_client.find_estimate(mobile) # Optional: Check if record exists before upsert if elem: baserow_client.update_estimate(elem["id"], data=data) else: baserow_client.insert_estimate(data=data) logger.info("✅ Successfully saved to Baserow") return True except Exception as e: logger.error(f"❌ Save failed (attempt {attempt+1}): {str(e)}") asyncio.sleep(1) return False def calculate_square_footage(length: float, width: float, floors: float, mobile_no: str) -> Dict[str, Any]: """Calculates total square footage based on dimensions and number of floors.""" logger.info(f"Tool Invoked: calculate_square_footage for {length}x{width} and {floors} floors") sqft_per_floor = length * width total_sqft = sqft_per_floor * floors session_data[mobile_no] = {"floors": floors, "sqft": sqft_per_floor} return {"length": length, "width": width, "floors": floors, "total_sqft": total_sqft} def calculate_construction_estimate(sqft: float, mobile_no: str) -> Dict[str, Any]: """Calculates a preliminary construction estimate based on square footage.""" logger.info(f"Tool Invoked: calculate_construction_estimate for {sqft} sqft") # Mock calculation: Rs.2400 per sqft estimate = sqft * 2400 previously_saved = session_data.get(mobile_no, {}) session_data[mobile_no] = {"floors": previously_saved.get('floors', 1), "sqft": previously_saved.get('sqft', 0), "estimate": estimate} # save_with_retry( # mobile=mobile_no, # floors=session_data[mobile_no].get('floors', 1), # sqft=sqft, # estimate=estimate # ) return { "sqft": sqft, "estimate": estimate, "currency": "INR" } # 3. SERVER INITIALIZATION # load_dotenv() app = FastAPI(title="Gemini Tool-Calling Server") class ChatRequest(BaseModel): message: str user_id: str class ChatResponse(BaseModel): response: str status: str # Persistent Model Instance client = genai.Client(api_key="AIzaSyBnCSTsoNp3TKCE7bEtxeOX8Nl_GE-gybU") MODEL_ID = "gemini-3.1-flash-lite-preview" # High speed, low latency for chatbots # 4. THE CORE LOGIC LOOP # Gemini's 'automatic_function_calling' handles the loop: # Request -> Model -> Tool Call -> Execute -> Model -> Final Response def run_chat_loop(user_input: str, mobile_no: str): try: if(not lead_client.check_user_exists(mobile_no)) : raise HTTPException( status_code=400, detail="User does not exist. Please capture lead first." ) if mobile_no not in sessions: sessions[mobile_no] = [] history = sessions[mobile_no] chat = client.chats.create( model=MODEL_ID, config=types.GenerateContentConfig( tools=[calculate_square_footage, calculate_construction_estimate], # Register tools here system_instruction=f""" ### ROLE You are "BuildCalc," an expert architectural assistant for a premium home construction firm. Your sole purpose is to help potential clients calculate a preliminary construction estimate and capture their interest as a lead. ### OPERATIONAL RULES 1. **Adaptive Data Collection:** Your objective is to obtain the total Square Footage (sqft). - If the user knows their **total sqft**, use it directly. - If the user provides **land dimensions** (e.g., 30x40, 30*60) and **number of floors**, use the calculation tool to determine the total area. 2. **Concise Engagement:** Keep responses brief and focused. If a user says they want to build a "3-story house," ask for the dimensions of the plot to help calculate the total area. 3. **Implicit Tool Usage:** Use your available tools to process these inputs. Do not explain the tools to the user; simply present the resulting estimate. 4. **Lead Nurturing:** Once the estimate is provided, offer a "detailed material breakdown" or a "site visit" to capture the lead. ### CONVERSATION LOGIC - **Scenario A (Direct):** User provides sqft (e.g., "I'm building 2400 sqft"). -> Calculate Estimate. - **Scenario B (Dimensions):** User provides plot size and floors (e.g., "30x60, 2 floors"). -> Calculate Sqft first, then Calculate Estimate. - **Scenario C (Missing Info):** If the user mentions floors but no plot size (or vice versa), politely ask for the missing detail: *"To give you an accurate estimate for those 3 floors, could you tell me the dimensions of your plot (e.g., 30x40 or 40x60)?"* ### CONSTRAINTS - Never guess the price or the area. Always rely on your tools. - Maintain a professional, helpful, and high-end tone. - If the user asks for a "quote," explain that this is a preliminary estimate and a formal quote requires a consultation. ### USER PRE-DETERMINED INFO - Mobile Number: {mobile_no} (Use this when required while invoking the tools)""" ), history=history # This provides the 'Memory' ) # This call handles the tool-calling loop internally response = chat.send_message(user_input) sessions[mobile_no] = chat.get_history() save_with_retry( mobile=mobile_no ) return response.text except Exception as e: logger.error(f"Error in chat loop: {str(e)}") raise e # 5. API ENDPOINT @app.post("/chat", response_model=ChatResponse) async def chat_endpoint(request: ChatRequest): logger.info(f"Received request from User: {request.user_id}") try: final_text = run_chat_loop(request.message, request.user_id) return ChatResponse(response=final_text, status="success") except Exception as e: raise HTTPException(status_code=500, detail="Internal AI Engine Error") @app.post("/lead") def capture_lead(user: lead_client.User): print("\n=== NEW REQUEST ===") print("INPUT:", user) exists = lead_client.check_user_exists(user.mobile) if exists: return { "status": "existing_user", "message": "User already exists", "mobile": user.mobile, "name": user.name, "go_to_chat": True } saved = lead_client.save_user(user.name, user.mobile, user.org) print("FINAL SAVE STATUS:", saved) if saved: return { "status": "new_user", "message": "User saved successfully", "mobile": user.mobile, "name": user.name, "go_to_chat": True } else: return { "status": "error", "message": "Failed to save user in Baserow", "go_to_chat": False } if __name__ == "__main__": import uvicorn logger.info("Starting production server...") uvicorn.run(app, host="0.0.0.0", port=8000)