Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat(audio): add AI appointment booking voice agent (Telnyx Voice AI)

cyberholics90dc0ad38cfe
diff --git a/audio/ai_appointment_booking_voice_agent/.env.example b/audio/ai_appointment_booking_voice_agent/.env.example
new file mode 100644
index 0000000..36c6dd4
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/.env.example
@@ -0,0 +1,28 @@
+# Telnyx API key (starts with KEY...). Used for Inference and, optionally, SMS.
+# Get it at portal.telnyx.com -> API Keys.
+TELNYX_API_KEY=KEYxxxxxxxxxxxxxxxxxxxxxxxx
+
+# Telnyx Inference (OpenAI-compatible endpoint). Defaults are correct for Telnyx.
+INFERENCE_BASE_URL=https://api.telnyx.com/v2/ai/openai
+INFERENCE_MODEL=moonshotai/Kimi-K2.6
+
+# Business profile injected into the agent at call start (Dynamic Variables webhook).
+BUSINESS_NAME=Brightsmile Dental
+BUSINESS_HOURS=Mon-Fri, 9:00 AM to 5:00 PM
+BUSINESS_TIMEZONE=America/New_York
+BUSINESS_SERVICES=Checkup, Cleaning, Whitening, Emergency visit
+
+# Scheduling
+SLOT_LENGTH_MIN=30
+BOOKING_HORIZON_DAYS=14
+
+# Optional SMS follow-up. Leave SEND_SMS=false for a safe demo (no messages sent).
+# When true, the follow-up drafted by Inference is texted to the caller.
+SEND_SMS=false
+SMS_FROM=+15551230000
+
+# Storage and server
+DB_PATH=.data/appointments.db
+HOST=0.0.0.0
+PORT=8000
diff --git a/audio/ai_appointment_booking_voice_agent/.gitignore b/audio/ai_appointment_booking_voice_agent/.gitignore
new file mode 100644
index 0000000..1e0bfee
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/.gitignore
@@ -0,0 +1,18 @@
+# Environment
+.env
+
+# Local data (SQLite CRM store and generated calendar invites)
+.data/
+*.ics
+
+# Python
+__pycache__/
+*.py[cod]
+.venv/
+*.egg-info/
+.eggs/
+
+# OS / editor
+.DS_Store
+.idea/
+.vscode/
diff --git a/audio/ai_appointment_booking_voice_agent/README.md b/audio/ai_appointment_booking_voice_agent/README.md
new file mode 100644
index 0000000..20231ea
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/README.md
@@ -0,0 +1,306 @@
+# AI Appointment Booking Voice Agent (Telnyx Voice AI)
+
+![Demo](assets/demo.png)
+
+*The live demo page: call the agent from the widget on the left, and watch the booking and the AI-written follow-up appear on the right as the call happens.*
+
+A voice AI agent with a real phone number that books appointments over live phone
+calls. The agent answers, qualifies the request, checks open slots, books the
+appointment, generates a calendar invite, and stores a structured record in a
+lightweight CRM dashboard. When the call ends, Telnyx Inference writes a
+personalised follow-up message from the call summary.
+
+Voice, telephony, tool calls, and inference all run on one platform, one API key.
+
+## Overview
+
+Telnyx runs the hard real-time parts in the portal: speech-to-text, the model,
+text-to-speech, phone number routing, and conversation history. Your code owns
+four things that have to be yours:
+
+- The **live context** injected into the agent at the start of every call (today's
+ date, business hours, services), via a Dynamic Variables webhook.
+- The **tools** the scheduling agent calls: check availability and book an
+ appointment. These are webhook tools that POST to this FastAPI server.
+- The **calendar invite and CRM record** created when a booking succeeds.
+- The **post-call follow-up**, drafted by Telnyx Inference and stored (and
+ optionally texted back to the caller).
+
+**What the Telnyx portal handles:** STT, LLM inference, TTS, phone number routing,
+conversation history, and the post-call insight summary.
+
+**What this code handles:** dynamic context, the booking tools, calendar invites,
+the CRM dashboard, and the Inference-generated follow-up.
+
+## How It Works
+
+![How It Works](assets/how_it_works.png)
+
+1. A caller dials the Telnyx number. The agent answers and, at call start, Telnyx
+ calls the Dynamic Variables webhook so the agent knows today's date, the hours,
+ and the service list.
+2. The agent greets the caller, finds out which service they want and roughly when.
+3. It calls the **check-availability** tool. Telnyx POSTs the date to this server,
+ which returns open slots, and the agent offers a few out loud.
+4. The caller picks a time. The agent calls the **book-appointment** tool. The
+ server books the slot, writes a CRM record, and generates an `.ics` invite.
+5. The agent confirms the booking reference out loud and ends the call.
+6. Telnyx posts the call summary to the **call-summary** webhook. The server asks
+ Telnyx Inference to draft a personalised follow-up, stores it, and optionally
+ texts it to the caller. Everything shows up on the CRM dashboard.
+
+## Tech Stack
+
+| Layer | Tool |
+|---|---|
+| Voice and telephony | Telnyx Voice AI + a Telnyx phone number ($0.05/min bundled) |
+| Agent | A single Telnyx AI Assistant with webhook tools |
+| LLM | `moonshotai/Kimi-K2.6` via Telnyx (the recommended voice model) |
+| Inference (follow-up) | Telnyx Inference, OpenAI-compatible endpoint, `moonshotai/Kimi-K2.6` |
+| Tools and webhooks | FastAPI + Uvicorn |
+| Calendar | Hand-rolled iCalendar (`.ics`), no dependency |
+| CRM store and dashboard | SQLite + a single server-rendered HTML page |
+| Package manager | uv |
+
+## Prerequisites
+
+- Python 3.10 or higher
+- [uv](https://docs.astral.sh/uv/) (`pip install uv`)
+- [ngrok](https://ngrok.com) to expose your local webhooks during development
+- A [Telnyx account](https://portal.telnyx.com/sign-up) with a funded balance
+
+## Telnyx Portal Setup
+
+Everything below is done at [portal.telnyx.com](https://portal.telnyx.com). You
+build **one** AI Assistant that handles the whole call. Start the FastAPI server
+and ngrok first (see "Running" below) so you have your public URL ready, then
+paste it where the steps say `https://YOUR-NGROK.ngrok.io`.
+
+### Step 1: API key and phone number
+
+1. Copy your **API Key** (starts with `KEY...`) from the API Keys page. Put it in
+ `.env` as `TELNYX_API_KEY` (used for Inference and optional SMS).
+2. Buy a phone number (a US local number is fine).
+
+### Step 2: Create the assistant
+
+- Left sidebar -> **AI Suite** -> **Assistants** -> **Create**. Start from a blank
+ canvas (templates like Lead Qualification also exist).
+- **Name:** `Appointment Agent`.
+- **Model:** select `moonshotai/Kimi-K2.6` (the Recommended voice model in the
+ dropdown). Only third-party models (OpenAI, etc.) need an API key here.
+- **Instructions:**
+
+```
+You are the booking agent for {{business_name}}. Today is {{today_pretty}}.
+Hours are {{business_hours}}. Services offered: {{services}}.
+
+Keep replies under two sentences; callers are listening, not reading. Be warm
+and efficient.
+
+Handle the whole call:
+1. Greet the caller and find out which service they want and roughly when.
+2. Call check_availability with the date in YYYY-MM-DD format. Offer at most
+ three of the returned times, spoken naturally.
+3. When the caller picks a time, confirm their name, then call book_appointment
+ with their name, the service, and the exact start value from the slot you
+ offered.
+4. Read back the booking reference and the day and time, then say a calendar
+ invite and a text confirmation are on the way.
+
+Never invent a time that check_availability did not return. If there are no slots,
+offer another day. For a general question, answer briefly and offer to book.
+```
+
+- **Greeting:** `Thanks for calling {{business_name}}. How can I help you today?`
+- Save.
+
+### Step 3: Add the two webhook tools
+
+Every assistant can already hang up. To add yours, in the assistant's **Tools**
+area click the **"Add tool"** dropdown and choose **Webhook Tool**. Add two.
+
+**Tool 1: check_availability**
+
+- Name: `check_availability` (no spaces allowed)
+- Description: `Return open appointment slots for a date. Send date as YYYY-MM-DD and optional service.`
+- Method: `POST`
+- Timeout (ms): `5000`
+- URL: `https://YOUR-NGROK.ngrok.io/tools/check-availability`
+- Add the model-filled arguments as **Body Parameters**: `date`, `service`.
+
+**Tool 2: book_appointment**
+
+- Name: `book_appointment`
+- Description: `Book a chosen slot. Send name, service, and the exact start from check_availability.`
+- Method: `POST`
+- Timeout (ms): `5000`
+- URL: `https://YOUR-NGROK.ngrok.io/tools/book-appointment`
+- Body Parameters: `name`, `service`, `start`.
+
+The caller's phone number is read from the call metadata Telnyx includes in the
+tool request, so you do not need a phone parameter. There is also a top-level
+**AI Suite -> Tools** page for reusable tools you attach to any assistant; the
+inline "Add tool" dropdown above is the simpler path.
+
+### Step 4: Dynamic Variables webhook
+
+In the assistant config, set the **Dynamic variables Webhook URL** field to:
+
+```
+https://YOUR-NGROK.ngrok.io/webhooks/dynamic-variables
+```
+
+This is what fills `{{business_name}}`, `{{today_pretty}}`, `{{business_hours}}`,
+and `{{services}}` at call start, so the agent never quotes a stale date.
+
+### Step 5: Post-call summary webhook
+
+Open the assistant's **Insights** (post-conversation / post-call) settings and set
+the summary/insights webhook URL to:
+
+```
+https://YOUR-NGROK.ngrok.io/webhooks/call-summary
+```
+
+Telnyx posts the call summary here when the conversation ends. The server drafts
+the Inference follow-up and stores the record for the dashboard.
+
+### Step 6: Assign the number and test
+
+- Assign the phone number from Step 1 to the **Appointment Agent**.
+- Use the assistant's built-in **Test** button for a browser call with no phone,
+ or dial the number directly.
+
+## Installation
+
+```bash
+cd Hands-On-AI-Engineering/audio/ai_appointment_booking_voice_agent
+uv venv
+source .venv/bin/activate # Windows: .venv\Scripts\activate
+uv pip install -e .
+cp .env.example .env # then edit .env
+```
+
+Open `.env` and set `TELNYX_API_KEY`, plus the business profile
+(`BUSINESS_NAME`, `BUSINESS_HOURS`, `BUSINESS_SERVICES`) you want the agent to use.
+
+## Running
+
+Start the webhook server:
+
+```bash
+python main.py
+```
+
+The server starts at `http://127.0.0.1:8000` and serves the CRM dashboard at
+`http://localhost:8000/`.
+
+In a separate terminal, expose it with ngrok:
+
+```bash
+ngrok http 8000
+```
+
+Copy the HTTPS URL (for example `https://abc123.ngrok.io`) and paste it into the
+four webhook/tool URLs in the portal steps above. Verify the server is up:
+
+```bash
+curl http://localhost:8000/health
+```
+
+## Demo
+
+The main demo is a real phone call. Dial the Telnyx number assigned to the
+appointment agent, book an appointment out loud, and watch the booking and the
+post-call follow-up appear at `http://localhost:8000/`.
+
+### The demo page (`demo.html`)
+
+`demo.html` is an audience-facing demo screen. Open it in a browser while
+`python main.py` is running and it shows only the three things a viewer needs:
+a way to call the agent, the **appointments** as they get booked, and the
+**personalised follow-up** after each call. It refreshes every few seconds from
+the server's read-only `/api/*` endpoints.
+
+To wire the call button, open `demo.html` and set the widget's **agent-id** to
+your assistant's ID:
+
+```html
+<telnyx-ai-agent agent-id="assistant-XXXXXXXX-...." environment="production"></telnyx-ai-agent>
+```
+
+Find the ID on the assistant page in the portal (AI Suite -> Assistants -> your
+assistant); it looks like `assistant-` followed by a UUID. The widget itself
+loads from Telnyx's CDN via the `@telnyx/ai-agent-widget` script already in the
+file, so a viewer can click and talk to the agent right on the page.
+
+Change `API_BASE` at the bottom of the file only if the server runs somewhere
+other than `localhost:8000`. CORS is open on the server for local demo use.
+
+The project ships with a fictional business and the CRM only ever holds the
+inputs from your own test calls. Keep it that way for any recording: demo data
+only, no real customer details.
+
+While you demo, keep the terminal running `python main.py` on screen. It prints
+every tool call and its response as JSON, so viewers see the agent read the open
+slots and write the booking in real time.
+
+### A call that shows everything
+
+1. "Hi, I'd like to book a cleaning sometime Thursday."
+2. The agent calls check_availability and offers three Thursday times.
+3. "10:30 works, my name is Alex." (the agent calls book_appointment)
+4. The agent reads back the reference, an `.ics` invite is written, the CRM row
+ appears.
+5. Call ends. Telnyx posts the summary, Inference drafts the follow-up, and it
+ lands on the dashboard.
+
+## Project Structure
+
+```
+ai_appointment_booking_voice_agent/
+├── main.py # FastAPI: webhook tools, post-call handler, CRM dashboard
+├── appointment_agent/
+│ ├── config.py # env settings (business profile, model, scheduling rules)
+│ ├── scheduling.py # open-slot logic and booking
+│ ├── crm.py # SQLite store (appointments + call summaries)
+│ ├── calendar_invite.py # hand-rolled .ics generation
+│ └── inference.py # Telnyx Inference follow-up + optional SMS
+├── demo.html # live demo page (call widget + bookings + follow-ups)
+├── assets/ # demo.png and how_it_works.png
+├── pyproject.toml
+├── .env.example
+├── .gitignore
+└── README.md
+```
+
+## Customising
+
+- **Swap the model.** Set the assistant model in the portal from the models your
+ account offers. `moonshotai/Kimi-K2.6` is the recommended voice model; other
+ self-hosted options like `Qwen/Qwen3-235B-A22B` or `zai-org/GLM-5.2` also work.
+ The follow-up model is `INFERENCE_MODEL` in `.env`.
+- **Change the business.** `BUSINESS_NAME`, `BUSINESS_HOURS`, `BUSINESS_SERVICES`,
+ and the open/close hours all live in `.env`. No code change.
+- **Use a real calendar.** `scheduling.py` is deliberately isolated. Point
+ `available_slots()` and `book()` at Google Calendar, Outlook, or Cal.com and
+ the webhook layer does not change.
+- **Turn on SMS.** Set `SEND_SMS=true` and `SMS_FROM` to a Telnyx number to text
+ the Inference follow-up to the caller.
+
+## What a call costs
+
+Telnyx bundles Voice AI (SIP + STT + LLM + TTS) at $0.05 per minute, with
+telephony itemised on top (inbound from $0.0032 per minute). A real five-minute
+call that books an appointment lands around $0.30, so $25 in signup credits is
+roughly 80 booking calls. Telnyx Inference is up to 75% less than closed-model
+APIs.
+
+## Resources
+
+- Telnyx AI Assistants: https://developers.telnyx.com/docs/inference/ai-assistants
+- AI Assistant widget: https://developers.telnyx.com/docs/inference/ai-assistants/ai-agent-widget
+- Telnyx Inference (OpenAI-compatible): https://developers.telnyx.com/docs/inference
+- API reference: https://developers.telnyx.com/api-reference/overview
+- Telnyx Portal: https://portal.telnyx.com
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/__init__.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/__init__.py
new file mode 100644
index 0000000..dfe8e95
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/__init__.py
@@ -0,0 +1 @@
+"""Telnyx appointment-booking voice agent: webhook tools, scheduling, CRM, and Inference follow-up."""
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/calendar_invite.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/calendar_invite.py
new file mode 100644
index 0000000..e8b45b1
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/calendar_invite.py
@@ -0,0 +1,56 @@
+"""
+Generate an iCalendar (.ics) invite for a booking.
+
+Hand-rolled so there is no extra dependency. Times are written as local
+wall-clock (floating) time, which every calendar app reads as the viewer's
+local time. Good enough for a demo invite; add a VTIMEZONE block if you need
+strict timezone handling.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from appointment_agent.config import SETTINGS
+
+_ICS_DIR = SETTINGS.db_path.parent / "invites"
+
+
+def _ics_stamp(iso: str) -> str:
+ return datetime.strptime(iso[:19], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%dT%H%M%S")
+
+
+def build_invite(booking: dict) -> tuple[str, Path]:
+ """Return (ics_text, path_on_disk) for a booking dict from scheduling.book()."""
+ ref = booking["booking_ref"]
+ summary = f"{booking['service']} at {SETTINGS.business_name}"
+ description = (
+ f"Booking reference {ref}. "
+ f"Booked for {booking['name']} ({booking['phone']})."
+ )
+
+ lines = [
+ "BEGIN:VCALENDAR",
+ "VERSION:2.0",
+ "PRODID:-//Telnyx Appointment Agent//EN",
+ "CALSCALE:GREGORIAN",
+ "METHOD:PUBLISH",
+ "BEGIN:VEVENT",
+ f"UID:{ref}@telnyx-appointment-agent",
+ f"DTSTAMP:{datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')}",
+ f"DTSTART:{_ics_stamp(booking['start'])}",
+ f"DTEND:{_ics_stamp(booking['end'])}",
+ f"SUMMARY:{summary}",
+ f"DESCRIPTION:{description}",
+ f"LOCATION:{SETTINGS.business_name}",
+ "STATUS:CONFIRMED",
+ "END:VEVENT",
+ "END:VCALENDAR",
+ ]
+ ics_text = "\r\n".join(lines) + "\r\n"
+
+ _ICS_DIR.mkdir(parents=True, exist_ok=True)
+ path = _ICS_DIR / f"{ref}.ics"
+ path.write_text(ics_text, encoding="utf-8")
+ return ics_text, path
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/config.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/config.py
new file mode 100644
index 0000000..a808378
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/config.py
@@ -0,0 +1,69 @@
+"""
+Runtime configuration, resolved from environment variables (see .env.example).
+
+Nothing is hardcoded: the business profile, model, and scheduling rules all come
+from the environment so the same code runs for any front desk.
+"""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+
+def _csv(value: str) -> list[str]:
+ return [item.strip() for item in value.split(",") if item.strip()]
+
+
+@dataclass(frozen=True)
+class Settings:
+ """All runtime settings, resolved from the environment with sane defaults."""
+
+ # Telnyx (cloud). The API key is used for Inference and optional SMS.
+ telnyx_api_key: str = os.getenv("TELNYX_API_KEY", "")
+ inference_base_url: str = os.getenv("INFERENCE_BASE_URL", "https://api.telnyx.com/v2/ai/openai")
+ inference_model: str = os.getenv("INFERENCE_MODEL", "moonshotai/Kimi-K2.6")
+
+ # Business profile, injected into the agent prompt at call start.
+ business_name: str = os.getenv("BUSINESS_NAME", "Brightsmile Dental")
+ business_hours: str = os.getenv("BUSINESS_HOURS", "Mon-Fri, 9:00 AM to 5:00 PM")
+ business_timezone: str = os.getenv("BUSINESS_TIMEZONE", "America/New_York")
+ support_email: str = os.getenv("SUPPORT_EMAIL", "[email protected]")
+ services: list[str] = field(
+ default_factory=lambda: _csv(
+ os.getenv("BUSINESS_SERVICES", "Checkup, Cleaning, Whitening, Emergency visit")
+ )
+ )
+
+ # Scheduling rules.
+ slot_length_min: int = int(os.getenv("SLOT_LENGTH_MIN", "30"))
+ booking_horizon_days: int = int(os.getenv("BOOKING_HORIZON_DAYS", "14"))
+ open_hour: int = int(os.getenv("OPEN_HOUR", "9"))
+ close_hour: int = int(os.getenv("CLOSE_HOUR", "17"))
+
+ # Optional SMS follow-up. Off by default so the demo sends nothing.
+ send_sms: bool = os.getenv("SEND_SMS", "false").lower() == "true"
+ sms_from: str = os.getenv("SMS_FROM", "")
+
+ # Storage and server.
+ db_path: Path = Path(os.getenv("DB_PATH", ".data/appointments.db"))
+ host: str = os.getenv("HOST", "0.0.0.0")
+ port: int = int(os.getenv("PORT", "8000"))
+
+
+SETTINGS = Settings()
+
+
+def require_api_key() -> str:
+ """Return the Telnyx API key or raise a clear error if it is missing."""
+ if not SETTINGS.telnyx_api_key:
+ raise RuntimeError(
+ "TELNYX_API_KEY is not set. Copy .env.example to .env and add your key "
+ "from portal.telnyx.com -> API Keys."
+ )
+ return SETTINGS.telnyx_api_key
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/crm.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/crm.py
new file mode 100644
index 0000000..c086d6f
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/crm.py
@@ -0,0 +1,132 @@
+"""
+Lightweight CRM store backed by SQLite.
+
+Two tables: appointments (what got booked) and call_summaries (the structured
+post-call record plus the Inference-generated follow-up). A single file on disk
+is the whole database, which is all a demo front desk needs.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from contextlib import contextmanager
+from datetime import datetime, timezone
+from typing import Iterator
+
+from appointment_agent.config import SETTINGS
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+@contextmanager
+def _connect() -> Iterator[sqlite3.Connection]:
+ SETTINGS.db_path.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(SETTINGS.db_path)
+ conn.row_factory = sqlite3.Row
+ try:
+ yield conn
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def init_db() -> None:
+ """Create tables if they do not exist. Safe to call on every startup."""
+ with _connect() as conn:
+ conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS appointments (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ booking_ref TEXT UNIQUE NOT NULL,
+ caller_name TEXT NOT NULL,
+ caller_phone TEXT NOT NULL,
+ service TEXT NOT NULL,
+ start_iso TEXT NOT NULL,
+ end_iso TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'booked',
+ created_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS call_summaries (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ conversation_id TEXT,
+ caller_phone TEXT,
+ summary TEXT,
+ structured_json TEXT,
+ follow_up TEXT,
+ created_at TEXT NOT NULL
+ );
+ """
+ )
+
+
+def is_slot_taken(start_iso: str) -> bool:
+ with _connect() as conn:
+ row = conn.execute(
+ "SELECT 1 FROM appointments WHERE start_iso = ? AND status = 'booked' LIMIT 1",
+ (start_iso,),
+ ).fetchone()
+ return row is not None
+
+
+def add_appointment(
+ booking_ref: str,
+ caller_name: str,
+ caller_phone: str,
+ service: str,
+ start_iso: str,
+ end_iso: str,
+) -> None:
+ with _connect() as conn:
+ conn.execute(
+ """
+ INSERT INTO appointments
+ (booking_ref, caller_name, caller_phone, service, start_iso, end_iso, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'booked', ?)
+ """,
+ (booking_ref, caller_name, caller_phone, service, start_iso, end_iso, _now_iso()),
+ )
+
+
+def list_appointments() -> list[dict]:
+ with _connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM appointments ORDER BY start_iso DESC"
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+
+def add_summary(
+ conversation_id: str | None,
+ caller_phone: str | None,
+ summary: str | None,
+ structured: dict | None,
+ follow_up: str | None,
+) -> None:
+ with _connect() as conn:
+ conn.execute(
+ """
+ INSERT INTO call_summaries
+ (conversation_id, caller_phone, summary, structured_json, follow_up, created_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ """,
+ (
+ conversation_id,
+ caller_phone,
+ summary,
+ json.dumps(structured) if structured is not None else None,
+ follow_up,
+ _now_iso(),
+ ),
+ )
+
+
+def list_summaries() -> list[dict]:
+ with _connect() as conn:
+ rows = conn.execute(
+ "SELECT * FROM call_summaries ORDER BY created_at DESC"
+ ).fetchall()
+ return [dict(row) for row in rows]
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/inference.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/inference.py
new file mode 100644
index 0000000..40ce6f3
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/inference.py
@@ -0,0 +1,61 @@
+"""
+Post-call intelligence, powered by Telnyx Inference.
+
+After a call ends, we ask a Telnyx-hosted model to write a short, personalised
+follow-up message from the structured call record. The endpoint is
+OpenAI-compatible, so the official `openai` client works with just the base URL
+and API key swapped. Optionally the follow-up is texted back to the caller
+through the Telnyx Messaging API.
+"""
+
+from __future__ import annotations
+
+import httpx
+from openai import OpenAI
+
+from appointment_agent.config import SETTINGS, require_api_key
+
+_SYSTEM_PROMPT = (
+ "You write short, warm SMS follow-ups for a business front desk. "
+ "Two sentences maximum. No emojis. Confirm the key detail and sign off "
+ "with the business name. Never invent details that are not provided."
+)
+
+
+def _client() -> OpenAI:
+ return OpenAI(base_url=SETTINGS.inference_base_url, api_key=require_api_key())
+
+
+def generate_follow_up(context: str) -> str:
+ """Draft a personalised follow-up message from a plain-text call context."""
+ response = _client().chat.completions.create(
+ model=SETTINGS.inference_model,
+ messages=[
+ {"role": "system", "content": _SYSTEM_PROMPT},
+ {
+ "role": "user",
+ "content": (
+ f"Business: {SETTINGS.business_name}\n"
+ f"Call context:\n{context}\n\n"
+ "Write the follow-up message."
+ ),
+ },
+ ],
+ temperature=0.4,
+ max_tokens=160,
+ )
+ return (response.choices[0].message.content or "").strip()
+
+
+def send_sms(to_number: str, text: str) -> dict:
+ """Send the follow-up via the Telnyx Messaging API. Only called when SEND_SMS=true."""
+ if not SETTINGS.sms_from:
+ raise RuntimeError("SMS_FROM is not set. Add a Telnyx number to send SMS.")
+ resp = httpx.post(
+ "https://api.telnyx.com/v2/messages",
+ headers={"Authorization": f"Bearer {require_api_key()}"},
+ json={"from": SETTINGS.sms_from, "to": to_number, "text": text},
+ timeout=20.0,
+ )
+ resp.raise_for_status()
+ return resp.json()
diff --git a/audio/ai_appointment_booking_voice_agent/appointment_agent/scheduling.py b/audio/ai_appointment_booking_voice_agent/appointment_agent/scheduling.py
new file mode 100644
index 0000000..d6176a8
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/appointment_agent/scheduling.py
@@ -0,0 +1,82 @@
+"""
+Slot logic for the scheduling agent.
+
+Slots are generated from the business hours in config, filtered against what is
+already booked in the CRM store. Times are treated as local wall-clock time for
+the business; that is all a front-desk demo needs, and it keeps the calendar
+invite readable. Swap this module for a real calendar API (Google, Outlook,
+Cal.com) without touching the webhook layer.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timedelta
+
+from appointment_agent import crm
+from appointment_agent.config import SETTINGS
+
+_TIME_FMT = "%Y-%m-%dT%H:%M:%S"
+
+
+def _parse_date(date_str: str) -> datetime:
+ """Accept YYYY-MM-DD (preferred) or a full ISO datetime and return midnight of that day."""
+ date_str = date_str.strip()
+ for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M"):
+ try:
+ dt = datetime.strptime(date_str[: len(fmt) + 2] if "T" in fmt else date_str, fmt)
+ return dt.replace(hour=0, minute=0, second=0, microsecond=0)
+ except ValueError:
+ continue
+ raise ValueError(f"Could not parse date: {date_str!r}. Use YYYY-MM-DD.")
+
+
+def available_slots(date_str: str, service: str | None = None) -> list[dict]:
+ """Return the open slots for a given date as a list of {start, end, label}."""
+ day = _parse_date(date_str)
+ now = datetime.now()
+
+ slots: list[dict] = []
+ cursor = day.replace(hour=SETTINGS.open_hour)
+ end_of_day = day.replace(hour=SETTINGS.close_hour)
+ step = timedelta(minutes=SETTINGS.slot_length_min)
+
+ while cursor + step <= end_of_day:
+ start_iso = cursor.strftime(_TIME_FMT)
+ end_iso = (cursor + step).strftime(_TIME_FMT)
+ is_past = cursor <= now
+ if not is_past and not crm.is_slot_taken(start_iso):
+ slots.append(
+ {
+ "start": start_iso,
+ "end": end_iso,
+ "label": cursor.strftime("%A %B %d, %I:%M %p"),
+ }
+ )
+ cursor += step
+
+ return slots
+
+
+def book(name: str, phone: str, service: str, start: str) -> dict:
+ """Book a slot. `start` is an ISO datetime (YYYY-MM-DDTHH:MM:SS). Idempotent per slot."""
+ start_dt = datetime.strptime(start[:19], _TIME_FMT)
+ end_dt = start_dt + timedelta(minutes=SETTINGS.slot_length_min)
+ start_iso = start_dt.strftime(_TIME_FMT)
+ end_iso = end_dt.strftime(_TIME_FMT)
+
+ if crm.is_slot_taken(start_iso):
+ raise ValueError("That time was just taken. Offer the caller another slot.")
+
+ booking_ref = f"APT-{uuid.uuid4().hex[:8].upper()}"
+ crm.add_appointment(booking_ref, name, phone, service, start_iso, end_iso)
+
+ return {
+ "booking_ref": booking_ref,
+ "name": name,
+ "phone": phone,
+ "service": service,
+ "start": start_iso,
+ "end": end_iso,
+ "label": start_dt.strftime("%A %B %d, %I:%M %p"),
+ }
diff --git a/audio/ai_appointment_booking_voice_agent/assets/demo.png b/audio/ai_appointment_booking_voice_agent/assets/demo.png
new file mode 100644
index 0000000..30f83ed
Binary files /dev/null and b/audio/ai_appointment_booking_voice_agent/assets/demo.png differ
diff --git a/audio/ai_appointment_booking_voice_agent/assets/how_it_works.png b/audio/ai_appointment_booking_voice_agent/assets/how_it_works.png
new file mode 100644
index 0000000..a934cc7
Binary files /dev/null and b/audio/ai_appointment_booking_voice_agent/assets/how_it_works.png differ
diff --git a/audio/ai_appointment_booking_voice_agent/demo.html b/audio/ai_appointment_booking_voice_agent/demo.html
new file mode 100644
index 0000000..b6b90f1
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/demo.html
@@ -0,0 +1,125 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>AI Appointment Booking Voice Agent</title>
+ <style>
+ *, *::before, *::after { box-sizing:border-box; margin:0; padding:0; }
+ :root { --accent:#4f46e5; --ink:#1e293b; --muted:#64748b; --line:#e5e7eb; --bg:#f5f7fb; }
+ body { font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
+ background:var(--bg); min-height:100vh; color:var(--ink); padding:40px 24px; }
+ .hero { text-align:center; max-width:640px; margin:0 auto 32px; }
+ .badge { display:inline-block; background:#eef2ff; color:#4338ca; font-size:12px; font-weight:600;
+ padding:4px 12px; border-radius:999px; margin-bottom:14px; letter-spacing:.3px;
+ border:1px solid #c7d2fe; }
+ h1 { font-size:28px; font-weight:700; color:#0f172a; line-height:1.3; }
+ .hero p { margin-top:8px; color:var(--muted); font-size:14px; }
+ .widget-wrap { display:flex; justify-content:center; margin-top:22px; }
+ .widget-hint { text-align:center; font-size:12px; color:var(--muted); margin-top:10px; }
+ main { max-width:1020px; margin:0 auto; display:grid; grid-template-columns:1fr 1fr; gap:20px; }
+ @media (max-width:820px){ main { grid-template-columns:1fr; } }
+ .card { background:#fff; border:1px solid var(--line); border-radius:14px; padding:20px;
+ box-shadow:0 1px 2px rgba(15,23,42,.04); }
+ .card h2 { font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted); margin-bottom:14px; }
+ table { width:100%; border-collapse:collapse; }
+ th,td { text-align:left; padding:9px 10px; font-size:13px; border-bottom:1px solid var(--line); }
+ th { font-size:11px; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }
+ tr:last-child td { border-bottom:none; }
+ code { color:var(--accent); font-weight:600; }
+ .pill { background:#dcfce7; color:#166534; padding:2px 9px; border-radius:999px; font-size:11px; font-weight:600; }
+ .sum { border:1px solid var(--line); border-radius:10px; padding:12px 14px; margin-bottom:10px; }
+ .sum .meta { font-size:12px; color:var(--muted); margin-bottom:6px; }
+ .sum .follow { background:#eef2ff; color:#3730a3; padding:9px 11px; border-radius:8px;
+ font-size:13px; margin-top:8px; line-height:1.5; }
+ .empty { color:#94a3b8; font-size:13px; padding:14px 0; }
+ #err { display:none; color:#b91c1c; font-size:12px; text-align:center; margin:10px 0; }
+ .footer { margin-top:32px; font-size:12px; color:#94a3b8; text-align:center; }
+ </style>
+</head>
+<body>
+
+ <div class="hero">
+ <div class="badge">Live Demo</div>
+ <h1>AI Appointment Booking Voice Agent</h1>
+ <p>Call the agent and book an appointment. It appears below the moment it is booked.</p>
+
+ <div class="widget-wrap">
+ <!-- Replace agent-id with your assistant's ID (portal -> AI Suite -> Assistants
+ -> your assistant). It looks like assistant-XXXXXXXX-.... Until you set a
+ real ID here, the call button will just spin. -->
+ <telnyx-ai-agent
+ agent-id="assistant-2f6780ae-e317-4090-9c29-82ca66d09946"
+ environment="production">
+ </telnyx-ai-agent>
+ <script async src="https://unpkg.com/@telnyx/ai-agent-widget@next"></script>
+ </div>
+ <div class="widget-hint">Click the call button above, or dial your Telnyx number.</div>
+ </div>
+
+ <div id="err">Waiting for the local server (run <code>python main.py</code>)…</div>
+
+ <main>
+ <div class="card">
+ <h2>Appointments booked</h2>
+ <table>
+ <thead><tr><th>Ref</th><th>Name</th><th>Service</th><th>When</th><th>Status</th></tr></thead>
+ <tbody id="appts"><tr><td colspan="5" class="empty">No bookings yet. Make a call.</td></tr></tbody>
+ </table>
+ </div>
+ <div class="card">
+ <h2>Personalised follow-up</h2>
+ <div id="summaries"><div class="empty">Appears after a call ends.</div></div>
+ </div>
+ </main>
+
+ <p class="footer">
+ Built with Telnyx AI Assistant Builder &middot; FastAPI webhook tools &middot; Kimi K2.6
+ </p>
+
+ <script>
+ // ---------- CONFIG ----------
+ const API_BASE = "http://localhost:8000"; // where python main.py is running
+ const REFRESH_MS = 4000;
+ // ----------------------------
+
+ const esc = (s) => (s ?? "").toString().replace(/[&<>"]/g, c =>
+ ({ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;" }[c]));
+
+ function fmt(iso) {
+ const d = new Date((iso || "").slice(0, 19));
+ return isNaN(d) ? (iso || "") : d.toLocaleString(undefined,
+ { weekday:"short", month:"short", day:"numeric", hour:"numeric", minute:"2-digit" });
+ }
+
+ async function refresh() {
+ try {
+ const [appts, sums] = await Promise.all([
+ fetch(`${API_BASE}/api/appointments`).then(r => r.json()),
+ fetch(`${API_BASE}/api/summaries`).then(r => r.json()),
+ ]);
+ document.getElementById("err").style.display = "none";
+
+ document.getElementById("appts").innerHTML = appts.length ? appts.map(a => `
+ <tr><td><code>${esc(a.booking_ref)}</code></td><td>${esc(a.caller_name)}</td>
+ <td>${esc(a.service)}</td><td>${fmt(a.start_iso)}</td>
+ <td><span class="pill">${esc(a.status)}</span></td></tr>`).join("")
+ : `<tr><td colspan="5" class="empty">No bookings yet. Make a call.</td></tr>`;
+
+ document.getElementById("summaries").innerHTML = sums.length ? sums.map(s => `
+ <div class="sum">
+ <div class="meta">${fmt(s.created_at)}</div>
+ <div>${esc(s.summary || "Call summary")}</div>
+ ${s.follow_up ? `<div class="follow">${esc(s.follow_up)}</div>` : ""}
+ </div>`).join("")
+ : `<div class="empty">Appears after a call ends.</div>`;
+ } catch (e) {
+ document.getElementById("err").style.display = "block";
+ }
+ }
+
+ refresh();
+ setInterval(refresh, REFRESH_MS);
+ </script>
+</body>
+</html>
diff --git a/audio/ai_appointment_booking_voice_agent/main.py b/audio/ai_appointment_booking_voice_agent/main.py
new file mode 100644
index 0000000..86813dc
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/main.py
@@ -0,0 +1,362 @@
+"""
+Telnyx AI Appointment Booking Voice Agent -- webhook backend, tools, and CRM dashboard.
+
+Telnyx runs the voice, the models, and the telephony in the portal. This FastAPI
+server contributes the parts that have to live in your code:
+
+ POST /webhooks/dynamic-variables -> live context injected at call start
+ POST /tools/check-availability -> tool the scheduling agent calls to read open slots
+ POST /tools/book-appointment -> tool that books a slot, makes an .ics, writes to the CRM
+ POST /webhooks/call-summary -> post-call record + Inference-generated follow-up
+ GET / -> lightweight CRM dashboard
+ GET /health -> readiness check
+
+Run with: uvicorn main:app --reload (or: python main.py)
+"""
+
+from __future__ import annotations
+
+import html
+import json
+import logging
+from datetime import date, datetime
+from pathlib import Path
+from typing import Any
+
+from fastapi import FastAPI, Request
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
+
+from appointment_agent import crm, inference, scheduling
+from appointment_agent.calendar_invite import build_invite
+from appointment_agent.config import SETTINGS
+
+# Log every tool call and its result to the console. This is the "show the
+# payload live" view: keep this terminal on screen during a demo.
+logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%H:%M:%S")
+log = logging.getLogger("appointment-agent")
+
+
+def _trace(label: str, data: Any) -> None:
+ log.info("%s %s", label, json.dumps(data, default=str)[:1000])
+
+
+app = FastAPI(title="Telnyx AI Appointment Booking Voice Agent")
+
+# Allow the local demo page (opened as a file, or from any localhost port) to
+# read the live JSON endpoints. This is a local demo server, not a public API.
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
[email protected]_event("startup")
+def _startup() -> None:
+ crm.init_db()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _extract_args(body: dict[str, Any]) -> dict[str, Any]:
+ """
+ Pull the tool arguments out of a Telnyx tool-call webhook body.
+
+ Telnyx posts the tool arguments when the model calls a tool. Different
+ surfaces nest them slightly differently, so we look in the common places
+ and fall back to the top-level body.
+ """
+ for key in ("arguments", "parameters", "data", "payload"):
+ value = body.get(key)
+ if isinstance(value, dict):
+ return value
+ return body
+
+
+def _caller_phone(body: dict[str, Any], args: dict[str, Any]) -> str:
+ for key in ("telnyx_end_user_target", "from", "caller_number", "phone", "caller_phone"):
+ value = body.get(key) or args.get(key)
+ if value:
+ return str(value)
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# Health
+# ---------------------------------------------------------------------------
+
+def health() -> dict[str, str]:
+ return {"status": "ok", "service": "telnyx-appointment-agent"}
+
+
+def demo_page() -> FileResponse:
+ """Serve the demo page over http://localhost:8000/demo (a secure context, so
+ the voice widget's microphone works, unlike opening the file directly)."""
+ return FileResponse(Path(__file__).parent / "demo.html")
+
+
+# ---------------------------------------------------------------------------
+# JSON API (read-only) used by the live demo page
+# ---------------------------------------------------------------------------
+
[email protected]("/api/appointments")
+def api_appointments() -> list[dict]:
+ return crm.list_appointments()
+
+
[email protected]("/api/summaries")
+def api_summaries() -> list[dict]:
+ return crm.list_summaries()
+
+
[email protected]("/api/business")
+def api_business() -> dict[str, Any]:
+ return {
+ "business_name": SETTINGS.business_name,
+ "business_hours": SETTINGS.business_hours,
+ "services": SETTINGS.services,
+ "model": SETTINGS.inference_model,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Dynamic variables webhook: live context injected into the agent prompt
+# ---------------------------------------------------------------------------
+
[email protected]("/webhooks/dynamic-variables")
+async def dynamic_variables(request: Request) -> JSONResponse:
+ """
+ Telnyx calls this at the start of every call. The returned values fill the
+ {{placeholders}} in the assistant's instructions, so the agent always knows
+ the current date, hours, and services without redeploying anything.
+ """
+ today = date.today()
+ variables = {
+ "business_name": SETTINGS.business_name,
+ "business_hours": SETTINGS.business_hours,
+ "business_timezone": SETTINGS.business_timezone,
+ "services": ", ".join(SETTINGS.services),
+ "support_email": SETTINGS.support_email,
+ "today": today.isoformat(),
+ "today_pretty": today.strftime("%A %B %d, %Y"),
+ "booking_horizon_days": str(SETTINGS.booking_horizon_days),
+ }
+ # Telnyx reads the returned JSON object directly as the map of dynamic
+ # variables (flat, top-level keys), so return it as-is -- not nested.
+ return JSONResponse(variables)
+
+
+# ---------------------------------------------------------------------------
+# Tool: check availability
+# ---------------------------------------------------------------------------
+
[email protected]("/tools/check-availability")
+async def check_availability(request: Request) -> JSONResponse:
+ """Tool the scheduling agent calls to read open slots for a date."""
+ body = await request.json()
+ args = _extract_args(body)
+ _trace("check_availability <-", args)
+
+ date_str = str(args.get("date") or date.today().isoformat())
+ service = args.get("service")
+
+ try:
+ slots = scheduling.available_slots(date_str, service)
+ except ValueError as exc:
+ return JSONResponse({"error": str(exc), "available": []})
+
+ # Keep the payload small: the model only needs a few options to offer.
+ top = slots[:6]
+ result = {
+ "date": date_str,
+ "service": service,
+ "count": len(slots),
+ "available": top,
+ "message": (
+ f"{len(slots)} open slots on {date_str}."
+ if slots
+ else f"No open slots on {date_str}. Offer another day."
+ ),
+ }
+ _trace("check_availability ->", result)
+ return JSONResponse(result)
+
+
+# ---------------------------------------------------------------------------
+# Tool: book appointment
+# ---------------------------------------------------------------------------
+
[email protected]("/tools/book-appointment")
+async def book_appointment(request: Request) -> JSONResponse:
+ """Tool that books a slot, generates a calendar invite, and writes to the CRM."""
+ body = await request.json()
+ args = _extract_args(body)
+ _trace("book_appointment <-", args)
+
+ name = str(args.get("name") or args.get("caller_name") or "").strip()
+ service = str(args.get("service") or "").strip()
+ start = str(args.get("start") or args.get("start_time") or "").strip()
+ phone = _caller_phone(body, args)
+
+ missing = [f for f, v in {"name": name, "service": service, "start": start}.items() if not v]
+ if missing:
+ return JSONResponse(
+ {"success": False, "error": f"Missing required fields: {', '.join(missing)}."}
+ )
+
+ try:
+ booking = scheduling.book(name=name, phone=phone, service=service, start=start)
+ except ValueError as exc:
+ return JSONResponse({"success": False, "error": str(exc)})
+
+ _, ics_path = build_invite(booking)
+
+ result = {
+ "success": True,
+ "booking_ref": booking["booking_ref"],
+ "confirmed_for": booking["label"],
+ "service": booking["service"],
+ "calendar_invite": str(ics_path.name),
+ "message": (
+ f"Booked {booking['service']} for {booking['label']}. "
+ f"Reference {booking['booking_ref']}."
+ ),
+ }
+ _trace("book_appointment ->", result)
+ return JSONResponse(result)
+
+
+# ---------------------------------------------------------------------------
+# Post-call webhook: structured summary + Inference-generated follow-up
+# ---------------------------------------------------------------------------
+
[email protected]("/webhooks/call-summary")
+async def call_summary(request: Request) -> JSONResponse:
+ """
+ Telnyx posts a conversation insight / summary after the call ends (configure
+ this URL under the assistant's Insights / post-conversation settings). We
+ store the record, ask Telnyx Inference to draft a personalised follow-up,
+ and optionally text it to the caller.
+ """
+ body = await request.json()
+ data = body.get("data", body)
+ payload = data.get("payload", data) if isinstance(data, dict) else {}
+
+ conversation_id = payload.get("conversation_id") or payload.get("id")
+ caller_phone = _caller_phone(payload, payload)
+ summary = (
+ payload.get("summary")
+ or payload.get("conversation_summary")
+ or payload.get("transcript")
+ or ""
+ )
+ structured = payload.get("insights") or payload.get("extracted_data") or payload
+
+ context = summary if summary else str(structured)[:2000]
+
+ follow_up = ""
+ try:
+ follow_up = inference.generate_follow_up(context)
+ if SETTINGS.send_sms and caller_phone:
+ inference.send_sms(caller_phone, follow_up)
+ except Exception as exc: # noqa: BLE001 - never fail the webhook on a follow-up error
+ follow_up = f"[follow-up generation skipped: {exc}]"
+
+ crm.add_summary(
+ conversation_id=conversation_id,
+ caller_phone=caller_phone,
+ summary=summary or None,
+ structured=structured if isinstance(structured, dict) else None,
+ follow_up=follow_up,
+ )
+ _trace("call_summary ->", {"conversation_id": conversation_id, "follow_up": follow_up})
+ return JSONResponse({"received": True, "follow_up": follow_up})
+
+
+# ---------------------------------------------------------------------------
+# CRM dashboard
+# ---------------------------------------------------------------------------
+
+def _fmt(iso: str) -> str:
+ try:
+ return datetime.strptime(iso[:19], "%Y-%m-%dT%H:%M:%S").strftime("%a %b %d, %I:%M %p")
+ except (ValueError, TypeError):
+ return iso or ""
+
+
[email protected]("/", response_class=HTMLResponse)
+def dashboard() -> str:
+ appts = crm.list_appointments()
+ summaries = crm.list_summaries()
+
+ appt_rows = "".join(
+ f"<tr><td><code>{html.escape(a['booking_ref'])}</code></td>"
+ f"<td>{html.escape(a['caller_name'])}</td>"
+ f"<td>{html.escape(a['caller_phone'] or '')}</td>"
+ f"<td>{html.escape(a['service'])}</td>"
+ f"<td>{_fmt(a['start_iso'])}</td>"
+ f"<td><span class='pill'>{html.escape(a['status'])}</span></td></tr>"
+ for a in appts
+ ) or "<tr><td colspan='6' class='empty'>No appointments yet. Call the agent to book one.</td></tr>"
+
+ summary_cards = "".join(
+ f"<div class='card'>"
+ f"<div class='muted'>{_fmt(s['created_at'])} &middot; {html.escape(s['caller_phone'] or 'unknown caller')}</div>"
+ f"<p>{html.escape(s['summary'] or 'No summary text.')}</p>"
+ f"<div class='followup'><strong>Follow-up (Telnyx Inference)</strong><br>{html.escape(s['follow_up'] or '')}</div>"
+ f"</div>"
+ for s in summaries
+ ) or "<div class='empty'>No call summaries yet.</div>"
+
+ return f"""<!doctype html>
+<html lang="en"><head><meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>{html.escape(SETTINGS.business_name)} · Front Desk CRM</title>
+<style>
+ :root {{ --bg:#0F172A; --ink:#1E293B; --accent:#4F46E5; --line:#E5E7EB; }}
+ * {{ box-sizing:border-box; }}
+ body {{ margin:0; font-family:-apple-system,Segoe UI,Roboto,sans-serif; color:var(--ink); background:#F8FAFC; }}
+ header {{ background:linear-gradient(135deg,#0F172A,#1E1B4B); color:#fff; padding:28px 32px; }}
+ header h1 {{ margin:0 0 4px; font-size:22px; }}
+ header p {{ margin:0; opacity:.75; font-size:14px; }}
+ main {{ max-width:1000px; margin:0 auto; padding:28px 32px; }}
+ h2 {{ font-size:15px; text-transform:uppercase; letter-spacing:.05em; color:#64748B; margin:28px 0 12px; }}
+ table {{ width:100%; border-collapse:collapse; background:#fff; border:1px solid var(--line); border-radius:10px; overflow:hidden; }}
+ th,td {{ text-align:left; padding:11px 14px; font-size:14px; border-bottom:1px solid var(--line); }}
+ th {{ background:#F1F5F9; color:#475569; font-size:12px; text-transform:uppercase; letter-spacing:.04em; }}
+ tr:last-child td {{ border-bottom:none; }}
+ code {{ color:var(--accent); font-weight:600; }}
+ .pill {{ background:#DCFCE7; color:#166534; padding:2px 10px; border-radius:999px; font-size:12px; font-weight:600; }}
+ .empty {{ color:#94A3B8; text-align:center; padding:24px; }}
+ .card {{ background:#fff; border:1px solid var(--line); border-radius:10px; padding:14px 16px; margin-bottom:12px; }}
+ .muted {{ color:#64748B; font-size:12px; margin-bottom:6px; }}
+ .card p {{ margin:0 0 10px; font-size:14px; line-height:1.5; }}
+ .followup {{ background:#EEF2FF; color:#3730A3; padding:10px 12px; border-radius:8px; font-size:13px; line-height:1.5; }}
+</style></head>
+<body>
+ <header>
+ <h1>{html.escape(SETTINGS.business_name)} · Front Desk CRM</h1>
+ <p>Appointments and post-call summaries booked by the Telnyx voice agent</p>
+ </header>
+ <main>
+ <h2>Appointments ({len(appts)})</h2>
+ <table>
+ <tr><th>Ref</th><th>Name</th><th>Phone</th><th>Service</th><th>When</th><th>Status</th></tr>
+ {appt_rows}
+ </table>
+ <h2>Call summaries ({len(summaries)})</h2>
+ {summary_cards}
+ </main>
+</body></html>"""
+
+
+if __name__ == "__main__":
+ import uvicorn
+
+ uvicorn.run("main:app", host=SETTINGS.host, port=SETTINGS.port, reload=True)
diff --git a/audio/ai_appointment_booking_voice_agent/pyproject.toml b/audio/ai_appointment_booking_voice_agent/pyproject.toml
new file mode 100644
index 0000000..44bac56
--- /dev/null
+++ b/audio/ai_appointment_booking_voice_agent/pyproject.toml
@@ -0,0 +1,16 @@
+[project]
+name = "ai-appointment-booking-voice-agent"
+version = "1.0.0"
+description = "A Telnyx Voice AI agent that answers real phone calls, books appointments through webhook tools, stores them in a CRM, and writes a personalised follow-up with Telnyx Inference."
+readme = "README.md"
+requires-python = ">=3.10,<3.14"
+dependencies = [
+ "fastapi>=0.115.0",
+ "uvicorn[standard]>=0.30.0",
+ "python-dotenv>=1.0.0",
+ "openai>=1.40.0",
+ "httpx>=0.27.0",
+]
+
+[tool.setuptools.packages.find]
+include = ["appointment_agent*"]