By Sagar Shankaran, Founder of CallSphere
How to build production-grade Google Calendar integration for AI voice agents — OAuth, real-time availability, conflict resolution.
Key takeaways
Roughly 60% of inbound calls to any service business end with "can I book an appointment?" If your AI voice agent cannot actually put an event on the right calendar, it is a very expensive answering machine. Google Calendar is the most common backend, and integrating it sounds simple — until you meet OAuth refresh tokens, shared calendars, timezone chaos, and the race condition where two agents try to book the same 10am slot.
This guide walks through a production Google Calendar integration for an AI voice agent, from OAuth setup to conflict-safe booking.
caller → agent
│
│ check_availability(provider_id, date)
▼
Google Calendar API (freebusy)
│
│ book_appointment(provider_id, start, end)
▼
Google Calendar API (events.insert with idempotency)
│
▼
Postgres (appointments mirror)
┌──────────────────┐
│ Voice agent edge │
└────────┬─────────┘
│ tool call
▼
┌──────────────────────────┐
│ /calendar service │
│ • OAuth token store │
│ • freebusy cache (60s) │
│ • idempotent bookings │
└────────┬─────────────────┘
│
▼
┌──────────────────────────┐
│ Google Calendar API │
└──────────────────────────┘
Walk the business owner through OAuth once during onboarding. Store the refresh token encrypted.
sequenceDiagram
autonumber
participant Caller as Caller
participant Agent as CallSphere Agent
participant API as CRM API
participant DB as CRM Database
participant Webhook as Webhook Listener
Caller->>Agent: Inbound call begins
Agent->>Agent: STT plus intent detection
Agent->>API: Lookup contact by phone
API->>DB: Read contact record
DB-->>API: Contact and history
API-->>Agent: Personalized context
Agent->>API: Create call activity
Agent->>API: Update deal stage
API->>Webhook: Outbound webhook fires
Webhook-->>Agent: Confirmed
Agent->>Caller: Spoken confirmation
from google_auth_oauthlib.flow import Flow
flow = Flow.from_client_secrets_file(
"credentials.json",
scopes=["https://www.googleapis.com/auth/calendar.events"],
redirect_uri="https://app.yourapp.com/oauth/google/callback",
)
@app.get("/oauth/google/start")
async def start():
auth_url, _ = flow.authorization_url(access_type="offline", prompt="consent")
return RedirectResponse(auth_url)
@app.get("/oauth/google/callback")
async def callback(code: str):
flow.fetch_token(code=code)
creds = flow.credentials
await store_refresh_token(tenant_id, encrypt(creds.refresh_token))
return {"ok": True}
Google's freebusy endpoint is the canonical source of truth, but calling it on every turn burns quota. Cache responses for 60 seconds per calendar.
Hear it before you finish reading
Talk to a live CallSphere AI voice agent in your browser — 60 seconds, no signup.
import redis.asyncio as redis
from googleapiclient.discovery import build
r = redis.from_url("redis://cache:6379/0")
async def free_slots(calendar_id: str, day_iso: str) -> list[dict]:
cache_key = f"fb:{calendar_id}:{day_iso}"
cached = await r.get(cache_key)
if cached:
return json.loads(cached)
service = build("calendar", "v3", credentials=load_creds(calendar_id))
body = {
"timeMin": f"{day_iso}T00:00:00Z",
"timeMax": f"{day_iso}T23:59:59Z",
"items": [{"id": calendar_id}],
}
resp = service.freebusy().query(body=body).execute()
busy = resp["calendars"][calendar_id]["busy"]
slots = compute_slots(busy)
await r.set(cache_key, json.dumps(slots), ex=60)
return slots
Every events.insert accepts a requestId that Google uses for idempotency. Pass a hash of (caller_id, start_time, provider_id).
import hashlib
def request_id(caller: str, start: str, provider: str) -> str:
return hashlib.sha256(f"{caller}|{start}|{provider}".encode()).hexdigest()
async def book(calendar_id: str, start_iso: str, end_iso: str, caller: str, summary: str):
service = build("calendar", "v3", credentials=load_creds(calendar_id))
event = {
"summary": summary,
"start": {"dateTime": start_iso, "timeZone": "America/Los_Angeles"},
"end": {"dateTime": end_iso, "timeZone": "America/Los_Angeles"},
}
return service.events().insert(
calendarId=calendar_id,
body=event,
sendUpdates="all",
).execute()
const tools = [
{
type: "function",
name: "check_availability",
description: "Return available 30-minute slots for a provider on a given date",
parameters: {
type: "object",
properties: {
provider_id: { type: "string" },
date: { type: "string", description: "YYYY-MM-DD" },
},
required: ["provider_id", "date"],
},
},
{
type: "function",
name: "book_appointment",
description: "Book an appointment for a caller",
parameters: {
type: "object",
properties: {
provider_id: { type: "string" },
start_iso: { type: "string" },
end_iso: { type: "string" },
caller_name: { type: "string" },
reason: { type: "string" },
},
required: ["provider_id", "start_iso", "end_iso", "caller_name"],
},
},
];
Always write the booking to your own database so you can answer "what did we book today?" without hitting Google's API.
CallSphere uses Google Calendar as one of the primary scheduling backends for its healthcare, salon, and real estate verticals. The voice agent runs on the OpenAI Realtime API with gpt-4o-realtime-preview-2025-06-03, PCM16 at 24kHz, and server VAD. Calendar tools live inside the 14-tool healthcare agent, the 4-tool salon agent, and the 10-agent real estate stack, all orchestrated through the OpenAI Agents SDK.
Bookings are mirrored to per-vertical Postgres databases, and a GPT-4o-mini post-call pipeline attaches the booked appointment to the call record so the business owner can audit every scheduling decision. Across 57+ languages and sub-second response times, the idempotency key pattern has eliminated double-booking on our production traffic.
sendUpdates flag: callers do not get their confirmation email.Only if you want to book on behalf of any user in a Google Workspace without each user granting consent.
Expose a cancel_appointment tool that deletes the event by ID and updates your mirror.
Still reading? Stop comparing — try CallSphere live.
CallSphere ships complete AI voice agents per industry — 14 tools for healthcare, 10 agents for real estate, 4 specialists for salons. See how it actually handles a call before you book a demo.
Yes — use Calendar push notifications (watch) to invalidate your cache on external edits.
Catch the 401, fall back to "let me transfer you to someone who can book that manually", and alert ops.
Same architecture, different SDK. The patterns translate directly.
Want to see Google Calendar scheduling working on a real voice agent? Book a demo, read the platform page, or explore pricing.
#CallSphere #GoogleCalendar #VoiceAI #Integration #OAuth #Scheduling #AIVoiceAgents
Written by
Sagar Shankaran· Founder, CallSphere
Sagar Shankaran is the founder of CallSphere, where he builds production AI voice and chat agents deployed across healthcare, hospitality, real estate, and home services. He writes about agentic AI, LLM engineering, and shipping voice agents that handle real calls in production.
See how AI voice agents work for your industry. Live demo available -- no signup required.
A how-to for Colombian education and tutoring SMBs to answer parents and students instantly, book trial classes 24/7 in Spanish and English, and grow enrollment with a CallSphere AI agent.
Tbilisi professional-services firms serving relocating founders and IT companies use CallSphere AI voice and chat agents to answer enquiries 24/7 in English, Georgian and Russian and book consultations.
A practical how-to for Palau eco-resorts and dive operators on capturing every high-value, multilingual enquiry with a CallSphere AI voice and chat agent, while honouring Palau’s marine-conservation commitments.
How salons, spas and wellness SMBs across the UAE, Saudi Arabia and Qatar use CallSphere AI voice and chat agents to capture every booking 24/7 in Arabic, English and expat languages, and cut no-shows.
How estate agents and property managers in Luxembourg City and across the Grand Duchy use CallSphere to capture multilingual viewing and enquiry calls 24/7, GDPR compliant.
A practical guide for Senegalese logistics, freight, legal and consulting SMBs in Dakar and Thiès to capture every enquiry 24/7 with a CallSphere AI voice and chat agent in French, Wolof and English.
© 2026 CallSphere LLC. All rights reserved.
Made within New York
Watch how CallSphere handles real customer calls, schedules appointments, and processes payments — live.
Try Live DemoBook a DemoCalculate Your ROI