redfernstech commited on
Commit
7f3c462
·
verified ·
1 Parent(s): e73251d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -8
app.py CHANGED
@@ -239,6 +239,9 @@ from langchain_core.prompts import ChatPromptTemplate
239
  from llama_index.core import StorageContext, VectorStoreIndex, SimpleDirectoryReader, Settings
240
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
241
 
 
 
 
242
 
243
  # Define Pydantic model for incoming request body
244
  class MessageRequest(BaseModel):
@@ -287,18 +290,19 @@ Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
287
  # Salesforce credentials
288
  username = os.getenv("username")
289
  password = os.getenv("password")
290
- security_token = os.getenv("security_token zasi")
291
  domain = os.getenv("domain") # e.g., 'test' for sandbox
292
 
293
- # Initialize Salesforce connection
 
294
  try:
295
  session_id, sf_instance = SalesforceLogin(
296
  username=username, password=password, security_token=security_token, domain=domain
297
  )
298
  sf = Salesforce(instance=sf_instance, session_id=session_id)
 
299
  except Exception as e:
300
- logger.error(f"Failed to connect to Salesforce: {e}")
301
- raise HTTPException(status_code=500, detail="Salesforce connection failed")
302
 
303
  # Chat history
304
  chat_history = []
@@ -316,6 +320,9 @@ os.makedirs(PERSIST_DIR, exist_ok=True)
316
  def data_ingestion_from_directory():
317
  try:
318
  documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
 
 
 
319
  storage_context = StorageContext.from_defaults()
320
  index = VectorStoreIndex.from_documents(documents)
321
  index.storage_context.persist(persist_dir=PERSIST_DIR)
@@ -389,10 +396,14 @@ async def load_chat(request: Request, id: str):
389
 
390
  @app.post("/hist/")
391
  async def save_chat_history(history: dict):
 
 
 
 
392
  user_id = history.get('userId')
393
  if not user_id:
394
  logger.error("userId is missing in history request")
395
- raise HTTPException(status_code=400, detail="userId is required")
396
 
397
  hist = ''.join([f"'{entry['sender']}: {entry['message']}'\n" for entry in history['history']])
398
  hist = "You are a Redfernstech summarize model. Identify user interests from this conversation: " + hist
@@ -402,17 +413,21 @@ async def save_chat_history(history: dict):
402
  logger.info(f"Chat history updated for user {user_id}")
403
  except Exception as e:
404
  logger.error(f"Failed to update lead: {e}")
405
- raise HTTPException(status_code=500, detail=f"Failed to update lead: {str(e)}")
406
 
407
  return {"summary": hist, "message": "Chat history saved"}
408
 
409
  @app.post("/webhook")
410
  async def receive_form_data(request: Request):
 
 
 
 
411
  try:
412
  form_data = await request.json()
413
  except json.JSONDecodeError:
414
  logger.error("Invalid JSON in webhook request")
415
- raise HTTPException(status_code=400, detail="Invalid JSON")
416
 
417
  first_name, last_name = split_name(form_data.get('name', ''))
418
  data = {
@@ -431,7 +446,7 @@ async def receive_form_data(request: Request):
431
  return JSONResponse({"id": unique_id})
432
  except Exception as e:
433
  logger.error(f"Failed to create lead: {e}")
434
- raise HTTPException(status_code=500, detail=f"Failed to create lead: {str(e)}")
435
 
436
  @app.post("/chat/")
437
  async def chat(request: MessageRequest):
 
239
  from llama_index.core import StorageContext, VectorStoreIndex, SimpleDirectoryReader, Settings
240
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
241
 
242
+ # Configure logging
243
+ logging.basicConfig(level=logging.INFO)
244
+ logger = logging.getLogger(__name__)
245
 
246
  # Define Pydantic model for incoming request body
247
  class MessageRequest(BaseModel):
 
290
  # Salesforce credentials
291
  username = os.getenv("username")
292
  password = os.getenv("password")
293
+ security_token = os.getenv("security_token")
294
  domain = os.getenv("domain") # e.g., 'test' for sandbox
295
 
296
+ # Initialize Salesforce connection (allow failure)
297
+ sf = None
298
  try:
299
  session_id, sf_instance = SalesforceLogin(
300
  username=username, password=password, security_token=security_token, domain=domain
301
  )
302
  sf = Salesforce(instance=sf_instance, session_id=session_id)
303
+ logger.info("Salesforce connection established")
304
  except Exception as e:
305
+ logger.error(f"Failed to connect to Salesforce: {e}. Continuing without Salesforce integration.")
 
306
 
307
  # Chat history
308
  chat_history = []
 
320
  def data_ingestion_from_directory():
321
  try:
322
  documents = SimpleDirectoryReader(PDF_DIRECTORY).load_data()
323
+ if not documents:
324
+ logger.warning("No documents found in PDF_DIRECTORY")
325
+ return
326
  storage_context = StorageContext.from_defaults()
327
  index = VectorStoreIndex.from_documents(documents)
328
  index.storage_context.persist(persist_dir=PERSIST_DIR)
 
396
 
397
  @app.post("/hist/")
398
  async def save_chat_history(history: dict):
399
+ if not sf:
400
+ logger.error("Salesforce integration is disabled")
401
+ return {"error": "Salesforce integration is unavailable"}, 503
402
+
403
  user_id = history.get('userId')
404
  if not user_id:
405
  logger.error("userId is missing in history request")
406
+ return {"error": "userId is required"}, 400
407
 
408
  hist = ''.join([f"'{entry['sender']}: {entry['message']}'\n" for entry in history['history']])
409
  hist = "You are a Redfernstech summarize model. Identify user interests from this conversation: " + hist
 
413
  logger.info(f"Chat history updated for user {user_id}")
414
  except Exception as e:
415
  logger.error(f"Failed to update lead: {e}")
416
+ return {"error": f"Failed to update lead: {str(e)}"}, 500
417
 
418
  return {"summary": hist, "message": "Chat history saved"}
419
 
420
  @app.post("/webhook")
421
  async def receive_form_data(request: Request):
422
+ if not sf:
423
+ logger.error("Salesforce integration is disabled")
424
+ return {"error": "Salesforce integration is unavailable"}, 503
425
+
426
  try:
427
  form_data = await request.json()
428
  except json.JSONDecodeError:
429
  logger.error("Invalid JSON in webhook request")
430
+ return {"error": "Invalid JSON"}, 400
431
 
432
  first_name, last_name = split_name(form_data.get('name', ''))
433
  data = {
 
446
  return JSONResponse({"id": unique_id})
447
  except Exception as e:
448
  logger.error(f"Failed to create lead: {e}")
449
+ return {"error": f"Failed to create lead: {str(e)}"}, 500
450
 
451
  @app.post("/chat/")
452
  async def chat(request: MessageRequest):