how to build an ai voice agent for appointment booking

how to build an ai voice agent for appointment booking

how to build an ai voice agent for appointment booking

published

published

"do you have anything after 3 pm tomorrow?" a caller asks the clinic. the agent checks the schedule and offers 6 pm or 7 pm. the caller picks 6 pm and hears "you're booked" before they hang up.

we can build an ai voice agent for appointment booking with rumik voice agents. we'll connect the agent to a scheduling api with two custom tools. one checks which times are free. the other saves the time the caller agrees to. the agent confirms the appointment after the api returns a booking id.

we'll use a small python scheduler for the demo. then we'll make a browser call and check that the time we heard matches the booking the scheduler saved.

how does an ai voice agent book an appointment?

the voice agent uses custom tools in rumik to check availability and save an appointment while the caller is on the line.

  1. check which times are free. the availability tool sends the requested date to the scheduler. each opening comes back with a time and a slot id. the agent reads out the times that match what the caller asked for.

  2. save the time the caller picks. the agent reads back the date and time. once the caller agrees, the booking tool sends the matching slot id. the scheduler checks that the slot is still free before saving it.

  3. confirm the appointment. the agent waits for the scheduler to return a booking id before saying "you're booked." if the slot was taken or the request times out, the agent says it couldn't confirm the booking.

the voice agent offers an open time, saves the chosen slot, and confirms the appointment after the scheduler returns a booking id.

you can try a sample conversation on the rumik appointment booking page.

connect your voice agent to an appointment scheduling api

if you already have a test scheduling api, grab the urls and credentials for checking availability and making a booking. you can go straight to creating the custom tools with your api's field names.

build a sample appointment scheduler in python

we'll use a small python server to list open times, save a booking, and find it after the call. it uses python's standard library.

create booking_demo.py and paste the next four python blocks into it in order. keep the indentation as shown.

1. start with two consultation slots

we'll give the clinic two consultation times each day, at 4 pm and 5 pm india time. each slot id includes the date and hour, so booking 4 pm on one day leaves 4 pm open on the next.

"""Run a disposable scheduling API for the appointment-booking tutorial."""

import argparse
import hmac
import json
import re
import secrets
from datetime import date, datetime, time, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Lock
from time import sleep
from urllib.parse import parse_qs, urlsplit


def make_server(port, booking_response_delay_ms=0):
    india_time = timezone(timedelta(hours=5, minutes=30))
    example_date = datetime.now(india_time).date() + timedelta(days=1)
    consultation_hours = (16, 17)
    bookings = {}
    booking_lock = Lock()
    token = secrets.token_urlsafe(24)
    expected_auth = f"Bearer {token}".encode("ascii")

    def resolve_date(value, today):
        if value == "today":
            return today
        if value == "tomorrow":
            return today + timedelta(days=1)
        if re.fullmatch(r"[0-9]{2}-[0-9]{2}", value):
            # A yearless date means the next occurrence, including today.
            for year in range(today.year, min(today.year + 9, 10000)):
                try:
                    candidate = date.fromisoformat(f"{year:04d}-{value}")
                except ValueError:
                    continue
                if candidate >= today:
                    return candidate
            raise ValueError("Invalid month and day")
        parsed = date.fromisoformat(value)
        if parsed.isoformat() != value:
            raise ValueError("Expected YYYY-MM-DD")
        return parsed

    def slot_start(slot_id):
        day, hour = slot_id.rsplit("/", 1)
        appointment_date = date.fromisoformat(day)
        if appointment_date.isoformat() != day or hour not in map(str, consultation_hours):
            raise ValueError("Invalid slot")
        return datetime.combine(appointment_date, time(int(hour)), india_time)

    class Handler(BaseHTTPRequestHandler):
        def reply(self, status, payload):
            body = json.dumps(payload).encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def authorized(self):
            received = self.headers.get("Authorization", "").encode("latin-1")
            if hmac.compare_digest(received, expected_auth):
                return True
            self.reply(401, {"status": "unauthorized"})
            return False
"""Run a disposable scheduling API for the appointment-booking tutorial."""

import argparse
import hmac
import json
import re
import secrets
from datetime import date, datetime, time, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Lock
from time import sleep
from urllib.parse import parse_qs, urlsplit


def make_server(port, booking_response_delay_ms=0):
    india_time = timezone(timedelta(hours=5, minutes=30))
    example_date = datetime.now(india_time).date() + timedelta(days=1)
    consultation_hours = (16, 17)
    bookings = {}
    booking_lock = Lock()
    token = secrets.token_urlsafe(24)
    expected_auth = f"Bearer {token}".encode("ascii")

    def resolve_date(value, today):
        if value == "today":
            return today
        if value == "tomorrow":
            return today + timedelta(days=1)
        if re.fullmatch(r"[0-9]{2}-[0-9]{2}", value):
            # A yearless date means the next occurrence, including today.
            for year in range(today.year, min(today.year + 9, 10000)):
                try:
                    candidate = date.fromisoformat(f"{year:04d}-{value}")
                except ValueError:
                    continue
                if candidate >= today:
                    return candidate
            raise ValueError("Invalid month and day")
        parsed = date.fromisoformat(value)
        if parsed.isoformat() != value:
            raise ValueError("Expected YYYY-MM-DD")
        return parsed

    def slot_start(slot_id):
        day, hour = slot_id.rsplit("/", 1)
        appointment_date = date.fromisoformat(day)
        if appointment_date.isoformat() != day or hour not in map(str, consultation_hours):
            raise ValueError("Invalid slot")
        return datetime.combine(appointment_date, time(int(hour)), india_time)

    class Handler(BaseHTTPRequestHandler):
        def reply(self, status, payload):
            body = json.dumps(payload).encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def authorized(self):
            received = self.headers.get("Authorization", "").encode("latin-1")
            if hmac.compare_digest(received, expected_auth):
                return True
            self.reply(401, {"status": "unauthorized"})
            return False

resolve_date turns "today", "tomorrow", or a month and day into a date using india time. bookings holds appointments as they're saved.

the server generates a bearer token when it starts. both tools send that token in the Authorization header so the server can check it before handling a request.

2. let the agent check what's free

now we'll give the agent a way to check the calendar. paste this block below authorized inside Handler.

        def do_GET(self):
            if not self.authorized():
                return

            url = urlsplit(self.path)
            if url.path == "/availability":
                requested_dates = parse_qs(url.query).get("date", [])
                try:
                    requested_date, = requested_dates
                    now = datetime.now(india_time)
                    day = resolve_date(requested_date, now.date())
                except ValueError:
                    self.reply(400, {"status": "invalid_date"})
                    return

                with booking_lock:
                    available = []
                    for hour in consultation_hours:
                        slot_id = f"{day}/{hour}"
                        starts_at = datetime.combine(day, time(hour), india_time)
                        if starts_at > now and slot_id not in bookings:
                            available.append({"slot_id": slot_id, "starts_at": starts_at.isoformat()})
                self.reply(200, {"slots": available})
            elif url.path == "/bookings":
                with booking_lock:
                    records = list(bookings.values())
                self.reply(200, {"bookings": records})
            else:
                self.reply(404, {"status": "not_found"})
        def do_GET(self):
            if not self.authorized():
                return

            url = urlsplit(self.path)
            if url.path == "/availability":
                requested_dates = parse_qs(url.query).get("date", [])
                try:
                    requested_date, = requested_dates
                    now = datetime.now(india_time)
                    day = resolve_date(requested_date, now.date())
                except ValueError:
                    self.reply(400, {"status": "invalid_date"})
                    return

                with booking_lock:
                    available = []
                    for hour in consultation_hours:
                        slot_id = f"{day}/{hour}"
                        starts_at = datetime.combine(day, time(hour), india_time)
                        if starts_at > now and slot_id not in bookings:
                            available.append({"slot_id": slot_id, "starts_at": starts_at.isoformat()})
                self.reply(200, {"slots": available})
            elif url.path == "/bookings":
                with booking_lock:
                    records = list(bookings.values())
                self.reply(200, {"bookings": records})
            else:
                self.reply(404, {"status": "not_found"})

GET /availability returns the times on the requested date that are still ahead and haven't been booked. a past date returns an empty list. a missing or invalid date returns http 400.

GET /bookings returns saved appointments. we'll use it to check whether an appointment was saved if the agent doesn't get a response.

3. book the time the caller picks

once the caller agrees to 4 pm, the agent sends its slot id to POST /bookings. the server checks the slot again in case someone else took it while the caller was deciding.

add this block after do_GET. keep the final return ThreadingHTTPServer(...) line at the same indentation as class Handler.

        def do_POST(self):
            if not self.authorized():
                return
            if urlsplit(self.path).path != "/bookings":
                self.reply(404, {"status": "not_found"})
                return

            try:
                size = int(self.headers.get("Content-Length", "0"))
                if not 0 < size <= 4096:
                    raise ValueError("Invalid body size")
                request = json.loads(self.rfile.read(size))
            except (ValueError, UnicodeError):
                self.reply(400, {"status": "invalid_request"})
                return

            slot_id = request.get("slot_id") if isinstance(request, dict) else None
            try:
                if not isinstance(slot_id, str):
                    raise ValueError("Expected a slot id")
                starts_at = slot_start(slot_id)
            except ValueError:
                self.reply(400, {"status": "invalid_slot"})
                return

            with booking_lock:
                if slot_id in bookings or starts_at <= datetime.now(india_time):
                    booking = None
                else:
                    booking = {
                        "status": "booked",
                        "booking_id": f"demo-{secrets.token_hex(4)}",
                        "slot_id": slot_id,
                        "starts_at": starts_at.isoformat(),
                    }
                    bookings[slot_id] = booking

            if booking is None:
                self.reply(409, {"status": "slot_unavailable"})
                return
            print(f"Saved booking: {json.dumps(booking)}", flush=True)
            if booking_response_delay_ms:
                sleep(booking_response_delay_ms / 1000)
            try:
                self.reply(201, booking)
            except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
                print("Client disconnected after the booking was saved.", flush=True)

    return ThreadingHTTPServer(("127.0.0.1", port), Handler), example_date, token
        def do_POST(self):
            if not self.authorized():
                return
            if urlsplit(self.path).path != "/bookings":
                self.reply(404, {"status": "not_found"})
                return

            try:
                size = int(self.headers.get("Content-Length", "0"))
                if not 0 < size <= 4096:
                    raise ValueError("Invalid body size")
                request = json.loads(self.rfile.read(size))
            except (ValueError, UnicodeError):
                self.reply(400, {"status": "invalid_request"})
                return

            slot_id = request.get("slot_id") if isinstance(request, dict) else None
            try:
                if not isinstance(slot_id, str):
                    raise ValueError("Expected a slot id")
                starts_at = slot_start(slot_id)
            except ValueError:
                self.reply(400, {"status": "invalid_slot"})
                return

            with booking_lock:
                if slot_id in bookings or starts_at <= datetime.now(india_time):
                    booking = None
                else:
                    booking = {
                        "status": "booked",
                        "booking_id": f"demo-{secrets.token_hex(4)}",
                        "slot_id": slot_id,
                        "starts_at": starts_at.isoformat(),
                    }
                    bookings[slot_id] = booking

            if booking is None:
                self.reply(409, {"status": "slot_unavailable"})
                return
            print(f"Saved booking: {json.dumps(booking)}", flush=True)
            if booking_response_delay_ms:
                sleep(booking_response_delay_ms / 1000)
            try:
                self.reply(201, booking)
            except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
                print("Client disconnected after the booking was saved.", flush=True)

    return ThreadingHTTPServer(("127.0.0.1", port), Handler), example_date, token

booking_lock keeps the check and save together so only one caller can book a slot. a second request for that slot gets http 409.

the code also lets us delay the reply after saving. we'll use that to test a timeout.

4. start the server

paste the last block at the end of booking_demo.py.

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8080)
    parser.add_argument(
        "--booking-response-delay-ms",
        type=int,
        default=0,
        help="Delay a successful booking response after saving the record.",
    )
    args = parser.parse_args()
    if args.booking_response_delay_ms < 0:
        parser.error("--booking-response-delay-ms must be zero or greater")

    server, example_date, token = make_server(args.port, args.booking_response_delay_ms)
    with server:
        print(f"Listening on http://127.0.0.1:{server.server_port}", flush=True)
        print(f"Example test date: {example_date} (India time)", flush=True)
        print("Sample consultation slots: 4 pm and 5 pm daily (India time)", flush=True)
        print(f"Bearer token: {token}", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    main()
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8080)
    parser.add_argument(
        "--booking-response-delay-ms",
        type=int,
        default=0,
        help="Delay a successful booking response after saving the record.",
    )
    args = parser.parse_args()
    if args.booking_response_delay_ms < 0:
        parser.error("--booking-response-delay-ms must be zero or greater")

    server, example_date, token = make_server(args.port, args.booking_response_delay_ms)
    with server:
        print(f"Listening on http://127.0.0.1:{server.server_port}", flush=True)
        print(f"Example test date: {example_date} (India time)", flush=True)
        print("Sample consultation slots: 4 pm and 5 pm daily (India time)", flush=True)
        print(f"Bearer token: {token}", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    main()

main() starts the server. we'll use the default settings for the first call. run this from the folder where you saved the file.

python booking_demo.py
python booking_demo.py

the server listens on port 8080. keep this terminal open and copy the value after Bearer token: for the playground.

we'll use a cloudflare quick tunnel so rumik can reach the local server. once cloudflared is installed, run this in a second terminal.

cloudflared tunnel --url http://127.0.0.1:8080
cloudflared tunnel --url http://127.0.0.1:8080

if windows just installed cloudflared and git bash says command not found, close and reopen the terminal so it can pick up the updated path. run cloudflared --version to check that the shell can find it before starting the tunnel again.

copy the https address ending in trycloudflare.com from the cloudflared output. we'll add /availability or /bookings to that address in each tool's url field. keep both terminals open during the call.

cloudflared tunnel creation message with an example of the https address to copy

note: if we restart cloudflared, we'll copy the new address into both tools. if we restart python, we'll copy the new bearer token into both tools. restarting python clears the sample bookings.

create custom tools for appointment booking

in the rumik playground, open agents, then tools. choose create tool and set kind to during call.

leave wait for response on for both tools. the agent needs the availability response before offering a time and the booking response before confirming it.

for each tool, open auth, choose bearer, and paste just the token from the python terminal. the playground adds the bearer prefix. the tunnel address comes from the cloudflared terminal and goes in url.

auth tab with bearer token selected and the saved token hidden

create a tool to check availability

  1. in name, enter check_availability.

  2. in description, enter “find open consultation slots for the date the caller asks for.”

  3. under llm parameters, click add parameter. set parameter name to date, type to string, and keep required parameter checked. in parameter description, enter “the appointment date in india time. send YYYY-MM-DD when the caller gives a year, MM-DD when they give only a month and day, or today or tomorrow when they use those words.”

  4. under endpoint, select GET in method. in url, paste the cloudflared address with /availability at the end. for example, if cloudflared printed https://example.trycloudflare.com, enter https://example.trycloudflare.com/availability.

  5. open params and add a row. enter date in name and {date} in value. this puts the date the agent heard into the request's query string.

  6. under api output, enter $slots. leave wait for response on and save the tool.

the agent reads starts_at to offer a time out loud. when the caller picks a time, the booking tool sends the corresponding slot_id back to the scheduler.

create a tool to book the appointment

  1. in name, enter book_appointment.

  2. in description, enter “save the consultation slot the caller agreed to.”

  3. under llm parameters, add a required string named slot_id. in parameter description, enter “copy the exact slot_id from check_availability for the time the caller agreed to.”

  4. under endpoint, select POST in method. in url, paste the same cloudflared address with /bookings at the end, for example https://example.trycloudflare.com/bookings.

  5. open headers and add a row with name set to Content-Type and value set to application/json. open body and paste {"slot_id":"{slot_id}"}.

  6. under api output, add three separate rows for $status, $booking_id, and $starts_at. leave wait for response on and save the tool.

after a successful save, the scheduler returns status: booked and a booking_id. it also prints a Saved booking: line in the terminal. we'll check that line after the call. if someone took the slot in the meantime, the scheduler returns http 409.

when should the agent say you're booked?

the voice agent should confirm an appointment only after the scheduling api returns a saved booking id. before it submits the booking, have it read back the chosen date and time and wait for the caller to agree.

in the playground, open agents, then voice agents, and choose create agent. paste this into first greeting.

hi, thanks for calling. what day works for your consultation?
hi, thanks for calling. what day works for your consultation?

paste the prompt below into system instruction. the names inside the double braces should match the two tools we saved. rumik's guide to attaching tools to a prompt shows how that works.

you book consultations for a test clinic. use india time when reading out appointment times.

if the caller already gave a date, use it. ask which date they want only if they haven't given one or you couldn't hear it clearly.

for today or tomorrow, send today or tomorrow. if they say a month and day without a year, send MM-DD, for example 11-17 for 17 november. if they include a year, send YYYY-MM-DD. the scheduler resolves yearless dates to the next occurrence, including today.

call {{check_availability}} before offering times. offer only times in the returned slots. if the list is empty, ask for another date. if the tool fails, say you couldn't check availability and ask the caller to repeat the date.

read back the chosen date and time and ask the caller to confirm. once they agree, use {{book_appointment}} with the slot id from the availability result.

say the appointment is booked only if the booking tool returns status booked and a booking id. if the tool fails or times out, tell the caller you couldn't confirm the booking yet. do not make another booking attempt in the same call.
you book consultations for a test clinic. use india time when reading out appointment times.

if the caller already gave a date, use it. ask which date they want only if they haven't given one or you couldn't hear it clearly.

for today or tomorrow, send today or tomorrow. if they say a month and day without a year, send MM-DD, for example 11-17 for 17 november. if they include a year, send YYYY-MM-DD. the scheduler resolves yearless dates to the next occurrence, including today.

call {{check_availability}} before offering times. offer only times in the returned slots. if the list is empty, ask for another date. if the tool fails, say you couldn't check availability and ask the caller to repeat the date.

read back the chosen date and time and ask the caller to confirm. once they agree, use {{book_appointment}} with the slot id from the availability result.

say the appointment is booked only if the booking tool returns status booked and a booking id. if the tool fails or times out, tell the caller you couldn't confirm the booking yet. do not make another booking attempt in the same call.

test your booking agent in the browser

we'll start with a call that books one of the sample times. the test passes when the agent confirms the chosen time and the scheduler shows one matching record.

if you're adding this agent to your own site, use the guide to starting a web call from your app.

make a call and find the booking

  1. keep the scheduler and tunnel running. in the playground, deploy your test agent and click test live.

  2. say “i'd like a consultation tomorrow at 5 pm.” the agent should use the date you gave, check availability, and read back the full date and time. agree when it asks you to confirm.

  3. in the scheduler terminal, find the Saved booking: line for the slot ending in /17. check that it has a booking_id and that starts_at matches the date and time you chose, including the +05:30 offset.

  4. open conversations in the playground. compare the saved time with what the agent confirmed in the call transcript and recording.

on another call, ask for a day and month without a year. pick a date that still has future slots. check that the server log shows an MM-DD query and that the agent reads back the date without asking for the year.

to test an interruption, ask the agent to repeat the date while it's reading it back. check that it waits for you to agree before saving the appointment. interrupting an agent while it's speaking is called barge-in.

here's the record from an earlier browser test. the scheduler returned http 201 and saved the 5 pm consultation. this run used the earlier slot id format. with the current demo, the slot id also includes the date.

saved test appointment for 18 november 2026 at 5 pm ist with http 201 and a booking id

what if the slot is taken or the request times out?

for each of these tests, we'll check what the caller hears and whether the scheduler wrote a record.

what to try

what the caller should hear

what to check in the scheduler

ask for a past date and include the year.

the agent asks for another date.

the availability response contains an empty slots list and no booking is created.

start with an open slot. after the agent offers it, book the same slot from a second session before agreeing to it in the first call.

the agent says it couldn't confirm the time.

the first call's booking request gets http 409. the scheduler shows one booking for that slot.

make the booking endpoint respond after the tool's timeout.

the agent says it couldn't confirm the booking yet.

the scheduler can still show one saved booking even though the agent timed out.

to reproduce that last case, restart the python scheduler with a seven-second delay after it saves a booking.

python booking_demo.py --booking-response-delay-ms 7000
python booking_demo.py --booking-response-delay-ms 7000

paste the new bearer token into both tools. set the booking tool's timeout to 5000 ms, deploy, and make another call.

when you agree to the slot, the scheduler saves the booking and waits seven seconds to reply. the agent should say it couldn't confirm the booking yet. look for the saved booking in the terminal.

in a local http test of the python scheduler, the client timed out after five seconds. a separate GET /bookings request still returned one saved appointment for the selected slot.

local test timeline showing the booking saved at 0 seconds, the client timing out at 5 seconds, and the server attempting to reply at 7 seconds

for your own scheduling api, give each booking attempt a request id and a way to look up the result. reuse the same id on retry to avoid creating a second appointment. aws's guide to safe api retries shows how to do this.

wrapping up

we gave the voice agent two tools, one to find an open time and one to book it. in the browser test, we check the recording against the scheduler to make sure the time the agent confirmed matches the saved appointment.

when you're ready to take calls on a +91 line, you can connect a phone number or bring your own sip trunk. repeat the booking and timeout tests on that route before taking customer calls.

try a booking in the rumik playground. pick one of the clinic's sample times and look for it in the scheduler.

"do you have anything after 3 pm tomorrow?" a caller asks the clinic. the agent checks the schedule and offers 6 pm or 7 pm. the caller picks 6 pm and hears "you're booked" before they hang up.

we can build an ai voice agent for appointment booking with rumik voice agents. we'll connect the agent to a scheduling api with two custom tools. one checks which times are free. the other saves the time the caller agrees to. the agent confirms the appointment after the api returns a booking id.

we'll use a small python scheduler for the demo. then we'll make a browser call and check that the time we heard matches the booking the scheduler saved.

how does an ai voice agent book an appointment?

the voice agent uses custom tools in rumik to check availability and save an appointment while the caller is on the line.

  1. check which times are free. the availability tool sends the requested date to the scheduler. each opening comes back with a time and a slot id. the agent reads out the times that match what the caller asked for.

  2. save the time the caller picks. the agent reads back the date and time. once the caller agrees, the booking tool sends the matching slot id. the scheduler checks that the slot is still free before saving it.

  3. confirm the appointment. the agent waits for the scheduler to return a booking id before saying "you're booked." if the slot was taken or the request times out, the agent says it couldn't confirm the booking.

the voice agent offers an open time, saves the chosen slot, and confirms the appointment after the scheduler returns a booking id.

you can try a sample conversation on the rumik appointment booking page.

connect your voice agent to an appointment scheduling api

if you already have a test scheduling api, grab the urls and credentials for checking availability and making a booking. you can go straight to creating the custom tools with your api's field names.

build a sample appointment scheduler in python

we'll use a small python server to list open times, save a booking, and find it after the call. it uses python's standard library.

create booking_demo.py and paste the next four python blocks into it in order. keep the indentation as shown.

1. start with two consultation slots

we'll give the clinic two consultation times each day, at 4 pm and 5 pm india time. each slot id includes the date and hour, so booking 4 pm on one day leaves 4 pm open on the next.

"""Run a disposable scheduling API for the appointment-booking tutorial."""

import argparse
import hmac
import json
import re
import secrets
from datetime import date, datetime, time, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Lock
from time import sleep
from urllib.parse import parse_qs, urlsplit


def make_server(port, booking_response_delay_ms=0):
    india_time = timezone(timedelta(hours=5, minutes=30))
    example_date = datetime.now(india_time).date() + timedelta(days=1)
    consultation_hours = (16, 17)
    bookings = {}
    booking_lock = Lock()
    token = secrets.token_urlsafe(24)
    expected_auth = f"Bearer {token}".encode("ascii")

    def resolve_date(value, today):
        if value == "today":
            return today
        if value == "tomorrow":
            return today + timedelta(days=1)
        if re.fullmatch(r"[0-9]{2}-[0-9]{2}", value):
            # A yearless date means the next occurrence, including today.
            for year in range(today.year, min(today.year + 9, 10000)):
                try:
                    candidate = date.fromisoformat(f"{year:04d}-{value}")
                except ValueError:
                    continue
                if candidate >= today:
                    return candidate
            raise ValueError("Invalid month and day")
        parsed = date.fromisoformat(value)
        if parsed.isoformat() != value:
            raise ValueError("Expected YYYY-MM-DD")
        return parsed

    def slot_start(slot_id):
        day, hour = slot_id.rsplit("/", 1)
        appointment_date = date.fromisoformat(day)
        if appointment_date.isoformat() != day or hour not in map(str, consultation_hours):
            raise ValueError("Invalid slot")
        return datetime.combine(appointment_date, time(int(hour)), india_time)

    class Handler(BaseHTTPRequestHandler):
        def reply(self, status, payload):
            body = json.dumps(payload).encode("utf-8")
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def authorized(self):
            received = self.headers.get("Authorization", "").encode("latin-1")
            if hmac.compare_digest(received, expected_auth):
                return True
            self.reply(401, {"status": "unauthorized"})
            return False

resolve_date turns "today", "tomorrow", or a month and day into a date using india time. bookings holds appointments as they're saved.

the server generates a bearer token when it starts. both tools send that token in the Authorization header so the server can check it before handling a request.

2. let the agent check what's free

now we'll give the agent a way to check the calendar. paste this block below authorized inside Handler.

        def do_GET(self):
            if not self.authorized():
                return

            url = urlsplit(self.path)
            if url.path == "/availability":
                requested_dates = parse_qs(url.query).get("date", [])
                try:
                    requested_date, = requested_dates
                    now = datetime.now(india_time)
                    day = resolve_date(requested_date, now.date())
                except ValueError:
                    self.reply(400, {"status": "invalid_date"})
                    return

                with booking_lock:
                    available = []
                    for hour in consultation_hours:
                        slot_id = f"{day}/{hour}"
                        starts_at = datetime.combine(day, time(hour), india_time)
                        if starts_at > now and slot_id not in bookings:
                            available.append({"slot_id": slot_id, "starts_at": starts_at.isoformat()})
                self.reply(200, {"slots": available})
            elif url.path == "/bookings":
                with booking_lock:
                    records = list(bookings.values())
                self.reply(200, {"bookings": records})
            else:
                self.reply(404, {"status": "not_found"})

GET /availability returns the times on the requested date that are still ahead and haven't been booked. a past date returns an empty list. a missing or invalid date returns http 400.

GET /bookings returns saved appointments. we'll use it to check whether an appointment was saved if the agent doesn't get a response.

3. book the time the caller picks

once the caller agrees to 4 pm, the agent sends its slot id to POST /bookings. the server checks the slot again in case someone else took it while the caller was deciding.

add this block after do_GET. keep the final return ThreadingHTTPServer(...) line at the same indentation as class Handler.

        def do_POST(self):
            if not self.authorized():
                return
            if urlsplit(self.path).path != "/bookings":
                self.reply(404, {"status": "not_found"})
                return

            try:
                size = int(self.headers.get("Content-Length", "0"))
                if not 0 < size <= 4096:
                    raise ValueError("Invalid body size")
                request = json.loads(self.rfile.read(size))
            except (ValueError, UnicodeError):
                self.reply(400, {"status": "invalid_request"})
                return

            slot_id = request.get("slot_id") if isinstance(request, dict) else None
            try:
                if not isinstance(slot_id, str):
                    raise ValueError("Expected a slot id")
                starts_at = slot_start(slot_id)
            except ValueError:
                self.reply(400, {"status": "invalid_slot"})
                return

            with booking_lock:
                if slot_id in bookings or starts_at <= datetime.now(india_time):
                    booking = None
                else:
                    booking = {
                        "status": "booked",
                        "booking_id": f"demo-{secrets.token_hex(4)}",
                        "slot_id": slot_id,
                        "starts_at": starts_at.isoformat(),
                    }
                    bookings[slot_id] = booking

            if booking is None:
                self.reply(409, {"status": "slot_unavailable"})
                return
            print(f"Saved booking: {json.dumps(booking)}", flush=True)
            if booking_response_delay_ms:
                sleep(booking_response_delay_ms / 1000)
            try:
                self.reply(201, booking)
            except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
                print("Client disconnected after the booking was saved.", flush=True)

    return ThreadingHTTPServer(("127.0.0.1", port), Handler), example_date, token

booking_lock keeps the check and save together so only one caller can book a slot. a second request for that slot gets http 409.

the code also lets us delay the reply after saving. we'll use that to test a timeout.

4. start the server

paste the last block at the end of booking_demo.py.

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8080)
    parser.add_argument(
        "--booking-response-delay-ms",
        type=int,
        default=0,
        help="Delay a successful booking response after saving the record.",
    )
    args = parser.parse_args()
    if args.booking_response_delay_ms < 0:
        parser.error("--booking-response-delay-ms must be zero or greater")

    server, example_date, token = make_server(args.port, args.booking_response_delay_ms)
    with server:
        print(f"Listening on http://127.0.0.1:{server.server_port}", flush=True)
        print(f"Example test date: {example_date} (India time)", flush=True)
        print("Sample consultation slots: 4 pm and 5 pm daily (India time)", flush=True)
        print(f"Bearer token: {token}", flush=True)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    main()

main() starts the server. we'll use the default settings for the first call. run this from the folder where you saved the file.

python booking_demo.py

the server listens on port 8080. keep this terminal open and copy the value after Bearer token: for the playground.

we'll use a cloudflare quick tunnel so rumik can reach the local server. once cloudflared is installed, run this in a second terminal.

cloudflared tunnel --url http://127.0.0.1:8080

if windows just installed cloudflared and git bash says command not found, close and reopen the terminal so it can pick up the updated path. run cloudflared --version to check that the shell can find it before starting the tunnel again.

copy the https address ending in trycloudflare.com from the cloudflared output. we'll add /availability or /bookings to that address in each tool's url field. keep both terminals open during the call.

cloudflared tunnel creation message with an example of the https address to copy

note: if we restart cloudflared, we'll copy the new address into both tools. if we restart python, we'll copy the new bearer token into both tools. restarting python clears the sample bookings.

create custom tools for appointment booking

in the rumik playground, open agents, then tools. choose create tool and set kind to during call.

leave wait for response on for both tools. the agent needs the availability response before offering a time and the booking response before confirming it.

for each tool, open auth, choose bearer, and paste just the token from the python terminal. the playground adds the bearer prefix. the tunnel address comes from the cloudflared terminal and goes in url.

auth tab with bearer token selected and the saved token hidden

create a tool to check availability

  1. in name, enter check_availability.

  2. in description, enter “find open consultation slots for the date the caller asks for.”

  3. under llm parameters, click add parameter. set parameter name to date, type to string, and keep required parameter checked. in parameter description, enter “the appointment date in india time. send YYYY-MM-DD when the caller gives a year, MM-DD when they give only a month and day, or today or tomorrow when they use those words.”

  4. under endpoint, select GET in method. in url, paste the cloudflared address with /availability at the end. for example, if cloudflared printed https://example.trycloudflare.com, enter https://example.trycloudflare.com/availability.

  5. open params and add a row. enter date in name and {date} in value. this puts the date the agent heard into the request's query string.

  6. under api output, enter $slots. leave wait for response on and save the tool.

the agent reads starts_at to offer a time out loud. when the caller picks a time, the booking tool sends the corresponding slot_id back to the scheduler.

create a tool to book the appointment

  1. in name, enter book_appointment.

  2. in description, enter “save the consultation slot the caller agreed to.”

  3. under llm parameters, add a required string named slot_id. in parameter description, enter “copy the exact slot_id from check_availability for the time the caller agreed to.”

  4. under endpoint, select POST in method. in url, paste the same cloudflared address with /bookings at the end, for example https://example.trycloudflare.com/bookings.

  5. open headers and add a row with name set to Content-Type and value set to application/json. open body and paste {"slot_id":"{slot_id}"}.

  6. under api output, add three separate rows for $status, $booking_id, and $starts_at. leave wait for response on and save the tool.

after a successful save, the scheduler returns status: booked and a booking_id. it also prints a Saved booking: line in the terminal. we'll check that line after the call. if someone took the slot in the meantime, the scheduler returns http 409.

when should the agent say you're booked?

the voice agent should confirm an appointment only after the scheduling api returns a saved booking id. before it submits the booking, have it read back the chosen date and time and wait for the caller to agree.

in the playground, open agents, then voice agents, and choose create agent. paste this into first greeting.

hi, thanks for calling. what day works for your consultation?

paste the prompt below into system instruction. the names inside the double braces should match the two tools we saved. rumik's guide to attaching tools to a prompt shows how that works.

you book consultations for a test clinic. use india time when reading out appointment times.

if the caller already gave a date, use it. ask which date they want only if they haven't given one or you couldn't hear it clearly.

for today or tomorrow, send today or tomorrow. if they say a month and day without a year, send MM-DD, for example 11-17 for 17 november. if they include a year, send YYYY-MM-DD. the scheduler resolves yearless dates to the next occurrence, including today.

call {{check_availability}} before offering times. offer only times in the returned slots. if the list is empty, ask for another date. if the tool fails, say you couldn't check availability and ask the caller to repeat the date.

read back the chosen date and time and ask the caller to confirm. once they agree, use {{book_appointment}} with the slot id from the availability result.

say the appointment is booked only if the booking tool returns status booked and a booking id. if the tool fails or times out, tell the caller you couldn't confirm the booking yet. do not make another booking attempt in the same call.

test your booking agent in the browser

we'll start with a call that books one of the sample times. the test passes when the agent confirms the chosen time and the scheduler shows one matching record.

if you're adding this agent to your own site, use the guide to starting a web call from your app.

make a call and find the booking

  1. keep the scheduler and tunnel running. in the playground, deploy your test agent and click test live.

  2. say “i'd like a consultation tomorrow at 5 pm.” the agent should use the date you gave, check availability, and read back the full date and time. agree when it asks you to confirm.

  3. in the scheduler terminal, find the Saved booking: line for the slot ending in /17. check that it has a booking_id and that starts_at matches the date and time you chose, including the +05:30 offset.

  4. open conversations in the playground. compare the saved time with what the agent confirmed in the call transcript and recording.

on another call, ask for a day and month without a year. pick a date that still has future slots. check that the server log shows an MM-DD query and that the agent reads back the date without asking for the year.

to test an interruption, ask the agent to repeat the date while it's reading it back. check that it waits for you to agree before saving the appointment. interrupting an agent while it's speaking is called barge-in.

here's the record from an earlier browser test. the scheduler returned http 201 and saved the 5 pm consultation. this run used the earlier slot id format. with the current demo, the slot id also includes the date.

saved test appointment for 18 november 2026 at 5 pm ist with http 201 and a booking id

what if the slot is taken or the request times out?

for each of these tests, we'll check what the caller hears and whether the scheduler wrote a record.

what to try

what the caller should hear

what to check in the scheduler

ask for a past date and include the year.

the agent asks for another date.

the availability response contains an empty slots list and no booking is created.

start with an open slot. after the agent offers it, book the same slot from a second session before agreeing to it in the first call.

the agent says it couldn't confirm the time.

the first call's booking request gets http 409. the scheduler shows one booking for that slot.

make the booking endpoint respond after the tool's timeout.

the agent says it couldn't confirm the booking yet.

the scheduler can still show one saved booking even though the agent timed out.

to reproduce that last case, restart the python scheduler with a seven-second delay after it saves a booking.

python booking_demo.py --booking-response-delay-ms 7000

paste the new bearer token into both tools. set the booking tool's timeout to 5000 ms, deploy, and make another call.

when you agree to the slot, the scheduler saves the booking and waits seven seconds to reply. the agent should say it couldn't confirm the booking yet. look for the saved booking in the terminal.

in a local http test of the python scheduler, the client timed out after five seconds. a separate GET /bookings request still returned one saved appointment for the selected slot.

local test timeline showing the booking saved at 0 seconds, the client timing out at 5 seconds, and the server attempting to reply at 7 seconds

for your own scheduling api, give each booking attempt a request id and a way to look up the result. reuse the same id on retry to avoid creating a second appointment. aws's guide to safe api retries shows how to do this.

wrapping up

we gave the voice agent two tools, one to find an open time and one to book it. in the browser test, we check the recording against the scheduler to make sure the time the agent confirmed matches the saved appointment.

when you're ready to take calls on a +91 line, you can connect a phone number or bring your own sip trunk. repeat the booking and timeout tests on that route before taking customer calls.

try a booking in the rumik playground. pick one of the clinic's sample times and look for it in the scheduler.

frequently asked questions

frequently asked questions

frequently asked questions

you can set up a booking agent in the rumik playground without writing python if you already have a scheduling api. point one tool at the endpoint that checks availability and the other at the endpoint that saves the appointment. the python scheduler gives you a test calendar if you need one.
you can test a rumik booking agent in your browser without a phone number. deploy the agent in the rumik playground and click test live. if you're running the sample scheduler on your computer, keep the https tunnel open so rumik can reach it.
a rumik voice agent can book into google calendar through a scheduling backend that has access to your calendar. the backend can check busy periods with google calendar's free/busy api and use your working hours and appointment duration to find open slots. when the caller picks one, the backend saves the appointment with the event creation api.
if your rumik agent says there are no openings, check the request its availability tool sent to your scheduler. in the sample scheduler, a 401 means the server rejected the bearer token. if you get 200 with an empty "slots" list, check that the tool sends "date=YYYY-MM-DD" and that it matches the date printed when the server starts. say the year out loud on your next test call.
a rumik voice agent can reschedule or cancel an appointment if you connect tools for those actions to your booking system. the sample scheduler here creates new bookings. to handle changes, have the booking system look up the appointment and verify that the caller can change it. for a reschedule, check the new slot before moving the appointment and have rumik confirm the change after the system saves it.

read other articles

read other articles

read other articles