The Intern That Never Sleeps
I once hired an intern named Kevin to handle customer emails. Kevin was great. But Kevin needed sleep. And lunch. And weekends. And sometimes Kevin would reply to a high-value lead with “lol idk” because he got bored.
Meanwhile, my friend Sarah just stopped checking her inbox. She built an AI agent instead. Her agent doesn’t sleep. It doesn’t get bored. It qualifies leads while she’s at the beach.
Today, you’re building Sarah’s agent. Not a toy. Not a demo. A real business automation that replaces the intern, the chaos, and the missed opportunities.
Why This Matters
Every time someone emails your business, you have a choice: respond in 5 minutes or lose them forever. Most businesses choose “lose them forever” because they’re drowning in manual work.
A basic AI agent does three things:
- It answers common questions instantly
- It qualifies if someone is a real buyer or just window shopping
- It routes hot leads to your phone while ignoring tire-kickers
This replaces: Your customer support intern, your lead screening process, and your anxiety about missing emails at 2 AM.
Business impact: Faster response times = more deals closed. Better qualification = less time wasted. 24/7 availability = you make money while sleeping.
What This Actually Is
An AI agent is a script with a brain. It listens to incoming messages (email, chat, form), thinks about what the person wants, and takes action based on rules you define.
What it is NOT: It’s not a robot that physically answers your phone. It’s not a magic box that prints money. It won’t write poetry or order pizza.
What it IS: A tireless worker that reads inputs, makes decisions, and triggers actions. Think of it as a factory worker on your digital assembly line.
Prerequisites
Zero coding? Perfect. We’ll use a simple Python script that you can copy-paste.
- A free Gmail account (for testing)
- Basic computer skills (you have these)
- 15 minutes of focus
- A desire to never answer “What’s your pricing?” manually again
If you can fill out a web form, you can build this agent.
Step-by-Step Tutorial
Step 1: Install Python (If You Haven’t)
Download Python from python.org. During installation, check “Add Python to PATH.” That’s it. One checkbox.
Step 2: Install Required Libraries
Open your terminal (Command Prompt on Windows, Terminal on Mac/Linux) and run:
pip install openai google-api-python-client google-auth-httplib2 google-auth-oauthlib
This gives your agent the brain (OpenAI) and the ears to listen to email (Google).
Step 3: Set Up Gmail API Access
Go to Google Cloud Console, create a project, enable the Gmail API, and download credentials as JSON. Save this file as credentials.json in your project folder.
Run this to authenticate once:
python quickstart.py
Where quickstart.py is Google’s sample code from their Gmail API docs. This creates a token.json file that lets your agent read emails.
Step 4: The Core Agent Script
Create a file called agent.py and paste this in:
import openai
import base64
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import os
# CONFIGURATION
openai.api_key = "YOUR_OPENAI_API_KEY"
GMAIL_TOKEN = "token.json" # Created in Step 3
CREDENTIALS = "credentials.json"
# Initialize Gmail service
def get_gmail_service():
creds = None
if os.path.exists(GMAIL_TOKEN):
creds = Credentials.from_authorized_user_file(GMAIL_TOKEN, ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send'])
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
return build('gmail', 'v1', credentials=creds)
# Extract email content
def get_email_content(service, msg_id):
msg = service.users().messages().get(userId='me', id=msg_id).execute()
payload = msg['payload']
headers = payload['headers']
for d in headers:
if d['name'] == 'From':
sender = d['value']
if d['name'] == 'Subject':
subject = d['value']
# Get body
parts = payload.get('parts', [])
data = parts[0]['body'].get('data', '')
body = base64.urlsafe_b64decode(data).decode('utf-8')
return sender, subject, body
# AI Decision Engine
def classify_and_respond(sender, subject, body):
prompt = f"""
You are a business automation agent. Analyze this email and decide what to do.
EMAIL:
From: {sender}
Subject: {subject}
Body: {body}
DECISION:
- If it's a sales inquiry or pricing question: respond with a friendly intro and ask for budget/timeline
- If it's a support question: provide a helpful answer or link to FAQ
- If it's spam/irrelevant: ignore
- If it's a serious buyer: flag as HIGH PRIORITY
Provide:
1. Action: (reply/ignore/priority)
2. Response draft (if reply)
3. Reason (one sentence)
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
max_tokens=200
)
return response.choices[0].message.content
# Send reply
def send_reply(service, to, subject, body):
message = f"""
From: me
To: {to}
Subject: Re: {subject}
{body}
"""
raw = base64.urlsafe_b64decode(message).encode('utf-8')
service.users().messages().send(userId='me', body={'raw': raw}).execute()
print(f"Replied to {to}")
# Main loop
def process_unread_emails():
service = get_gmail_service()
results = service.users().messages().list(userId='me', labelIds=['INBOX', 'UNREAD']).execute()
messages = results.get('messages', [])
for msg in messages:
sender, subject, body = get_email_content(service, msg['id'])
decision = classify_and_respond(sender, subject, body)
print(f"\nFrom: {sender}\nDecision: {decision}")
# Parse decision and act
if "priority" in decision.lower():
print("🚨 HIGH PRIORITY LEAD - Alerting owner!")
# Here you could add SMS via Twilio
elif "reply" in decision.lower():
# Extract draft response
lines = decision.split('\n')
response_body = "\n".join([l for l in lines if "Response draft" in l])
send_reply(service, sender, subject, response_body)
else:
print("Ignoring email")
# Mark as read
service.users().messages().modify(userId='me', id=msg['id'], body={'removeLabelIds': ['UNREAD']}).execute()
if __name__ == "__main__":
process_unread_emails()
print("\nAgent finished shift. Back to sleep.")
Step 5: Run Your Agent
python agent.py
Watch it scan your inbox. Send yourself a test email: “Hey, I’m interested in your services. What’s your pricing?” and see it reply within seconds.
Complete Automation Example: The Real Estate Lead Machine
Here’s how a real estate agent uses this exact agent:
The Trigger: Someone visits their website and emails “Is 123 Main Street still available?”
The Agent’s Process:
- Reads email at 11 PM
- Classifies as “hot lead” (specific property + buying intent)
- AI writes a personalized reply: “Yes! It’s available. I can show it Saturday. What’s your budget?”
- Sends reply immediately
- Flags as HIGH PRIORITY and sends SMS to agent’s phone: “New hot lead: 123 Main St. Check email.”
The Result: Lead gets instant response while competitors sleep. Agent wakes up to a qualified appointment, not a cold inbox.
Real Business Use Cases
- Consulting Firm: Receives 30 inquiries/day. Agent filters out “just curious” people and only replies to those with budgets over $10K, saving 10 hours/week.
- E-commerce Store: Answers “Where’s my order?” by checking order status via API, reducing support tickets by 40%.
- Freelance Designer: Agent replies with portfolio links and asks about project scope, then auto-books intro calls on Calendly.
- Recruiter: Screens job applicants by asking about visa status and salary expectations, only forwarding qualified candidates.
- SaaS Startup: Handles trial user questions and automatically upgrades users who ask about pricing, capturing revenue while founders sleep.
Common Mistakes & Gotchas
- Running too fast: Add a 5-second delay between emails to avoid rate limits.
- Using GPT-4 for everything: GPT-3.5 is cheaper and fine for classification.
- Forgetting to filter spam: Add a rule to ignore emails from @gmail.com if you only want business domains.
- No human oversight: For the first week, CC yourself on all replies to catch errors.
- Running on your laptop: Eventually, deploy this to a cloud server so it runs 24/7.
How This Fits Into a Bigger Automation System
This agent is the front door of your automation factory. Now connect it to:
- CRM: Hot leads get auto-added to HubSpot/Salesforce with full email thread
- Voice Agent: When high-priority lead arrives, AI calls your phone and reads the email aloud
- Multi-agent Workflow: Agent 1 qualifies → Agent 2 drafts proposal → Agent 3 schedules meeting
- RAG System: Agent searches your knowledge base for answers to technical questions
What to Learn Next
You just built the brain. Next lesson: Give It a Voice. We’ll connect this agent to a phone number so it can answer calls, take messages, and even make outbound calls to your hottest leads.
Meet me in the next lesson. We’re going omnichannel.

