Back to articles
October 21, 2026AI AgentsFastAPIVoice AIGoogle CalendarSystem Design

Building an AI Voice Receptionist That Actually Books Appointments

Lessons from shipping a multi-tenant AI phone agent with FastAPI, Retell, and Google Calendar: tool-calling webhooks, timezone traps, double-booking guards, and two-way calendar sync.

A voice agent that can chat is a demo. A voice agent that can answer a clinic's phone at 6 PM, find a free slot, book it, and not double-book the front desk is a product.

I recently built an AI receptionist platform for appointment-based businesses such as med spas and clinics. Each business connects its Google Calendar, gets an AI agent with its own phone number, and the agent handles callers end to end: pricing questions, new bookings, reschedules, and cancellations.

The language model is the easy part. Almost every hard problem lived in the tool layer between the model and the calendar. Here is what I learned.


The Architecture in One Picture

 Caller ──► Phone number ──► Retell voice agent (LLM + voice)
                                   │
                    ┌──────────────┴──────────────┐
                    ▼                             ▼
        Tool webhook (mid-call)        Lifecycle webhook
        /api/tools/retell              /api/webhooks/retell
        check / book / reschedule      call_started, call_ended,
        / cancel / current time        call_analyzed
                    │                             │
                    ▼                             ▼
           Google Calendar  ◄──── push sync ──── FastAPI + Postgres
          (source of truth)     /api/webhooks/google-calendar

The stack is FastAPI with SQLModel on Postgres, a Strawberry GraphQL API for the Next.js dashboard, Retell for telephony and voice, and the Google Calendar API for scheduling. There are two separate webhook surfaces, and keeping them separate was one of the best early decisions:

  • Tool webhook: called synchronously while the caller is waiting on the line. It must be fast, and it must always return something the agent can say out loud.
  • Lifecycle webhook: called asynchronously for bookkeeping, such as call status, duration, recording URL, transcript, and summary.

Lesson 1: Never Trust the Model to Tell You Who the Tenant Is

The platform is multi-tenant. One backend serves many businesses, each with its own calendar, hours, and timezone. The tempting design is to put a business_id in the tool arguments and let the model pass it along.

Don't. Anything the model sends can be hallucinated or manipulated by a caller.

Instead, the only identifier the tool endpoint trusts is the call ID that the telephony provider attaches to the request. We resolve everything else server-side:

call = await session.exec(
    select(Call).where(Call.retell_call_id == call_id)
)
db_call = call.first()
business_id = db_call.business_id   # tenant derived from our own records
 
cal = await get_calendar_integration(session, business_id)
business = await get_business(session, business_id)
tz_str = business.timezone

The call row is created by the lifecycle webhook, which maps the provider's agent ID to our Agent row and therefore to a business. The model never gets a say in which calendar it touches.


Lesson 2: Tool Responses Are Sentences, Not Status Codes

In a normal API you return a 4xx with an error body. In a voice agent, the tool result is fed back to the LLM, which then speaks about it. A stack trace or a bare 400 makes the agent go silent or improvise.

So every tool path, including validation failures and conflicts, returns HTTP 200 with a human-readable result string that is safe to read aloud:

if not start_time or not end_time:
    return {"result": "Error: Please provide start_time and end_time."}
 
if conflict:
    return {"result": "Failed to book: The requested time slot is already "
                      "booked. Please choose a different time."}

The wording matters. A blunt "The time slot is NOT available", followed by an explicit instruction to choose a different time, gives the model a clear next step instead of leaving it to guess. Treat tool output as prompt text, because that is what it is.


Lesson 3: Timezones Will Break You, and LLMs Make It Worse

Appointment systems always have timezone bugs. LLM agents add a new failure mode: models love to append a Z to timestamps. A caller says "2 PM tomorrow", and the model sends 2026-09-02T14:00:00Z, which is 2 PM UTC, not 2 PM in the clinic.

Two defenses fixed this:

1. Anchor the model in the business's real clock. The agent's instructions tell it to call get_current_datetime silently at the very start of every call. It returns the current date and time in the business's timezone, plus an explicit hint:

now = datetime.now(ZoneInfo(tz_str))
result_message = (
    f"The current date and time in the clinic's timezone ({tz_str}) is "
    f"{now.strftime('%A, %B %d, %Y %I:%M %p')}. "
    "Use this date to anchor relative dates like 'tomorrow' or 'next Tuesday'."
)

Without it, "next Tuesday" resolves against whatever date the model believes it is, which is usually its training cutoff.

2. Treat a trailing Z as a lie. The normalizer reinterprets timestamps that are naive or end in Z as local business time, then converts to UTC for storage:

def to_utc(time_input, tz_str="UTC"):
    dt = dt_parser.isoparse(time_input) if isinstance(time_input, str) else time_input
    is_z = isinstance(time_input, str) and time_input.endswith("Z")
    tz = ZoneInfo(tz_str)
    if dt.tzinfo is None or is_z:
        dt = dt.replace(tzinfo=None).replace(tzinfo=tz)
    return dt.astimezone(timezone.utc)

Everything in the database is UTC. Everything the caller hears is in the clinic's local time. Conversion happens at exactly one boundary.


Lesson 4: Two Layers of Double-Booking Protection

Google Calendar is the source of truth for the business owner, who may also add events by hand. But checking only Google is not enough: two simultaneous calls can both see a free slot before either event lands.

So every availability check and booking runs a local overlap query first, using the standard interval-overlap condition:

conflict = await session.exec(
    select(Appointment).where(
        Appointment.business_id == business_id,
        Appointment.status != "CANCELED",
        Appointment.start_time < end_utc,
        Appointment.end_time > start_utc,
    )
)

Two intervals overlap exactly when each starts before the other ends. This single condition covers partial overlaps, containment, and exact matches without special cases.

The booking flow then looks like this:

  • Check business hours (is the clinic even open on that day and time?).
  • Check the local appointments table for overlap.
  • Check Google Calendar for events, ignoring cancelled and "free" (transparent) events.
  • Create the Google event.
  • Dual-write a local Appointment row keyed by the Google event_id.
  • Email the business owner a notification.

Reschedules run the same overlap check but exclude the appointment being moved, otherwise a customer could never shift their own booking by 15 minutes.

One more practical detail: the Google client library is synchronous, so every call goes through asyncio.to_thread. A blocking HTTP call inside an async handler stalls the event loop for every other call in flight.


Lesson 5: Two-Way Sync with Calendar Push Notifications

If the clinic owner drags an appointment to a new time in Google Calendar, the local table is now wrong, and the agent will offer a slot that is actually taken.

The fix is Google's Calendar watch API. When a business connects its calendar, we register a webhook channel. Google then pings our endpoint whenever anything changes:

watch = service.events().watch(
    calendarId="primary",
    body={"id": channel_id, "type": "web_hook", "address": webhook_url},
).execute()
# store watch["id"] and watch["resourceId"] on the Business row

The handler does a few things worth copying:

  • Acknowledges the initial sync handshake immediately without doing work.
  • Maps the channel back to a business using the stored channel and resource IDs.
  • Pulls recent events with showDeleted=True so cancellations arrive too.
  • Reconciles start time, end time, and cancelled status into the local table, converting through the business timezone.

Google's push message contains no event data, only a "something changed" signal. You always fetch the details yourself, which also makes the handler naturally idempotent.


Lesson 6: Verticalize with Config, Not Code

A med spa talks about Botox, fillers, and consultations. A dental office talks about cleanings and emergencies. Hard-coding each industry into prompts does not scale.

Instead, each industry is a versioned IndustryConfig row with structured JSON sections:

  • knowledge: terminology, synonyms, treatment categories, common caller intents
  • receptionist_behavior: tone, greeting style, how to handle uncertainty
  • workflows: step-by-step flows for booking, pricing questions, consultations
  • guardrails: what the agent must never say, such as medical advice

When a business is created, its config is compiled into the system prompt, and Retell's LLM is created with the same shared tool definitions. Launching a new vertical becomes a data task: write one config, seed it, and ship. Updating a business later can also push a refreshed prompt to the live agent.


What I'd Harden Before Scaling Further

Shipping honestly means naming the gaps. These are the items on my list as call volume grows:

  • Verify webhook signatures. Both the tool endpoint and the lifecycle endpoint should reject requests that are not signed by the telephony provider.
  • Enforce overlaps in the database. A Postgres exclusion constraint on the appointment time range makes double-booking impossible even when two requests race past the application check.
  • Renew watch channels. Google calendar watch channels expire, so a scheduled job must refresh them before they lapse.
  • Keep secrets out of code. API keys belong in environment configuration only, with no fallback defaults in source.
  • Return typed tool errors internally. Keep friendly sentences for the model, but log structured error codes for dashboards and alerts.

Key Takeaways

  • Resolve the tenant from trusted server-side identifiers, never from model-supplied arguments.
  • Write tool results as spoken sentences, because the model will read them to a real person.
  • Defend against LLM timestamp sloppiness with an anchor tool and a single UTC boundary.
  • Combine a local overlap query with the external calendar for race-free booking.
  • Use push notifications for two-way sync and treat them as hints to refetch.
  • Express industry differences as versioned configuration.

Building a voice agent, an AI booking flow, or any LLM tool-calling system that has to touch real-world schedules and payments? Let's connect and we can map out the architecture together.

Building a mobile app or web platform?

I take products from concept to a production release in 4–6 weeks. Let's talk through your goals.

Start a conversation

Have a project in mind?

Tell me what you're building and where you're stuck. I'll come back with a plan, a timeline and an honest estimate.

muizz@themoiz.com
Replies within 24 hours
Hire me on Upwork