# %% from pymongo.mongo_client import MongoClient from pymongo.server_api import ServerApi import os from dotenv import load_dotenv from datetime import datetime, timezone # %% load_dotenv() MONGODB_CONNECTION_STRING = os.getenv('MONGODB_CONNECTION_STRING') # %% # Create a new client and connect to the server client = MongoClient(MONGODB_CONNECTION_STRING, server_api=ServerApi('1')) # Send a ping to confirm a successful connection try: client.admin.command('ping') print("Pinged your deployment. You successfully connected to MongoDB!") database = client["AdminLogs"] chat_logs = database["ChatLogs"] print("Connected to MongoDB collection successfully!") except Exception as e: print(e) # %% def log_chat(session_id: str, name: str, email: str, query: str, answer: str, latency_ms: float | None=None, metadata: dict=None): """ Logs a chat interaction to the MongoDB 'ChatLogs' collection. """ company_id = "80bd8dd8-1e20-5271-927a-02beab69abdd" chatbot_id = "a3a86959-0f92-5124-8eb8-d3012f8b1ea3" data = { "company_id": company_id, "chatbot_id": chatbot_id, "session_id": session_id, "name": name, "email": email, "timestamp": datetime.now(timezone.utc), "query": query, "answer": answer, "metadata": metadata or {}, "starred": False } if latency_ms is not None: data["latency_ms"] = latency_ms try: print("Logging chat:", data) result = chat_logs.insert_one(data) except Exception as e: print("Failed to log chat interaction:", e) # %%