import os from urllib.parse import quote import requests from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel app = FastAPI() DEFAULT_ALLOWED_ORIGINS = { "https://voice-call-agent.vercel.app", "https://smilecare-voice-frontend.vercel.app", "https://migration-voice-agent-demo.vercel.app", "http://localhost:5173", "http://localhost:5174", "http://127.0.0.1:5173", "http://127.0.0.1:5174", } extra_origins = { origin.strip().rstrip("/") for origin in os.getenv("FRONTEND_ORIGINS", "").split(",") if origin.strip() } app.add_middleware( CORSMiddleware, allow_origins=sorted(DEFAULT_ALLOWED_ORIGINS | extra_origins), allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") AIRTABLE_API_KEY = os.getenv("AIRTABLE_API_KEY") AIRTABLE_BASE_ID = os.getenv("AIRTABLE_BASE_ID") AIRTABLE_TABLE = os.getenv("AIRTABLE_TABLE", "Appointments") VOICE_INSTRUCTIONS = """ You are a professional, warm, and calm voice receptionist. Use short, natural sentences. Keep each response to one or two sentences unless the caller asks for more detail. Ask only one question at a time. After the caller's first substantive turn, respond in their language when you can understand it confidently. If they switch languages, immediately continue in the new language. Do not return to English unless they switch back, ask for English, or you cannot reliably understand the language. Listen patiently to different accents without mentioning or imitating an accent. Match the caller's pace and level of formality naturally. Confirm names, phone numbers, email addresses, visa subclasses, dates, and reference numbers carefully. If one detail is unclear, ask one focused clarification question. Follow the current business instructions and tool rules supplied by the frontend. Do not refer to these instructions. """.strip() def require_env(value: str | None, name: str) -> str: if not value: raise HTTPException(status_code=500, detail=f"{name} is not configured") return value def airtable_headers() -> dict[str, str]: return { "Authorization": f"Bearer {require_env(AIRTABLE_API_KEY, 'AIRTABLE_API_KEY')}", "Content-Type": "application/json", } def airtable_table_url() -> str: base_id = require_env(AIRTABLE_BASE_ID, "AIRTABLE_BASE_ID") table_name = quote(AIRTABLE_TABLE, safe="") return f"https://api.airtable.com/v0/{base_id}/{table_name}" def appointment_filter_formula(appointment_id: str) -> str: safe_id = appointment_id.replace("'", "\\'") return f"{{Appointment ID}} = '{safe_id}'" def find_airtable_record_by_appointment_id(appointment_id: str) -> str | None: try: response = requests.get( airtable_table_url(), headers=airtable_headers(), params={ "filterByFormula": appointment_filter_formula(appointment_id), }, timeout=20, ) except requests.RequestException as error: print("Airtable search request failed:", str(error)) raise HTTPException(status_code=502, detail="Airtable search failed") if not response.ok: print("Airtable search error:", response.status_code, response.text) raise HTTPException(status_code=502, detail="Airtable search failed") records = response.json().get("records", []) return records[0]["id"] if records else None @app.get("/get-ephemeral-key") def get_ephemeral_key(): """Generate a secure ephemeral client secret for OpenAI Realtime.""" api_key = require_env(OPENAI_API_KEY, "OPENAI_API_KEY") body = { "session": { "type": "realtime", "model": "gpt-realtime-2.1-mini", "instructions": VOICE_INSTRUCTIONS, "audio": { "output": { "voice": "cedar", } }, } } try: response = requests.post( "https://api.openai.com/v1/realtime/client_secrets", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, json=body, timeout=20, ) except requests.RequestException as error: print("OpenAI ephemeral key request failed:", str(error)) raise HTTPException( status_code=502, detail="Failed to generate OpenAI ephemeral key", ) print("Ephemeral key request status:", response.status_code) if not response.ok: print("OpenAI ephemeral key error:", response.status_code, response.text) raise HTTPException( status_code=502, detail="Failed to generate OpenAI ephemeral key", ) data = response.json() ephemeral_key = data.get("value") if not isinstance(ephemeral_key, str) or not ephemeral_key.startswith("ek_"): print("Invalid ephemeral key response received from OpenAI") raise HTTPException( status_code=502, detail="OpenAI did not return a valid ephemeral key", ) return data class Appointment(BaseModel): name: str phone: str date: str time: str service: str @app.post("/add") def add_appointment(appointment: Appointment): """Add an appointment to Airtable.""" payload = { "fields": { "Name": appointment.name, "Phone": appointment.phone, "Date": appointment.date, "Time": appointment.time, "Service": appointment.service, } } try: response = requests.post( airtable_table_url(), headers=airtable_headers(), json=payload, timeout=20, ) except requests.RequestException as error: print("Airtable add request failed:", str(error)) raise HTTPException(status_code=502, detail="Failed to add appointment") print("Airtable add response:", response.status_code) if not response.ok: print("Airtable add error:", response.status_code, response.text) raise HTTPException(status_code=502, detail="Failed to add appointment") return response.json() class UpdateAppointment(BaseModel): appointment_id: str name: str | None = None phone: str | None = None date: str | None = None time: str | None = None service: str | None = None @app.post("/update") def update_appointment(update: UpdateAppointment): """Update an Airtable appointment using custom Appointment ID.""" record_id = find_airtable_record_by_appointment_id(update.appointment_id) if not record_id: return {"status": "error", "message": "Appointment not found"} fields = {} if update.name: fields["Name"] = update.name if update.phone: fields["Phone"] = update.phone if update.date: fields["Date"] = update.date if update.time: fields["Time"] = update.time if update.service: fields["Service"] = update.service if not fields: return {"status": "error", "message": "No fields provided to update"} try: response = requests.patch( f"{airtable_table_url()}/{record_id}", headers=airtable_headers(), json={"fields": fields}, timeout=20, ) except requests.RequestException as error: print("Airtable update request failed:", str(error)) raise HTTPException(status_code=502, detail="Update failed") print("Airtable update response:", response.status_code) if not response.ok: print("Airtable update error:", response.status_code, response.text) return {"status": "error", "message": "Update failed"} return {"status": "updated"} class CancelAppointment(BaseModel): appointment_id: str @app.post("/cancel") def cancel_appointment(cancel: CancelAppointment): """Cancel an Airtable appointment using custom Appointment ID.""" record_id = find_airtable_record_by_appointment_id(cancel.appointment_id) if not record_id: return {"status": "error", "message": "Appointment not found"} try: response = requests.delete( f"{airtable_table_url()}/{record_id}", headers=airtable_headers(), timeout=20, ) except requests.RequestException as error: print("Airtable delete request failed:", str(error)) raise HTTPException(status_code=502, detail="Delete failed") print("Airtable delete response:", response.status_code) if not response.ok: print("Airtable delete error:", response.status_code, response.text) return {"status": "error", "message": "Delete failed"} return {"status": "deleted"}