import os import json import gradio as gr from openai import OpenAI from dotenv import load_dotenv from email.mime.text import MIMEText import requests from google_auth_oauthlib.flow import InstalledAppFlow # Load environment variables load_dotenv(override=True) client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # Google Calendar API from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # ==== Google Calendar Setup ==== SCOPES = ['https://www.googleapis.com/auth/calendar.events'] def get_calendar_service(): creds = Credentials.from_authorized_user_file("token.json", SCOPES) return build("calendar", "v3", credentials=creds) # === Pushover Function === def send_notification(message): try: response = requests.post( "https://api.pushover.net/1/messages.json", data={ "token": os.getenv("PUSHOVER_TOKEN"), "user": os.getenv("PUSHOVER_USER"), "message": message } ) print("Pushover notification sent.") return {"status": "pushover sent", "response": response.status_code} except Exception as e: print(f"Failed to send pushover: {e}") return {"status": "pushover failed", "error": str(e)} # === Tool Function === def record_user_interest(email, name=None): msg = f"User interested: {name or 'Anonymous'} <{email}>" return send_notification(msg) def record_unknown_question(question): msg = f"Unknown question: {question}" return send_notification(msg) def schedule_session(topic, preferred_time, email): zapier_webhook = os.getenv("ZAPIER_WEBHOOK_URL") payload = { "topic": topic, "preferred_time": preferred_time, "email": email } try: response = requests.post(zapier_webhook, json=payload) if response.status_code == 200: print("Zapier webhook triggered.") return send_notification(f"Session scheduled:\nTopic: {topic}\nTime: {preferred_time}") else: print("Zapier error:", response.text) return {"status": "webhook error", "response": response.text} except Exception as e: print(f"Webhook Exception: {e}") return {"status": "webhook error", "error": str(e)} # === Tool Functions === def send_email(subject, body, user_email): import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender_email = os.getenv("SMTP_FROM") smtp_user = os.getenv("SMTP_USER") smtp_pass = os.getenv("SMTP_PASS") smtp_server = os.getenv("SMTP_SERVER") smtp_port = int(os.getenv("SMTP_PORT", 587)) # default to 587 if not set message = MIMEMultipart() message["From"] = sender_email message["To"] = user_email message["Subject"] = subject message.attach(MIMEText(body, "plain")) try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(smtp_user, smtp_pass) server.send_message(message) print(f"Email sent to {user_email}") return {"status": "sent"} except Exception as e: print(f"Failed to send email: {e}") return {"status": "failed", "error": str(e)} # === Tool Schema === record_unknown_question_json = { "name": "record_unknown_question", "description": "Use this tool to log a question the assistant couldn't answer.", "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "The question text" } }, "required": ["question"], "additionalProperties": False } } record_user_interest_json = { "name": "record_user_interest", "description": "Log the email of a user who's interested in following up.", "parameters": { "type": "object", "properties": { "email": { "type": "string", "description": "The user's email address" }, "name": { "type": "string", "description": "The user's name if available" } }, "required": ["email"], "additionalProperties": False } } schedule_session_json = { "name": "schedule_session", "description": "Schedule a tutoring session for a given topic and time.", "parameters": { "type": "object", "properties": { "topic": {"type": "string", "description": "Topic for the session"}, "preferred_time": {"type": "string", "description": "Preferred time for the session"}, "email": {"type": "string", "description": "User's email address to notify"} }, "required": ["topic", "preferred_time"], "additionalProperties": False } } tools = [ {"type": "function", "function": record_unknown_question_json}, {"type": "function", "function": record_user_interest_json}, {"type": "function", "function": schedule_session_json} ] # === Class with chat logic === class Tutor: def __init__(self): self.openai = client self.name = "Tutor" def system_prompt(self): return ( f"You are {self.name}, a helpful tutor specializing in math and physics. " f"If you don’t know the answer to a question, use the tool to record it." ) def handle_tool_call(self, tool_calls): results = [] for tool_call in tool_calls: tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) tool = globals().get(tool_name) result = tool(**arguments) if tool else {} results.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) }) return results def chat(self, message, history): messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}] done = False while not done: response = self.openai.chat.completions.create( model="gpt-4o", messages=messages, tools=tools ) choice = response.choices[0] if choice.finish_reason == "tool_calls": tool_calls = choice.message.tool_calls messages.append(choice.message) messages.extend(self.handle_tool_call(tool_calls)) else: done = True return response.choices[0].message.content # === Run the app === if __name__ == "__main__": tutor = Tutor() gr.ChatInterface(tutor.chat, type="messages").launch()