chandrashekhar2002dubey commited on
Commit
0cebd53
Β·
1 Parent(s): 07e38d1

Fixed default bugs

Browse files
Files changed (4) hide show
  1. .gitignore +2 -1
  2. app.py +114 -22
  3. baserow_client.py +71 -0
  4. lead_client.py +69 -0
.gitignore CHANGED
@@ -1,2 +1,3 @@
1
  .env
2
- logs
 
 
1
  .env
2
+ logs
3
+ __pycache__
app.py CHANGED
@@ -1,5 +1,8 @@
 
1
  import os
2
  import logging
 
 
3
  from datetime import datetime
4
  from typing import Dict, Any, List
5
 
@@ -11,6 +14,11 @@ from dotenv import load_dotenv
11
  from google import genai
12
  from google.genai import types
13
 
 
 
 
 
 
14
  # 1. PER-START LOGGING CONFIGURATION
15
  # Creates a new log file every time the server starts
16
  log_filename = f"logs/server_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
@@ -27,27 +35,70 @@ logging.basicConfig(
27
  logger = logging.getLogger("gemini-server")
28
 
29
  sessions: Dict[str, List[types.Content]] = {}
30
-
31
- # 2. TOOL DEFINITIONS
32
- # def get_stock_price(ticker: str) -> Dict[str, Any]:
33
- # """Retrieves the current stock price for a given ticker symbol."""
34
- # logger.info(f"Tool Invoked: get_stock_price for {ticker}")
35
- # # Mock data for demonstration
36
- # return {"ticker": ticker, "price": 150.25, "currency": "USD"}
37
-
38
- def calculate_square_footage(length: float, width: float, floors: float) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  """Calculates total square footage based on dimensions and number of floors."""
40
  logger.info(f"Tool Invoked: calculate_square_footage for {length}x{width} and {floors} floors")
41
  sqft_per_floor = length * width
42
  total_sqft = sqft_per_floor * floors
 
43
  return {"length": length, "width": width, "floors": floors, "total_sqft": total_sqft}
44
 
45
- def calculate_construction_estimate(sqft: float) -> Dict[str, Any]:
46
  """Calculates a preliminary construction estimate based on square footage."""
47
  logger.info(f"Tool Invoked: calculate_construction_estimate for {sqft} sqft")
48
  # Mock calculation: Rs.2400 per sqft
 
49
  estimate = sqft * 2400
50
- return {"sqft": sqft, "estimate": estimate, "currency": "INR"}
 
 
 
 
 
 
 
 
 
 
51
 
52
 
53
  # 3. SERVER INITIALIZATION
@@ -63,24 +114,30 @@ class ChatResponse(BaseModel):
63
  status: str
64
 
65
  # Persistent Model Instance
66
- client = genai.Client(api_key="AIzaSyBnCSTsoNp3TKCE7bEtxeOX8Nl_GE-gybU")
67
  MODEL_ID = "gemini-3.1-flash-lite-preview" # High speed, low latency for chatbots
68
 
69
  # 4. THE CORE LOGIC LOOP
70
  # Gemini's 'automatic_function_calling' handles the loop:
71
  # Request -> Model -> Tool Call -> Execute -> Model -> Final Response
72
- def run_chat_loop(user_input: str, session_id: str):
73
  try:
74
- if session_id not in sessions:
75
- sessions[session_id] = []
 
 
 
 
 
 
76
 
77
- history = sessions[session_id]
78
 
79
  chat = client.chats.create(
80
  model=MODEL_ID,
81
  config=types.GenerateContentConfig(
82
  tools=[calculate_square_footage, calculate_construction_estimate], # Register tools here
83
- system_instruction="""
84
  ### ROLE
85
  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.
86
 
@@ -100,17 +157,17 @@ You are "BuildCalc," an expert architectural assistant for a premium home constr
100
  ### CONSTRAINTS
101
  - Never guess the price or the area. Always rely on your tools.
102
  - Maintain a professional, helpful, and high-end tone.
103
- - If the user asks for a "quote," explain that this is a preliminary estimate and a formal quote requires a consultation."""
 
 
 
104
  ),
105
  history=history # This provides the 'Memory'
106
  )
107
 
108
  # This call handles the tool-calling loop internally
109
  response = chat.send_message(user_input)
110
- sessions[session_id] = chat.get_history()
111
-
112
- logger.info(f"User Input: {user_input}")
113
- logger.info(f"Model Final Output: {response.text}")
114
 
115
  return response.text
116
  except Exception as e:
@@ -127,6 +184,41 @@ async def chat_endpoint(request: ChatRequest):
127
  return ChatResponse(response=final_text, status="success")
128
  except Exception as e:
129
  raise HTTPException(status_code=500, detail="Internal AI Engine Error")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  if __name__ == "__main__":
132
  import uvicorn
 
1
+ import json
2
  import os
3
  import logging
4
+ import asyncio
5
+ import lead_client
6
  from datetime import datetime
7
  from typing import Dict, Any, List
8
 
 
14
  from google import genai
15
  from google.genai import types
16
 
17
+ from baserow_client import BaserowClient
18
+ from dotenv import load_dotenv
19
+
20
+ load_dotenv()
21
+
22
  # 1. PER-START LOGGING CONFIGURATION
23
  # Creates a new log file every time the server starts
24
  log_filename = f"logs/server_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
 
35
  logger = logging.getLogger("gemini-server")
36
 
37
  sessions: Dict[str, List[types.Content]] = {}
38
+ session_data: Dict[str, Dict[str, Any]] = {}
39
+
40
+ baserow_client = BaserowClient()
41
+
42
+ def save_with_retry(mobile, floors, sqft, estimate, retries=3):
43
+ for attempt in range(retries):
44
+ try:
45
+ logger.info(f"πŸ“€ Attempt {attempt+1}: Saving lead {mobile}")
46
+
47
+ # --- THE FIX STARTS HERE ---
48
+ raw_history = sessions.get(mobile, [])
49
+
50
+ # Convert each Content object into a serializable dictionary
51
+ serializable_history = [
52
+ content.model_dump() if hasattr(content, 'model_dump') else str(content)
53
+ for content in raw_history
54
+ ]
55
+ # --- THE FIX ENDS HERE ---
56
+
57
+ data = {
58
+ "mobile": mobile,
59
+ "floors": floors,
60
+ "sqft": sqft,
61
+ "estimate": estimate,
62
+ "chat_history": str(serializable_history),
63
+ "created_at": datetime.now().isoformat()
64
+ }
65
+
66
+ baserow_client.insert_estimate(data=data)
67
+
68
+ logger.info("βœ… Successfully saved to Baserow")
69
+ return True
70
+
71
+ except Exception as e:
72
+ logger.error(f"❌ Save failed (attempt {attempt+1}): {str(e)}")
73
+ asyncio.sleep(1)
74
+
75
+ return False
76
+
77
+ def calculate_square_footage(length: float, width: float, floors: float, mobile_no: str) -> Dict[str, Any]:
78
  """Calculates total square footage based on dimensions and number of floors."""
79
  logger.info(f"Tool Invoked: calculate_square_footage for {length}x{width} and {floors} floors")
80
  sqft_per_floor = length * width
81
  total_sqft = sqft_per_floor * floors
82
+ session_data[mobile_no] = {"floors": floors, "sqft": sqft_per_floor}
83
  return {"length": length, "width": width, "floors": floors, "total_sqft": total_sqft}
84
 
85
+ def calculate_construction_estimate(sqft: float, mobile_no: str) -> Dict[str, Any]:
86
  """Calculates a preliminary construction estimate based on square footage."""
87
  logger.info(f"Tool Invoked: calculate_construction_estimate for {sqft} sqft")
88
  # Mock calculation: Rs.2400 per sqft
89
+
90
  estimate = sqft * 2400
91
+ save_with_retry(
92
+ mobile=mobile_no,
93
+ floors=session_data.get("floors", 1),
94
+ sqft=sqft,
95
+ estimate=estimate
96
+ )
97
+ return {
98
+ "sqft": sqft,
99
+ "estimate": estimate,
100
+ "currency": "INR"
101
+ }
102
 
103
 
104
  # 3. SERVER INITIALIZATION
 
114
  status: str
115
 
116
  # Persistent Model Instance
117
+ client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
118
  MODEL_ID = "gemini-3.1-flash-lite-preview" # High speed, low latency for chatbots
119
 
120
  # 4. THE CORE LOGIC LOOP
121
  # Gemini's 'automatic_function_calling' handles the loop:
122
  # Request -> Model -> Tool Call -> Execute -> Model -> Final Response
123
+ def run_chat_loop(user_input: str, mobile_no: str):
124
  try:
125
+ if(not lead_client.check_user_exists(mobile_no)) :
126
+ raise HTTPException(
127
+ status_code=400,
128
+ detail="User does not exist. Please capture lead first."
129
+ )
130
+
131
+ if mobile_no not in sessions:
132
+ sessions[mobile_no] = []
133
 
134
+ history = sessions[mobile_no]
135
 
136
  chat = client.chats.create(
137
  model=MODEL_ID,
138
  config=types.GenerateContentConfig(
139
  tools=[calculate_square_footage, calculate_construction_estimate], # Register tools here
140
+ system_instruction=f"""
141
  ### ROLE
142
  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.
143
 
 
157
  ### CONSTRAINTS
158
  - Never guess the price or the area. Always rely on your tools.
159
  - Maintain a professional, helpful, and high-end tone.
160
+ - If the user asks for a "quote," explain that this is a preliminary estimate and a formal quote requires a consultation.
161
+
162
+ ### USER PRE-DETERMINED INFO
163
+ - Mobile Number: {mobile_no} (Use this when required while invoking the tools)"""
164
  ),
165
  history=history # This provides the 'Memory'
166
  )
167
 
168
  # This call handles the tool-calling loop internally
169
  response = chat.send_message(user_input)
170
+ sessions[mobile_no] = chat.get_history()
 
 
 
171
 
172
  return response.text
173
  except Exception as e:
 
184
  return ChatResponse(response=final_text, status="success")
185
  except Exception as e:
186
  raise HTTPException(status_code=500, detail="Internal AI Engine Error")
187
+
188
+ @app.post("/lead")
189
+ def capture_lead(user: lead_client.User):
190
+ print("\n=== NEW REQUEST ===")
191
+ print("INPUT:", user)
192
+
193
+ exists = lead_client.check_user_exists(user.mobile)
194
+
195
+ if exists:
196
+ return {
197
+ "status": "existing_user",
198
+ "message": "User already exists",
199
+ "mobile": user.mobile,
200
+ "name": user.name,
201
+ "go_to_chat": True
202
+ }
203
+
204
+ saved = lead_client.save_user(user.name, user.mobile)
205
+
206
+ print("FINAL SAVE STATUS:", saved)
207
+
208
+ if saved:
209
+ return {
210
+ "status": "new_user",
211
+ "message": "User saved successfully",
212
+ "mobile": user.mobile,
213
+ "name": user.name,
214
+ "go_to_chat": True
215
+ }
216
+ else:
217
+ return {
218
+ "status": "error",
219
+ "message": "Failed to save user in Baserow",
220
+ "go_to_chat": False
221
+ }
222
 
223
  if __name__ == "__main__":
224
  import uvicorn
baserow_client.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ import os
3
+ from datetime import datetime
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ BASEROW_TOKEN = os.getenv("BASEROW_TOKEN")
9
+ USER_CHAT_TABLE_ID = os.getenv("BASEROW_TABLE_ID")
10
+
11
+ BASE_URL = f"https://api.baserow.io/api/database/rows/table/{USER_CHAT_TABLE_ID}/?user_field_names=true"
12
+
13
+
14
+ class BaserowClient:
15
+ def __init__(self):
16
+ self.headers = {
17
+ "Authorization": f"Token {BASEROW_TOKEN}",
18
+ "Content-Type": "application/json"
19
+ }
20
+
21
+ # πŸ” FIND estimate BY MOBILE
22
+ def find_estimate(self, mobile):
23
+ url = f"{BASE_URL}&filter__mobile__equal={mobile}"
24
+
25
+ with httpx.Client() as client:
26
+ res = client.get(url, headers=self.headers)
27
+
28
+ print("\n--- FIND estimate ---")
29
+ print(res.status_code, res.text)
30
+
31
+ data = res.json()
32
+ return data["results"][0] if data.get("results") else None
33
+
34
+ # βž• INSERT
35
+ def insert_estimate(self, data):
36
+ with httpx.Client() as client:
37
+ res = client.post(BASE_URL, headers=self.headers, json=data)
38
+
39
+ print("\n--- INSERT ---")
40
+ print(res.status_code, res.text)
41
+
42
+ return res.json()
43
+
44
+ # ✏️ UPDATE
45
+ def update_estimate(self, row_id, data):
46
+ url = f"https://api.baserow.io/api/database/rows/table/{USER_CHAT_TABLE_ID}/{row_id}/?user_field_names=true"
47
+
48
+ with httpx.Client() as client:
49
+ res = client.patch(url, headers=self.headers, json=data)
50
+
51
+ print("\n--- UPDATE ---")
52
+ print(res.status_code, res.text)
53
+
54
+ return res.json()
55
+
56
+ # πŸ” UPSERT (MAIN LOGIC)
57
+ def upsert_estimate(self, mobile, floors, estimate, sqft):
58
+ #existing = self.find_estimate(mobile)
59
+
60
+ data = {
61
+ "mobile": mobile,
62
+ "floors": floors,
63
+ "sqft": sqft,
64
+ "estimate": estimate,
65
+ "created_at": datetime.now().isoformat()
66
+ }
67
+
68
+ # if existing:
69
+ # return self.update_estimate(existing["id"], data)
70
+
71
+ return self.insert_estimate(data)
lead_client.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import requests
4
+ from fastapi import FastAPI
5
+ from pydantic import BaseModel
6
+
7
+ load_dotenv() # Load environment variables from .env file
8
+
9
+ # πŸ”‘ CONFIG
10
+ BASEROW_TOKEN = os.getenv("BASEROW_TOKEN")
11
+ LEAD_CLIENT_TABLE_ID = os.getenv("BASEROW_TABLE_ID_V1")
12
+
13
+ # if not BASEROW_TOKEN or not TABLE_ID:
14
+ # raise Exception("❌ Missing BASEROW_TOKEN or TABLE_ID in environment variables")
15
+
16
+ BASE_URL = f"https://api.baserow.io/api/database/rows/table/{LEAD_CLIENT_TABLE_ID}/"
17
+
18
+ HEADERS = {
19
+ "Authorization": f"Token {BASEROW_TOKEN}",
20
+ "Content-Type": "application/json"
21
+ }
22
+
23
+ # πŸ“₯ Request Model
24
+ class User(BaseModel):
25
+ name: str
26
+ mobile: str
27
+
28
+ # πŸ” Check if user exists (SAFE METHOD)
29
+ def check_user_exists(mobile):
30
+ try:
31
+ response = requests.get(BASE_URL, headers=HEADERS)
32
+
33
+ print("\n--- CHECK USER DEBUG ---")
34
+ print("STATUS:", response.status_code)
35
+ print("RESPONSE:", response.text)
36
+
37
+ if response.status_code == 200:
38
+ data = response.json()
39
+
40
+ for row in data.get("results", []):
41
+ # βœ… use field ID
42
+ if str(row.get("field_7932385")) == str(mobile):
43
+ return True
44
+
45
+ return False
46
+
47
+ except Exception as e:
48
+ print("CHECK ERROR:", str(e))
49
+ return False
50
+
51
+
52
+ # πŸ’Ύ Save user to Baserow
53
+ def save_user(name, mobile):
54
+ payload = {
55
+ "field_7932386": name, # βœ… name
56
+ "field_7932385": str(mobile) # βœ… mobile
57
+ }
58
+ try:
59
+ response = requests.post(BASE_URL, headers=HEADERS, json=payload)
60
+
61
+ print("\n--- SAVE USER DEBUG ---")
62
+ print("PAYLOAD:", payload)
63
+ print("STATUS:", response.status_code)
64
+ print("RESPONSE:", response.text)
65
+
66
+ return response.status_code in [200, 201]
67
+ except Exception as e:
68
+ print("SAVE ERROR:", str(e))
69
+ return False