How to Build a Human Handoff for an AI Support Bot (With Code)
Most chatbot tutorials end when the bot gives an answer. Real support doesn’t. Sooner or later a customer asks something the bot can’t answer, wants a refund, is upset, or simply asks for a person. What happens next deci
Most chatbot tutorials end when the bot gives an answer. Real support doesn’t. Sooner or later a customer asks something the bot can’t answer, wants a refund, is upset, or simply asks for a person. What happens next decides whether they trust your product or close the tab.
The demand for a human option is clear. Zendesk’s CX Trends 2027 report, as summarised by Futurum, found that 88% of consumers want a human available if needed. A bot that traps people in a loop is a liability.
In this post I’ll walk through a simple, practical human handoff: deciding when to hand off, packaging context for the person who takes over, notifying the team, keeping the bot quiet afterwards, and handling the moments when nobody is online. The code is illustrative Python, so adapt it to your own stack.
What a good handoff does
A handoff is more than a “contact us” link. A good one:
- Triggers at the right moments, not too early and not too late.
- Passes the full context, so the customer never has to repeat themselves.
- Reaches a person quickly, through a channel your team actually watches.
- Stops the bot from talking over the human.
- Sets honest expectations when nobody is available.
- Leaves a record you can learn from.
The flow at a glance
- A customer message arrives.
- The bot retrieves content and drafts an answer.
- A decision function checks whether to hand off.
- If yes, the system builds a payload, saves it, notifies the team and marks the session as waiting for a human.
- While the session is waiting or with a human, the bot stays silent.
- A person replies, and the session closes when the issue is resolved.
Step 1: Decide when to hand off
Start with a small set of clear triggers. You can add more later, based on what you see in real conversations.
- The customer asks for a person. Always honour this immediately.
- There is no supporting source. If retrieval found nothing relevant, the bot has nothing to base an answer on.
- Retrieval confidence is low. The best match is a weak one.
- The topic is sensitive. Complaints, disputes and requests that involve money usually need a person.
from dataclasses import dataclass
HUMAN_REQUEST_PHRASES = [
'human', 'real person', 'representative',
'talk to someone', 'speak to someone', 'customer service',
]
SENSITIVE_TOPICS = ['complaint', 'chargeback', 'legal', 'cancel my account']
@dataclass
class HandoffDecision:
handoff: bool
reason: str = ''
def should_handoff(message, valid_sources, top_score, min_score=0.35):
text = message.lower()
if any(p in text for p in HUMAN_REQUEST_PHRASES):
return HandoffDecision(True, 'customer_requested_human')
if any(t in text for t in SENSITIVE_TOPICS):
return HandoffDecision(True, 'sensitive_topic')
if not valid_sources or top_score < min_score:
return HandoffDecision(True, 'no_supporting_source')
return HandoffDecision(False)
Two honest notes about this code:
- Keyword matching is crude. It’s a good starting point, but real conversations will show phrases you didn’t expect. Review them and extend the lists.
- The
min_scorevalue of 0.35 is a placeholder. The right threshold depends on your embedding model and content, so tune it on your own test questions.
Also think carefully about sensitive topics. A question about your refund policy can often be answered by the bot. A request for an actual refund usually needs a person. Draw that line deliberately.
Step 2: Package the context
The person who takes over should see everything they need on one screen: why the handoff happened, what the customer last said, the recent conversation and any contact details.
import time
def build_handoff_payload(session, decision):
return {
'session_id': session['id'],
'reason': decision.reason,
'created_at': int(time.time()),
'customer': session.get('customer', {}),
'last_message': session['messages'][-1]['text'],
'transcript': session['messages'][-10:],
'page_url': session.get('page_url'),
}
Including the page the customer was on is a small detail that helps a lot. If someone is stuck on the pricing page, your team already knows what they’re likely asking about.
Step 3: Notify the team where they already work
A handoff nobody notices is worse than no handoff. Send the alert to a channel your team actually watches, such as Slack, email or your helpdesk. Many tools accept a simple webhook.
import os
import requests
def notify_team(payload):
url = os.environ['HANDOFF_WEBHOOK_URL']
text = 'New chat handoff (' + payload['reason'] + '): ' + payload['last_message']
response = requests.post(url, json={'text': text}, timeout=5)
response.raise_for_status()
Keep the notification short and store the full payload in your own database or ticket system. That way the alert stays readable, and the full transcript lives somewhere your team can open it.
Step 4: Track the session state, and silence the bot
This is the step people forget. Once a person is handling the conversation, the bot must stop replying. Otherwise the customer gets answers from two sources, and the bot can contradict the human.
Use a small state machine:
from enum import Enum
class State(str, Enum):
BOT = 'bot'
WAITING_FOR_HUMAN = 'waiting_for_human'
HUMAN = 'human'
CLOSED = 'closed'
Then route every incoming message through one function:
def route(session, message, answer_fn, open_check):
session['messages'].append({'role': 'user', 'text': message})
if session['state'] in (State.WAITING_FOR_HUMAN, State.HUMAN):
return None # the bot stays silent while a person handles the chat
answer, valid_sources, top_score = answer_fn(message)
decision = should_handoff(message, valid_sources, top_score)
if not decision.handoff:
session['messages'].append({'role': 'bot', 'text': answer})
return answer
payload = build_handoff_payload(session, decision)
save_handoff(payload) # your database or ticket system
notify_team(payload)
session['state'] = State.WAITING_FOR_HUMAN
if open_check():
reply = 'Let me pass this to our team. They can see our chat so far.'
else:
reply = 'Our team is offline right now. Leave your email and they will reply as soon as they are back.'
session['messages'].append({'role': 'bot', 'text': reply})
return reply
Here answer_fn is your normal RAG answer function, returning the answer, the valid sources and the top retrieval score. save_handoff is a placeholder for however you store handoffs.
Step 5: Handle the hours when nobody is online
For many small teams, the busiest time for customers is exactly when nobody is working. Handle it honestly instead of promising an instant reply that won’t come.
from datetime import datetime
from zoneinfo import ZoneInfo
def is_open_now(tz='Europe/London', open_hour=9, close_hour=17):
now = datetime.now(ZoneInfo(tz))
return now.weekday() < 5 and open_hour <= now.hour < close_hour
When the team is offline, the bot should do three things:
- Say plainly that the team is offline.
- Collect an email or phone number.
- Tell the customer when to expect a reply, if you can commit to a time.
Use your own time zone and working hours, and remember public holidays.
Step 6: Say what is happening
Customers are comfortable with a handoff when it’s clear. Good messages are short and honest:
- “I’m not sure about this one. Let me pass you to our team.”
- “They can see our chat so far, so you won’t need to repeat yourself.”
- “Our team is offline right now. Leave your email and they’ll reply when they’re back.”
Avoid pretending the bot is a person, and avoid vague lines like “someone will be with you shortly” if that isn’t true.
Step 7: Test the handoff
Handoff bugs are easy to miss because they only appear in awkward moments. A few tests go a long way.
def test_customer_asks_for_human():
d = should_handoff('Can I talk to a real person?', valid_sources=[1], top_score=0.9)
assert d.handoff and d.reason == 'customer_requested_human'
def test_no_source_triggers_handoff():
d = should_handoff('What is your warranty on custom orders?', valid_sources=[], top_score=0.1)
assert d.handoff and d.reason == 'no_supporting_source'
def test_normal_question_stays_with_bot():
d = should_handoff('What are your opening hours?', valid_sources=[1], top_score=0.8)
assert not d.handoff
def test_bot_stays_silent_after_handoff():
session = {'id': 'a1', 'state': State.WAITING_FOR_HUMAN, 'messages': []}
reply = route(session, 'hello?', lambda m: ('hi', [1], 0.9), lambda: True)
assert reply is None
The last test protects against the most embarrassing bug: the bot answering over a human.
Measure it
A handoff is also data. Track these over time:
- Handoff rate: the share of conversations passed to a person.
-
Reasons: which triggers fire most often. A lot of
no_supporting_sourcemeans your content has gaps. - Time to first human reply: how long customers wait after a handoff.
- Resolution after handoff: how many handoffs end with the issue solved.
If the handoff rate is very high, the bot is not covering enough. If it is near zero, check that it isn’t refusing to hand off when it should.
Common mistakes
- The bot keeps answering after the handoff. Use a session state and stay silent.
- No context for the human. The customer has to repeat everything.
- A notification nobody sees. Send it where the team already works.
- Handoff that only works in office hours, with no offline path.
- A dead end. “Contact us” with no way to leave details.
- Triggering too eagerly, so the bot hands off questions it could answer, or too rarely, so customers get stuck.
- Storing transcripts without thinking about privacy. Conversations can contain personal data. Tell users they’re talking to an AI assistant, decide how long you keep transcripts, and check the rules that apply to you.
Putting it together
A human handoff is not a feature you bolt on at the end. It is part of the design: clear triggers, rich context, a notification that reaches someone, a bot that knows when to stop talking, and an honest message when nobody is around. Get those right and the bot’s limits stop being a weakness and become part of why customers trust it.
How do you decide when your bot should hand off: confidence scores, keywords, or something else? I’d like to compare approaches in the comments.
These notes come from AI chatbot projects we built for client websites at Techowdy.
AI assistance disclosure: this article was prepared with AI assistance and reviewed and fact-checked by the author before publication.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.