vip11017 commited on
Commit
ec295dd
·
0 Parent(s):

Added functionality to store form answer in mongodb

Browse files
.gitignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ .venv/
6
+ models/
7
+ .cache/
8
+ .env
9
+ *.pdf
10
+
11
+ # macOS
12
+ .DS_Store
13
+ data/.DS_Store
app/config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pymongo.mongo_client import MongoClient
2
+ from pymongo.server_api import ServerApi
3
+ from qdrant_client import QdrantClient
4
+ import os
5
+ from dotenv import load_dotenv
6
+
7
+
8
+ load_dotenv()
9
+
10
+ # MongoDB connection
11
+ MONGODB_CONNECTION_STRING = os.getenv("MONGODB_CONNECTION_STRING")
12
+ DB_NAME = "chatbot_demo"
13
+
14
+ # Demo chatbot defaults
15
+ DEMO_MAX_MESSAGES = 20
16
+ DEMO_EXPIRY_DAYS = 7
17
+
18
+
19
+ # Create a new client and connect to the server
20
+ client = MongoClient(MONGODB_CONNECTION_STRING, server_api=ServerApi('1'))
21
+
22
+ # Send a ping to confirm a successful connection
23
+ try:
24
+ client.admin.command('ping')
25
+ print("Pinged your deployment. You successfully connected to MongoDB!")
26
+
27
+ demo_database = client["Demo"]
28
+ demo_form_submissions = demo_database["demo_form_submissions"]
29
+ print("Connected to MongoDB collection successfully!")
30
+ except Exception as e:
31
+ print(e)
32
+
33
+ #Qdrant
34
+ QDRANT_URL = os.getenv("QDRANT_URL")
35
+ QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
36
+ client = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
app/ingestion/demo_form_fetch_store.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from app.config import demo_form_submissions
3
+ from ingestion.models import ChatbotIngest
4
+ from pydantic import HttpUrl
5
+
6
+ def store_demo_chatbot(ingest_data: ChatbotIngest):
7
+ try:
8
+ # Convert Pydantic model to dict
9
+ data_dict = ingest_data.dict()
10
+
11
+ # Convert HttpUrl to string
12
+ if isinstance(data_dict["website_url"], HttpUrl):
13
+ data_dict["website_url"] = str(data_dict["website_url"])
14
+
15
+ # Generate a unique chatbot_id
16
+ chatbot_id = str(uuid.uuid4())
17
+ data_dict['chatbot_id'] = chatbot_id
18
+
19
+ # Insert into MongoDB
20
+ demo_form_submissions.insert_one(data_dict)
21
+ print(f"Chatbot {chatbot_id} ingested successfully for company {ingest_data.company_name}")
22
+ return chatbot_id
23
+
24
+ except Exception as e:
25
+ print(f"Error storing demo chatbot: {e}")
26
+ raise
27
+
28
+ def get_chatbot_config(chatbot_id: str) -> dict:
29
+ """
30
+ Fetches a chatbot config from MongoDB by ID.
31
+ """
32
+ return demo_form_submissions.find_one({"chatbot_id": chatbot_id})
app/ingestion/models.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, EmailStr, HttpUrl
2
+ from typing import List, Optional
3
+ from datetime import datetime, timezone
4
+
5
+ class ChatbotIngest(BaseModel):
6
+ company_name: str
7
+ chatbot_name: Optional[str] = None
8
+ website_url: HttpUrl
9
+ chatbot_purpose: List[str] = []
10
+ additional_content: Optional[List[str]] = []
11
+ sensitive_topics: Optional[str] = None
12
+ tone_style: Optional[List[str]] = None
13
+ contact_email: EmailStr
14
+ contact_phone: str
15
+ submitted_at: datetime
16
+ ingested_at: datetime = datetime.now(timezone.utc)
app/ingestion/rag.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def scrape_website(url: str) -> str:
2
+ # Fetch website text (BeautifulSoup, requests)
3
+ return "full text of website"
4
+
5
+ def chunk_text(text: str) -> list[str]:
6
+ # Split text into chunks for embeddings
7
+ return ["chunk1", "chunk2"]
8
+
9
+ def store_website_chunks(chatbot_id: str, chunks: list, qdrant_client):
10
+ # Embed chunks and store in Qdrant
11
+ pass
12
+
13
+
app/ingestion/routes.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, BackgroundTasks, HTTPException
2
+ from ingestion.models import ChatbotIngest
3
+ from pymongo import MongoClient
4
+ from ingestion.utils import extract_tally_payload, store_demo_chatbot
5
+ from ingestion.workers import build_rag_for_chatbot
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+ logger.setLevel(logging.INFO)
10
+
11
+ router = APIRouter()
12
+
13
+
14
+ @router.post("/ingest")
15
+ async def ingest_chatbot_webhook(payload: dict,):
16
+ """
17
+ Adapter endpoint for Tally webhook.
18
+ Extracts form fields from Tally's nested payload and maps them to ChatbotIngest.
19
+ """
20
+ try:
21
+ ingest_dict = extract_tally_payload(payload)
22
+ ingest_data = ChatbotIngest(**ingest_dict)
23
+ print(ingest_data)
24
+ chatbot_id = store_demo_chatbot(ingest_data)
25
+
26
+ return {
27
+ "chatbot_id": chatbot_id,
28
+ "demo_url": f"/chatbot/demo/{chatbot_id}",
29
+ "message": "Demo chatbot ingestion succesfull"
30
+ }
31
+ except Exception as e:
32
+ logger.error(f"Error processing ingestion webhook: {e}")
33
+ raise HTTPException(status_code=500, detail="Internal Server Error - Failed to ingest chatbot demo")
app/ingestion/utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ def extract_tally_payload(payload: dict):
6
+ """
7
+ Extracts key chatbot information from a Tally webhook payload.
8
+ Handles optional/missing multi-select and dropdown values.
9
+ """
10
+ fields = payload.get("data", {}).get("fields", [])
11
+
12
+ # Map key -> field
13
+ key_map = {f["key"]: f for f in fields}
14
+
15
+ # Company info
16
+ company_name = key_map.get("question_kyp5Dd", {}).get("value")
17
+ chatbot_name = key_map.get("question_vAp47X", {}).get("value") or None
18
+ website_url = key_map.get("question_K6gL7z", {}).get("value")
19
+
20
+ # Multi-select chatbot purpose
21
+ purpose_field = key_map.get("question_1lxMZ4", {})
22
+ option_map = {opt["id"]: opt["text"] for opt in purpose_field.get("options", [])}
23
+ value_ids = purpose_field.get("value") or []
24
+ chatbot_purpose = [option_map.get(v, v) for v in value_ids]
25
+
26
+ # Multi-select additional content
27
+ content_field = key_map.get("question_MbgLkE", {})
28
+ content_option_map = {opt["id"]: opt["text"] for opt in content_field.get("options", [])}
29
+ value_ids = content_field.get("value") or []
30
+ additional_content = [content_option_map.get(v, v) for v in value_ids]
31
+
32
+ # Sensitive topics
33
+ sensitive_topics = key_map.get("question_J6gLaz", {}).get("value") or None
34
+
35
+ # Tone/style dropdown
36
+ tone_field = key_map.get("question_N694OQ", {})
37
+ tone_option_map = {opt["id"]: opt["text"] for opt in tone_field.get("options", [])}
38
+ value_ids = tone_field.get("value") or []
39
+ tone_style = [tone_option_map.get(v, v) for v in value_ids] if value_ids else None
40
+
41
+ # Contact
42
+ contact_email = key_map.get("question_qd7YN7", {}).get("value")
43
+ contact_phone = key_map.get("question_QDaxEp", {}).get("value")
44
+
45
+ # Timestamps
46
+ submitted_at_str = payload.get("data", {}).get("createdAt")
47
+ submitted_at = datetime.fromisoformat(submitted_at_str.replace("Z", "+00:00"))
48
+
49
+ return {
50
+ "company_name": company_name,
51
+ "chatbot_name": chatbot_name,
52
+ "website_url": website_url,
53
+ "chatbot_purpose": chatbot_purpose,
54
+ "additional_content": additional_content,
55
+ "sensitive_topics": sensitive_topics,
56
+ "tone_style": tone_style,
57
+ "contact_email": contact_email,
58
+ "contact_phone": contact_phone,
59
+ "submitted_at": submitted_at,
60
+ }
61
+
62
+
63
+
app/ingestion/webscrape.py ADDED
File without changes
app/ingestion/workers.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ingestion.utils import get_chatbot_config
2
+ from ingestion.rag import scrape_website, chunk_text, store_website_chunks
3
+ from app.config import qdrant_client
4
+
5
+ # workers.py
6
+ def build_rag_for_chatbot(chatbot_id: str):
7
+ # Full RAG pipeline for a single chatbot
8
+ config = get_chatbot_config(chatbot_id)
9
+ text = scrape_website(config['website_url'])
10
+ chunks = chunk_text(text)
11
+ store_website_chunks(chatbot_id, chunks, qdrant_client)
app/main.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from ingestion.routes import router as ingestion_router
3
+
4
+ app = FastAPI(
5
+ title="Chatbot Platform - Demo Ingestion",
6
+ description="Handles Tally form ingestion and demo chatbot configuration.",
7
+ version="1.0.0"
8
+ )
9
+
10
+ # Mount ingestion routes
11
+ app.include_router(ingestion_router, prefix="/ingestion", tags=["ingestion"])