Build an AI Agent That Answers Customer Support Emails
Updated 2026-11-24
A customer support email agent watches a shared inbox, reads the customer’s question, matches your FAQ snippets, and creates a draft reply for a human to send. This guide layers retrieval-style prompting on top of the Gmail OAuth tools from Connect an AI agent to Gmail and never calls users.messages.send. For label-based sorting first, pair with Build an AI agent that triages Gmail. Last tested 2026-11-24.
Prerequisites
- Gmail API enabled and
credentials.jsonfrom Connect an AI agent to Gmail - Python 3.10+ and an OpenAI-compatible chat API key
- A plain-text or Markdown FAQ file your team maintains (shipping times, refund policy, hours)
Docs used:
Steps
1. Scope OAuth for read + draft (not send)
Reuse the Gmail connect guide’s token flow with scopes:
SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
]
Delete an old token.json if you previously authorized fewer scopes.
2. Load a small FAQ corpus
# support_agent.py
from pathlib import Path
FAQ = Path("faq.md").read_text(encoding="utf-8")
def retrieve_faq_snippets(question: str, limit: int = 3) -> str:
"""Naive keyword match; swap for vector search when your FAQ grows."""
hits = []
for block in FAQ.split("\n\n"):
if any(word.lower() in block.lower() for word in question.split()[:8]):
hits.append(block.strip())
return "\n\n".join(hits[:limit]) or FAQ[:2000]
Keep answers in faq.md so humans can audit what the model may cite.
3. List unread support threads
def list_support_messages(svc, query: str = "is:unread to:support@yourdomain.com newer_than:2d"):
resp = svc.users().messages().list(userId="me", q=query, maxResults=10).execute()
return resp.get("messages", [])
Adjust the query to your alias. Gmail documents search syntax in operators.
4. Build the draft prompt with grounded context
import openai
def draft_support_reply(customer_text: str, subject: str) -> str:
context = retrieve_faq_snippets(customer_text)
system = (
"You write concise support replies. Use ONLY facts from the FAQ context. "
"If the FAQ lacks an answer, say you will escalate and do not invent policy."
)
user = f"Subject: {subject}\n\nCustomer:\n{customer_text}\n\nFAQ:\n{context}"
resp = openai.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
)
return resp.choices[0].message.content.strip()
Wire draft_email(to, subject, body) from Connect an AI agent to Gmail after you extract the customer address from headers.
5. Loop messages and create drafts
For each unread message:
users.messages.getwithformat="full"and decode the plain-text body (same walker as the connect guide).- Call
draft_support_reply. - Call
users.drafts.createwith the reply body. - Optionally remove the
UNREADlabel after drafting so the queue does not stall.
Register the three Gmail functions plus a draft_support_for_message(id) wrapper in your agent loop from Build your first AI agent in Python if you want natural-language control.
6. Schedule or monitor
Run the script on a cron with Build an AI agent that runs on a schedule, or post a Slack summary with Connect an AI agent to Slack when new drafts are ready.
Common errors
Draft cites policies not in faq.md. Tighten the system prompt and shorten retrieve_faq_snippets. Never let the model invent refund windows or SLAs.
Invalid To header on draft create. Validate the customer address with parseaddr before calling drafts.create.
OAuth insufficient authentication scopes. Delete token.json and re-consent after you add gmail.compose.
Same thread drafted twice. Mark processed messages with a user label (see triage guide) or store processed IDs in SQLite.
FAQ
Does this agent send email automatically?
No. It creates drafts only. A human reviews and sends from Gmail.
Can I use Gmail MCP instead of Python?
Yes. Configure Gmail MCP server in Claude or Antigravity and paste the same FAQ into the prompt. This Python path is better when you need custom retrieval or scheduling.
How do I handle attachments?
Start with format="full" and skip non-text parts. For PDF invoices, add a separate extraction step before you draft a reply.
Where should escalation go?
Add an escalate_to_human tool that applies a Gmail label and notifies Slack. Do not let the model guess PII-heavy cases.
Related guides
- Connect an AI agent to Gmail (OAuth + draft tools)
- Build an AI agent that triages Gmail (labels + priority)
- Gmail MCP server (hosted MCP alternative)
- Build an AI agent that runs on a schedule
- Connect an AI agent to Slack (notify humans about drafts)
- OpenAI Agents SDK handoffs (route billing vs. technical agents)
- What is an AI agent?