import json import os import re import requests import numpy as np import faiss from dotenv import load_dotenv from openai import OpenAI from pypdf import PdfReader import gradio as gr load_dotenv(override=True) # ------------------------------ # Push notification utility (optional) # ------------------------------ def push(text): token = os.getenv("PUSHOVER_TOKEN") user = os.getenv("PUSHOVER_USER") if not token or not user: print("Pushover not configured — skipping push.") return requests.post( "https://api.pushover.net/1/messages.json", data={"token": token, "user": user, "message": text}, ) # ------------------------------ # Tool functions # ------------------------------ def record_user_details(email, name="Name not provided", mobile="not provided", notes="not provided"): push(f"Recording {name} with email {email}, mobile {mobile}, notes {notes}") return {"recorded": "ok"} def record_unknown_question(question): push(f"Unknown question: {question}") return {"recorded": "ok"} tools = [ { "type": "function", "function": { "name": "record_user_details", "description": "Record user interest + email", "parameters": { "type": "object", "properties": { "email": {"type": "string"}, "name": {"type": "string"}, "mobile": {"type": "string"}, "notes": {"type": "string"}, }, "required": ["email"], } } }, { "type": "function", "function": { "name": "record_unknown_question", "description": "Record any question that cannot be answered", "parameters": { "type": "object", "properties": {"question": {"type": "string"}}, "required": ["question"], } } } ] # ------------------------------ # RAG Retriever with FAISS # ------------------------------ class Retriever: def __init__(self, pdf_path, summary_path, embedding_model="text-embedding-3-large"): self.client = OpenAI() self.embedding_model = embedding_model print("Loading and chunking documents...") self.chunks = self.load_and_chunk(pdf_path, summary_path) print("Building FAISS index...") self.build_index() # --- Helpers --- def clean_text(self, text): return re.sub(r"\s+", " ", text).strip() def chunk(self, text, max_tokens=300): sentences = re.split(r"(?<=[.!?]) +", text) chunks, cur = [], "" for s in sentences: if len((cur + " " + s).split()) > max_tokens: chunks.append(cur.strip()) cur = s else: cur += " " + s if cur.strip(): chunks.append(cur.strip()) return chunks # --- Load PDF + summary --- def load_and_chunk(self, pdf_path, summary_path): reader = PdfReader(pdf_path) pdf_text = " ".join(page.extract_text() or "" for page in reader.pages) pdf_text = self.clean_text(pdf_text) with open(summary_path, "r", encoding="utf-8") as f: summary_text = self.clean_text(f.read()) return self.chunk(pdf_text) + self.chunk(summary_text) # --- Embeddings + FAISS --- def build_index(self): response = self.client.embeddings.create( model=self.embedding_model, input=self.chunks ) vectors = np.array([e.embedding for e in response.data]).astype("float32") self.index = faiss.IndexFlatL2(vectors.shape[1]) self.index.add(vectors) # --- Retrieval --- def retrieve(self, query, k=5): q_emb = self.client.embeddings.create( model=self.embedding_model, input=query ).data[0].embedding q_vec = np.array(q_emb).astype("float32").reshape(1, -1) distances, indices = self.index.search(q_vec, k) return [self.chunks[i] for i in indices[0]] # ------------------------------ # Chatbot # ------------------------------ class ChatBot: def __init__(self): self.client = OpenAI() self.name = "Christian Rivard" self.retriever = Retriever("me/Linkedin.pdf", "me/summary.txt") def handle_tool_calls(self, tool_calls): results = [] for call in tool_calls: name = call.function.name args = json.loads(call.function.arguments) fn = globals().get(name) result = fn(**args) results.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}) return results def build_messages(self, message, history): chunks = self.retriever.retrieve(message) persona = f"You are {self.name}, speaking professionally to recruiters." rules = ( "Use only the provided retrieved context. " "If unsure, call record_unknown_question. " "Encourage users to share name, company, email, mobile." ) rag = "\n\n".join([f"CHUNK {i+1}: {c}" for i, c in enumerate(chunks)]) system_prompt = f"{persona}\n{rules}\n\nRelevant CV info:\n{rag}" return [{"role": "system", "content": system_prompt}] + history + [ {"role": "user", "content": message} ] def chat(self, message, history): messages = self.build_messages(message, history) while True: response = self.client.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools ) msg = response.choices[0].message if msg.finish_reason == "tool_calls": results = self.handle_tool_calls(msg.tool_calls) messages.append(msg) messages.extend(results) else: return msg.content # ------------------------------ # Launch Gradio App # ------------------------------ bot = ChatBot() demo = gr.ChatInterface(bot.chat, type="messages") if __name__ == "__main__": demo.launch()