Blog · · 5 min read
Booking into Google Calendar from a Voice Agent
How a voice agent finds open slots in Google Calendar with freeBusy, and how to prevent double bookings with a re-check before insert and deterministic event IDs.
Key points
- Compute open slots by subtracting busy times from freeBusy, padded with buffers, from business hours, and offer callers only two or three options.
- Double bookings come from three places, a competing booking for the same slot, a retried tool call, and bookings made through other channels that never reach the calendar.
- Re-check freeBusy immediately before inserting, and give each event an ID derived from the tool call so retries collapse into a single event.
A voice agent booking into Google Calendar runs through four steps: find open slots, offer a few to the caller, read back and get consent, then create the event. Open slots are business hours minus whatever freeBusy reports as busy. Double bookings are mostly prevented by re-checking right before you insert and by giving each event an ID derived from the tool call, so a retried request can't create a second copy.
Finding open slots
You need four inputs:
| Input | Example | Source |
|---|---|---|
| Business hours | Weekdays 9:00–12:00 and 14:00–18:00, Saturday mornings only | Business settings |
| Appointment length | 30 minutes | Business settings, sometimes per service |
| Buffer | 10 minutes before and after for cleanup and prep | Business settings |
| Busy times | Existing event 10:00–10:30 | Google Calendar freeBusy |
The procedure:
- Turn the caller's request ("Tuesday afternoon next week") into a date range.
- Call freeBusy for that range.
- Lay out appointment-length slots inside business hours.
- Drop any slot that overlaps a busy period, after padding by the buffer.
- Return the few slots closest to what the caller asked for.
freeBusy returns only busy intervals, never event titles or notes (Google Calendar API freeBusy). Since booking only needs times, the agent never has to read the content of anyone's calendar.
async function busyTimes(token: string, calendarId: string, from: Date, to: Date) {
const r = await fetch('https://www.googleapis.com/calendar/v3/freeBusy', {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ timeMin: from.toISOString(), timeMax: to.toISOString(), items: [{ id: calendarId }] }),
});
if (!r.ok) throw new Error(`freeBusy ${r.status}`);
const data = await r.json();
const cal = data.calendars[calendarId];
if (cal.errors?.length) throw new Error(cal.errors[0].reason);
return cal.busy.map((b: { start: string; end: string }) => ({ start: Date.parse(b.start), end: Date.parse(b.end) }));
}
const MIN = 60_000;
// Open slots of length `dur` with `buffer` padding, every `step` minutes, within one opening window
function freeSlots(open: number, close: number, busy: { start: number; end: number }[], dur = 30, buffer = 10, step = 30) {
const out: number[] = [];
for (let t = open; t + dur * MIN <= close; t += step * MIN) {
const s = t - buffer * MIN, e = t + (dur + buffer) * MIN;
if (!busy.some((b) => b.start < e && s < b.end)) out.push(t);
}
return out;
}Over the phone, nobody remembers a list of eight times. Offer the two or three closest to the request, and ask about another day if none fit.
Where double bookings come from
| Cause | What happens | Defence |
|---|---|---|
| A competing booking for the same slot | Between offering a slot and getting consent, another caller or a staff member takes it | Re-check freeBusy right before inserting |
| A retried tool call | A network hiccup delivers "create booking" twice and you get two identical events | Derive the event ID from the tool call |
| Other booking channels | Web bookings or a paper diary never make it into the calendar | Make one calendar the single source of truth |
The first one is inherent to voice: reading back details and waiting for "yes" takes time. Google Calendar has no way to hold a slot, so a re-check immediately before insert is the main defence. A small window still exists between that check and the insert. If that worries you, check freeBusy again after creating the event and alert staff if you find an overlap.
Creating the event safely
- Re-check freeBusy just before inserting. If the slot is gone, don't create anything. Say "I'm sorry, that time was just taken" and offer alternatives.
- Set the event ID yourself. Google Calendar accepts a client-supplied ID: base32hex characters (lowercase a–v and digits), 5 to 1024 characters, unique per calendar. Derive it from the tool call and a retry produces the same ID.
- Don't send invitations. Use
sendUpdates=none. - Keep sensitive details out of the title. Use "Appointment (Yamada)" and put the reason in the description.
import { createHash } from 'node:crypto';
async function createBooking(token: string, calendarId: string, idempotencyKey: string, start: Date, end: Date, name: string, phone: string) {
const id = 'bk' + createHash('sha256').update(idempotencyKey).digest('hex').slice(0, 30); // hex digits fall inside base32hex
const r = await fetch(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?sendUpdates=none`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({
id,
summary: `Appointment (${name})`,
description: `Phone: ${phone}`,
start: { dateTime: start.toISOString() },
end: { dateTime: end.toISOString() },
}),
});
if (r.status === 409) return { id, duplicate: true }; // an event with this ID already exists (the retry)
if (!r.ok) throw new Error(`events.insert ${r.status}`);
return { id, duplicate: false };
}One caveat from Google's own docs: because the system is globally distributed, ID collisions aren't guaranteed to be detected at creation time (events.insert). A deterministic ID sharply reduces duplicates; it isn't an absolute guarantee.
Doing this with voicast
With voicast you put the functions above on your own server and let the agent call them as in-call tools (config.tools). When the AI decides to use a tool, voicast sends a signed POST to the tool's URL; your server calls the Google Calendar API and returns the result.
"tools": [
{
"name": "find_free_slots",
"description": "Find open slots. Use when the caller names a preferred day.",
"url": "https://saas.example.com/voicast/tools",
"parameters": {
"properties": { "date": { "type": "string", "description": "Preferred day (YYYY-MM-DD)" } },
"required": ["date"]
}
},
{
"name": "create_booking",
"description": "Book an appointment. Use after offering slots and the caller picks one.",
"url": "https://saas.example.com/voicast/tools",
"confirm": true,
"parameters": {
"properties": {
"start": { "type": "string", "description": "Start time (ISO 8601)" },
"name": { "type": "string" },
"phone": { "type": "string" }
},
"required": ["start", "name", "phone"]
}
}
]create_booking gets confirm: true, so the AI reads the time and name back and only uses it after the caller says yes. Your server verifies the signature first. For find_free_slots it computes slots with busyTimes and freeSlots and returns two or three; for create_booking it re-checks freeBusy and then calls createBooking. Derive the event ID from the request's tool_call_id (the same value as the idempotency-key header), so a retried request from voicast still produces one event.
Reply within 8 seconds. Timeouts and Google errors reach the AI as a failure, and it apologizes and offers a callback from staff. When the slot is already taken, return a 2xx such as { "booked": false, "message": "That time was just taken" } instead of an error, so the AI can offer another time naturally.
If each of your customers has their own calendar, use call.tenant.external_id in the request to decide which calendar to read. Keep the Google access tokens on your server; voicast never needs them. A built-in Google Calendar integration is in preparation. For a worked use case, see taking restaurant reservations by phone.
FAQ
Can the agent find availability across several staff calendars?
freeBusy accepts multiple calendars in one request. Decide whether you need everyone free at once or any one person free, and adjust the slot calculation. Add a staff name to the tool parameters if callers ask for a specific person.
Does this work with Microsoft 365 calendars?
The approach is the same. Get busy times from the getSchedule API in Microsoft Graph and run the same slot calculation. The voicast tool definitions stay the same; only the API your server calls changes.
How should rescheduling work?
Find the existing booking by phone number or name, read it back, create the new event, then cancel the old one. Creating first means that if the new slot turns out to be taken, the caller hasn't lost their original booking.