Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add Email Auto Responder - automated email triage and response agent

Tiioluwanicb2da10bbdfc
diff --git a/ai_agents/email_auto_responder/.env.example b/ai_agents/email_auto_responder/.env.example
new file mode 100644
index 0000000..11d295e
--- /dev/null
+++ b/ai_agents/email_auto_responder/.env.example
@@ -0,0 +1,12 @@
+# NVIDIA NIM API key for GLM-5.1
+NVIDIA_API_KEY=your_nvidia_api_key_here
+
+# Gmail account used for IMAP access
+
+# Gmail App Password (not your regular Gmail password)
+# Create one at: https://myaccount.google.com/apppasswords
+APP_PASSWORD=your_gmail_app_password_here
+
+# Optional: maximum unread emails to process per run
+MAX_EMAILS=5
diff --git a/ai_agents/email_auto_responder/.gitignore b/ai_agents/email_auto_responder/.gitignore
new file mode 100644
index 0000000..e2ea3a1
--- /dev/null
+++ b/ai_agents/email_auto_responder/.gitignore
@@ -0,0 +1,5 @@
+.env
+.venv/
+__pycache__/
+*.pyc
+.streamlit/secrets.toml
diff --git a/ai_agents/email_auto_responder/README.md b/ai_agents/email_auto_responder/README.md
new file mode 100644
index 0000000..fff835b
--- /dev/null
+++ b/ai_agents/email_auto_responder/README.md
@@ -0,0 +1,104 @@
+# Email Auto Responder
+> An automated email triage and response agent that reads unread Gmail messages, classifies intent, and drafts professional replies.
+
+## Overview
+Email Auto Responder helps you process incoming Gmail messages faster. The app fetches unread emails over IMAP, uses CrewAI agents powered by GLM-5.1 via NVIDIA NIM to classify each message and draft a reply, then presents the original email alongside the suggested response in a clean Streamlit dashboard.
+
+## Demo
+<img src="assets/demo.gif" alt="Email Auto Responder demo showing Gmail triage and draft replies in the Streamlit dashboard" width="800"/>
+
+## Features
+- Fetch unread Gmail messages via IMAP
+- Classify emails into seven categories: inquiry, complaint, follow-up, marketing, notification, newsletter, and spam
+- Determine whether each message needs a reply via a separate needs_response flag
+- Generate professional draft replies only when a response is needed
+- Color-coded category badges and response-needed indicators in the UI
+- Friendly empty state when no unread emails exist
+- Sidebar with app description and example use cases
+
+## Tech Stack
+**Agent Framework:**
+- CrewAI Flows - agent orchestration and flow management
+
+**LLM:**
+- GLM-5.1 (z-ai/glm-5.1) via NVIDIA NIM - OpenAI-compatible API
+
+**Email:**
+- Gmail via IMAP using Python imaplib
+
+**UI:**
+- Streamlit
+
+## Prerequisites
+- Python 3.10+
+- NVIDIA API key - get one at https://build.nvidia.com
+- Gmail account with IMAP enabled
+- Gmail App Password for IMAP authentication - get one at https://myaccount.google.com/apppasswords
+
+## Setup
+
+### 1. Clone the Repository
+```bash
+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git
+cd Hands-On-AI-Engineering/ai_agents/email_auto_responder
+```
+
+If you already have this folder locally (for example as a standalone checkout or copy), skip to step 2.
+
+### 2. Create Virtual Environment
+```bash
+python -m venv .venv
+.venv\Scripts\activate # Windows
+source .venv/bin/activate # macOS/Linux
+```
+
+### 3. Install Dependencies
+```bash
+pip install -r requirements.txt
+```
+
+### 4. Configure Environment Variables
+```bash
+cp .env.example .env # macOS/Linux
+copy .env.example .env # Windows CMD
+Copy-Item .env.example .env # PowerShell
+```
+Open `.env` and add your credentials:
+- `NVIDIA_API_KEY` - your NVIDIA NIM API key
+- `EMAIL_ADDRESS` - your Gmail address
+- `APP_PASSWORD` - your Gmail App Password
+
+### 5. Run the App
+```bash
+streamlit run app.py
+```
+
+## Usage
+Click **Check Emails** in the dashboard to fetch and process your unread Gmail messages. The agent classifies each email and drafts a reply for messages that need a response.
+
+Example email types handled:
+- Inquiry from a client asking about pricing
+- Complaint about a delayed order
+- Follow-up on a previous conversation
+- Newsletter or marketing email (no reply needed)
+- Spam (no reply needed)
+
+## Project Structure
+email_auto_responder/
+├── app.py # Streamlit UI
+├── flow.py # CrewAI Flow orchestration
+├── crew.py # CrewAI agents and tasks
+├── email_utils.py # Gmail IMAP helpers
+├── requirements.txt
+├── .env.example
+├── .gitignore
+├── README.md
+└── assets/
+ └── demo.gif
+
+## How It Works
+1. The user clicks **Check Emails** in the Streamlit UI.
+2. The CrewAI Flow fetches unread emails from Gmail via IMAP.
+3. The Email Classifier agent assigns each email a category and a needs_response flag.
+4. The Response Writer agent drafts a professional reply only when needs_response is true.
+5. Results are displayed in the UI with the original email, category badge, and draft response when applicable.
diff --git a/ai_agents/email_auto_responder/app.py b/ai_agents/email_auto_responder/app.py
new file mode 100644
index 0000000..36c72dd
--- /dev/null
+++ b/ai_agents/email_auto_responder/app.py
@@ -0,0 +1,188 @@
+"""Streamlit dashboard for email triage and draft reply generation."""
+
+import streamlit as st
+from dotenv import load_dotenv
+
+from flow import run_email_flow
+
+load_dotenv()
+
+st.set_page_config(
+ page_title="Email Auto Responder",
+ page_icon="📧",
+ layout="wide",
+)
+
+CATEGORY_STYLES = {
+ "inquiry": {"label": "Inquiry", "color": "#1E88E5", "background": "#E3F2FD"},
+ "complaint": {"label": "Complaint", "color": "#E53935", "background": "#FFEBEE"},
+ "follow_up": {"label": "Follow Up", "color": "#FB8C00", "background": "#FFF3E0"},
+ "marketing": {"label": "Marketing", "color": "#8E24AA", "background": "#F3E5F5"},
+ "notification": {"label": "Notification", "color": "#00897B", "background": "#E0F2F1"},
+ "newsletter": {"label": "Newsletter", "color": "#43A047", "background": "#E8F5E9"},
+ "spam": {"label": "Spam", "color": "#757575", "background": "#F5F5F5"},
+}
+
+NO_RESPONSE_MESSAGES = {
+ "marketing": "No response generated. This is a promotional email.",
+ "notification": "No response generated. This is an automated notification.",
+ "newsletter": "No response generated. This is a newsletter or content digest.",
+ "spam": "No response generated. This message was classified as spam.",
+}
+
+
+def render_category_badge(category: str) -> None:
+ """Render a color-coded HTML badge for the email category."""
+ style = CATEGORY_STYLES.get(category, CATEGORY_STYLES["inquiry"])
+ st.markdown(
+ f"""
+ <span style="
+ background-color: {style['background']};
+ color: {style['color']};
+ padding: 0.25rem 0.75rem;
+ border-radius: 999px;
+ font-size: 0.85rem;
+ font-weight: 600;
+ border: 1px solid {style['color']};
+ ">
+ {style['label']}
+ </span>
+ """,
+ unsafe_allow_html=True,
+ )
+
+
+def render_needs_response_indicator(needs_response: bool) -> None:
+ """Render a badge indicating whether the email needs a reply."""
+ if needs_response:
+ label = "Response needed"
+ color = "#1565C0"
+ background = "#E3F2FD"
+ else:
+ label = "No response needed"
+ color = "#616161"
+ background = "#EEEEEE"
+
+ st.markdown(
+ f"""
+ <span style="
+ background-color: {background};
+ color: {color};
+ padding: 0.2rem 0.6rem;
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 500;
+ border: 1px solid {color};
+ ">
+ {label}
+ </span>
+ """,
+ unsafe_allow_html=True,
+ )
+
+
+def get_no_response_message(category: str) -> str:
+ """Return the UI message shown when no draft reply is generated."""
+ return NO_RESPONSE_MESSAGES.get(
+ category,
+ "No response generated. This message does not require a reply.",
+ )
+
+
+def render_email_card(email_result: dict) -> None:
+ """Render a bordered card with email details and draft response."""
+ with st.container(border=True):
+ header_col, badge_col = st.columns([4, 1])
+ with header_col:
+ st.markdown(f"**From:** {email_result['sender']}")
+ st.markdown(f"**Subject:** {email_result['subject']}")
+ with badge_col:
+ render_category_badge(email_result.get("category", "inquiry"))
+ render_needs_response_indicator(
+ email_result.get("needs_response", True)
+ )
+
+ st.markdown("##### Original Email")
+ st.text_area(
+ "Original message",
+ value=email_result.get("body", ""),
+ height=180,
+ disabled=True,
+ label_visibility="collapsed",
+ )
+
+ st.markdown("##### Drafted Response")
+ draft_response = email_result.get("draft_response")
+ needs_response = email_result.get("needs_response", True)
+ category = email_result.get("category", "inquiry")
+
+ if not needs_response or not draft_response:
+ st.info(get_no_response_message(category))
+ else:
+ st.text_area(
+ "Draft response",
+ value=draft_response,
+ height=180,
+ disabled=True,
+ label_visibility="collapsed",
+ )
+
+
+def main() -> None:
+ """Run the Streamlit email auto responder dashboard."""
+ with st.sidebar:
+ st.title("Email Auto Responder")
+ st.markdown(
+ """
+ An automated email triage and response agent that reads unread Gmail
+ messages, classifies their intent across seven categories, flags whether
+ each message needs a reply, and drafts professional responses when needed.
+ """
+ )
+ st.markdown("---")
+ st.markdown("**Example use cases**")
+ st.markdown(
+ """
+ - Triage customer support inbox by intent
+ - Draft first-pass replies for inquiries and follow-ups
+ - Flag complaints for priority follow-up
+ - Skip replies for marketing, notifications, and newsletters
+ - Filter spam before manual review
+ """
+ )
+ st.markdown("---")
+ st.caption("Configure NVIDIA_API_KEY, EMAIL_ADDRESS, and APP_PASSWORD in .env")
+
+ st.title("Email Auto Responder")
+ st.markdown(
+ "Click **Check Emails** to fetch unread Gmail messages and generate draft replies."
+ )
+
+ if "results" not in st.session_state:
+ st.session_state.results = []
+ st.session_state.error = None
+ st.session_state.checked = False
+
+ if st.button("Check Emails", type="primary", use_container_width=False):
+ with st.spinner("Fetching and processing emails..."):
+ flow_output = run_email_flow()
+ st.session_state.results = flow_output.get("results", [])
+ st.session_state.error = flow_output.get("error")
+ st.session_state.checked = True
+
+ if st.session_state.error:
+ st.error(st.session_state.error)
+
+ if st.session_state.checked and not st.session_state.error:
+ if not st.session_state.results:
+ st.info(
+ "No unread emails found. Your inbox is clear, or all messages have already been read."
+ )
+ else:
+ st.success(f"Processed {len(st.session_state.results)} unread email(s).")
+ for email_result in st.session_state.results:
+ render_email_card(email_result)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ai_agents/email_auto_responder/assets/demo.gif b/ai_agents/email_auto_responder/assets/demo.gif
new file mode 100644
index 0000000..8118f3f
Binary files /dev/null and b/ai_agents/email_auto_responder/assets/demo.gif differ
diff --git a/ai_agents/email_auto_responder/crew.py b/ai_agents/email_auto_responder/crew.py
new file mode 100644
index 0000000..0569a84
--- /dev/null
+++ b/ai_agents/email_auto_responder/crew.py
@@ -0,0 +1,241 @@
+import json
+import os
+import re
+
+from crewai import Agent, Crew, LLM, Process, Task
+from dotenv import load_dotenv
+
+load_dotenv()
+
+CATEGORY_NEEDS_RESPONSE: dict[str, bool] = {
+ "inquiry": True,
+ "complaint": True,
+ "follow_up": True,
+ "marketing": False,
+ "notification": False,
+ "newsletter": False,
+ "spam": False,
+}
+
+VALID_CATEGORIES = set(CATEGORY_NEEDS_RESPONSE.keys())
+
+_CATEGORY_ALIASES: dict[str, str] = {
+ "follow-up": "follow_up",
+ "followup": "follow_up",
+ "follow up": "follow_up",
+}
+
+
+def get_llm() -> LLM:
+ """Create the NVIDIA NIM LLM client from environment config."""
+ api_key = os.getenv("NVIDIA_API_KEY")
+ if not api_key:
+ raise ValueError("NVIDIA_API_KEY must be set in the environment.")
+
+ return LLM(
+ model="z-ai/glm-5.1",
+ provider="openai",
+ base_url="https://integrate.api.nvidia.com/v1",
+ api_key=api_key,
+ )
+
+
+def normalize_category(raw_category: str) -> str:
+ """Map raw classifier output to a valid category name."""
+ cleaned = raw_category.strip().lower().replace("-", "_")
+ cleaned = _CATEGORY_ALIASES.get(cleaned.replace("_", " "), cleaned)
+ cleaned = cleaned.replace(" ", "_")
+
+ if cleaned in VALID_CATEGORIES:
+ return cleaned
+
+ if re.search(r"\b(not|non|no)[_\s-]?spam\b", cleaned):
+ for category in sorted(VALID_CATEGORIES - {"spam"}, key=len, reverse=True):
+ if re.search(rf"\b{category}\b", cleaned):
+ return category
+ return "inquiry"
+
+ for category in sorted(VALID_CATEGORIES, key=len, reverse=True):
+ pattern = category.replace("_", "[_\\s-]?")
+ if re.search(rf"\b{pattern}\b", cleaned):
+ return category
+
+ return "inquiry"
+
+
+def parse_classify_output(raw: str) -> tuple[str, bool]:
+ """Parse classifier output into category and needs_response values."""
+ text = raw.strip()
+
+ json_match = re.search(r"\{[^{}]*\}", text, re.DOTALL)
+ if json_match:
+ try:
+ data = json.loads(json_match.group())
+ category = normalize_category(str(data.get("category", "inquiry")))
+ needs_response = data.get("needs_response")
+ if isinstance(needs_response, bool):
+ return category, needs_response
+ if isinstance(needs_response, str):
+ parsed = needs_response.strip().lower() in ("true", "yes", "1")
+ return category, parsed
+ except (json.JSONDecodeError, TypeError, ValueError):
+ pass
+
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
+ category = normalize_category(lines[0] if lines else text)
+ needs_response = CATEGORY_NEEDS_RESPONSE[category]
+
+ for line in lines:
+ lower_line = line.lower()
+ if "needs_response" in lower_line:
+ if "false" in lower_line or "no" in lower_line.split(":")[-1]:
+ needs_response = False
+ elif "true" in lower_line or "yes" in lower_line.split(":")[-1]:
+ needs_response = True
+ break
+
+ return category, needs_response
+
+
+class EmailProcessingCrew:
+ """CrewAI agents and tasks for email classification and reply drafting."""
+
+ def __init__(self) -> None:
+ """Initialize the crew with a configured LLM."""
+ self.llm = get_llm()
+
+ def email_classifier(self) -> Agent:
+ """Return the agent that classifies email intent."""
+ return Agent(
+ role="Email Classifier",
+ goal=(
+ "Classify incoming emails into exactly one category and determine "
+ "whether the message needs a human reply."
+ ),
+ backstory=(
+ "You are an expert email triage specialist who quickly identifies "
+ "customer intent, promotional content, automated alerts, and malicious "
+ "messages. You distinguish legitimate marketing and notifications from "
+ "actual spam, and you never miscategorize urgent complaints."
+ ),
+ llm=self.llm,
+ verbose=True,
+ )
+
+ def response_writer(self) -> Agent:
+ """Return the agent that drafts email replies."""
+ return Agent(
+ role="Response Writer",
+ goal=(
+ "Draft professional, concise email replies that address the sender's "
+ "needs while matching the tone of the original message."
+ ),
+ backstory=(
+ "You are a skilled customer communications expert with years of "
+ "experience writing clear, helpful, and empathetic email responses "
+ "for support and sales teams."
+ ),
+ llm=self.llm,
+ verbose=True,
+ )
+
+ def classify_task(self, email_data: dict[str, str]) -> Task:
+ """Build the classification task for a single email."""
+ return Task(
+ description=(
+ "Classify the following email and decide if it needs a reply.\n\n"
+ f"Sender: {email_data['sender']}\n"
+ f"Subject: {email_data['subject']}\n"
+ f"Body:\n{email_data['body']}\n\n"
+ "Choose exactly one category:\n"
+ "- inquiry: customer question, project ask, or request for information\n"
+ "- complaint: billing issue, service problem, or dissatisfaction\n"
+ "- follow_up: checking on a prior thread or awaiting an update\n"
+ "- marketing: promotional offers, product announcements, or webinar invites "
+ "from known senders\n"
+ "- notification: automated alerts the user subscribed to, such as job alerts, "
+ "shipping updates, or receipts\n"
+ "- newsletter: recurring content digests or blog subscriptions\n"
+ "- spam: malicious, phishing, scam, or unsolicited junk ONLY\n\n"
+ "Important: Do not use spam for legitimate marketing or notification emails.\n\n"
+ "Return ONLY valid JSON with no markdown fences:\n"
+ '{"category": "<category>", "needs_response": <true or false>}\n'
+ "Use snake_case category values. Set needs_response to true only for "
+ "inquiry, complaint, and follow_up."
+ ),
+ expected_output=(
+ 'JSON object: {"category": "inquiry", "needs_response": true}'
+ ),
+ agent=self.email_classifier(),
+ )
+
+ def response_task(self, email_data: dict[str, str], classify_task: Task) -> Task:
+ """Build the reply drafting task for a single email."""
+ return Task(
+ description=(
+ "Write a professional, concise reply to the email below.\n\n"
+ f"Sender: {email_data['sender']}\n"
+ f"Subject: {email_data['subject']}\n"
+ f"Body:\n{email_data['body']}\n\n"
+ "Use the classification JSON from the previous task. "
+ "If needs_response is false, or the category is marketing, notification, "
+ "newsletter, or spam, respond with exactly: NO_RESPONSE\n\n"
+ "Otherwise, write a complete reply body without a subject line prefix. "
+ "Match the sender's tone and keep the response concise."
+ ),
+ expected_output=(
+ "A professional email reply body, or NO_RESPONSE when no reply is needed"
+ ),
+ agent=self.response_writer(),
+ context=[classify_task],
+ )
+
+ def crew(self) -> Crew:
+ """Return a base Crew with classifier and writer agents."""
+ return Crew(
+ agents=[self.email_classifier(), self.response_writer()],
+ tasks=[],
+ process=Process.sequential,
+ verbose=True,
+ )
+
+ def process_email(self, email_data: dict[str, str]) -> dict[str, str | bool | None]:
+ """Classify one email and return category, flags, and draft reply."""
+ classifier = self.email_classifier()
+ writer = self.response_writer()
+ classify = self.classify_task(email_data)
+ respond = self.response_task(email_data, classify)
+
+ processing_crew = Crew(
+ agents=[classifier, writer],
+ tasks=[classify, respond],
+ process=Process.sequential,
+ verbose=True,
+ )
+
+ result = processing_crew.kickoff()
+ category, needs_response = parse_classify_output(
+ str(result.tasks_output[0].raw)
+ )
+ raw_response = str(result.tasks_output[1].raw).strip()
+
+ draft_response: str | None
+ if not needs_response or raw_response.upper() == "NO_RESPONSE":
+ draft_response = None
+ else:
+ draft_response = re.sub(
+ r"^(subject:\s*.+\n+)",
+ "",
+ raw_response,
+ flags=re.IGNORECASE,
+ ).strip()
+
+ return {
+ "sender": email_data["sender"],
+ "subject": email_data["subject"],
+ "body": email_data["body"],
+ "category": category,
+ "needs_response": needs_response,
+ "draft_response": draft_response,
+ "message_id": email_data.get("message_id", ""),
+ }
diff --git a/ai_agents/email_auto_responder/email_utils.py b/ai_agents/email_auto_responder/email_utils.py
new file mode 100644
index 0000000..1bd5121
--- /dev/null
+++ b/ai_agents/email_auto_responder/email_utils.py
@@ -0,0 +1,141 @@
+import email
+import imaplib
+import os
+from email.header import decode_header
+from typing import Any
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+
+def decode_mime_header(value: str | None) -> str:
+ """Decode a MIME-encoded email header into plain text."""
+ if not value:
+ return ""
+
+ decoded_parts = decode_header(value)
+ result_parts: list[str] = []
+
+ for part, encoding in decoded_parts:
+ if isinstance(part, bytes):
+ result_parts.append(part.decode(encoding or "utf-8", errors="replace"))
+ else:
+ result_parts.append(part)
+
+ return " ".join(result_parts).strip()
+
+
+def parse_email_body(message: email.message.Message) -> str:
+ """Extract plain text or HTML body content from an email message."""
+ if message.is_multipart():
+ text_parts: list[str] = []
+ html_parts: list[str] = []
+
+ for part in message.walk():
+ content_type = part.get_content_type()
+ content_disposition = str(part.get("Content-Disposition", ""))
+
+ if "attachment" in content_disposition:
+ continue
+
+ payload = part.get_payload(decode=True)
+ if payload is None:
+ continue
+
+ charset = part.get_content_charset() or "utf-8"
+ decoded_text = payload.decode(charset, errors="replace")
+
+ if content_type == "text/plain":
+ text_parts.append(decoded_text)
+ elif content_type == "text/html" and not text_parts:
+ html_parts.append(decoded_text)
+
+ if text_parts:
+ return "\n".join(text_parts).strip()
+
+ if html_parts:
+ return html_parts[0].strip()
+
+ return ""
+
+ payload = message.get_payload(decode=True)
+ if payload is None:
+ return ""
+
+ charset = message.get_content_charset() or "utf-8"
+ return payload.decode(charset, errors="replace").strip()
+
+
+def parse_email_message(raw_email: bytes) -> dict[str, str]:
+ """Parse raw RFC822 bytes into sender, subject, and body fields."""
+ message = email.message_from_bytes(raw_email)
+
+ sender = decode_mime_header(message.get("From"))
+ subject = decode_mime_header(message.get("Subject"))
+ body = parse_email_body(message)
+
+ return {
+ "sender": sender,
+ "subject": subject or "(No subject)",
+ "body": body or "(No body content)",
+ }
+
+
+def fetch_unread_emails(
+ email_address: str | None = None,
+ app_password: str | None = None,
+ max_emails: int = 5,
+) -> list[dict[str, Any]]:
+ """Fetch unread inbox messages from Gmail over IMAP."""
+ email_address = email_address or os.getenv("EMAIL_ADDRESS")
+ app_password = app_password or os.getenv("APP_PASSWORD")
+
+ if not email_address or not app_password:
+ raise ValueError(
+ "EMAIL_ADDRESS and APP_PASSWORD must be set in the environment or passed as arguments."
+ )
+
+ mail = imaplib.IMAP4_SSL("imap.gmail.com")
+ mail.login(email_address, app_password)
+ mail.select("inbox")
+
+ try:
+ _, message_numbers = mail.search(None, "UNSEEN")
+ unread_ids = message_numbers[0].split()
+
+ if not unread_ids:
+ return []
+
+ selected_ids = unread_ids[-max_emails:]
+ emails: list[dict[str, Any]] = []
+
+ for message_id in selected_ids:
+ _, message_data = mail.fetch(message_id, "(RFC822)")
+ if not message_data or not message_data[0]:
+ continue
+
+ raw_email = message_data[0][1]
+ if not isinstance(raw_email, bytes):
+ continue
+
+ parsed = parse_email_message(raw_email)
+ parsed["message_id"] = message_id.decode()
+ emails.append(parsed)
+
+ return emails
+ finally:
+ mail.logout()
+
+
+def get_email_credentials() -> tuple[str, str]:
+ """Load Gmail address and app password from environment variables."""
+ email_address = os.getenv("EMAIL_ADDRESS")
+ app_password = os.getenv("APP_PASSWORD")
+
+ if not email_address or not app_password:
+ raise ValueError(
+ "Missing email credentials. Set EMAIL_ADDRESS and APP_PASSWORD in your .env file."
+ )
+
+ return email_address, app_password
diff --git a/ai_agents/email_auto_responder/flow.py b/ai_agents/email_auto_responder/flow.py
new file mode 100644
index 0000000..afaa4d0
--- /dev/null
+++ b/ai_agents/email_auto_responder/flow.py
@@ -0,0 +1,84 @@
+import os
+from typing import Any
+
+from crewai.flow import Flow, listen, start
+from dotenv import load_dotenv
+from pydantic import BaseModel, Field
+
+from crew import EmailProcessingCrew
+from email_utils import fetch_unread_emails, get_email_credentials
+
+load_dotenv()
+
+
+class ProcessedEmail(BaseModel):
+ """Structured result for a single processed email."""
+
+ sender: str = ""
+ subject: str = ""
+ body: str = ""
+ category: str = "inquiry"
+ needs_response: bool = True
+ draft_response: str | None = None
+ message_id: str = ""
+
+
+class EmailFlowState(BaseModel):
+ """Shared state for the email auto responder flow."""
+
+ emails: list[dict[str, Any]] = Field(default_factory=list)
+ results: list[ProcessedEmail] = Field(default_factory=list)
+ error: str | None = None
+
+
+class EmailAutoResponderFlow(Flow[EmailFlowState]):
+ """CrewAI flow that fetches unread emails and processes them."""
+
+ @start()
+ def fetch_emails(self) -> list[dict[str, Any]]:
+ """Fetch unread emails from Gmail via IMAP."""
+ try:
+ email_address, app_password = get_email_credentials()
+ emails = fetch_unread_emails(
+ email_address=email_address,
+ app_password=app_password,
+ max_emails=int(os.getenv("MAX_EMAILS", "5")),
+ )
+ self.state.emails = emails
+ return emails
+ except Exception as exc:
+ self.state.error = str(exc)
+ self.state.emails = []
+ return []
+
+ @listen(fetch_emails)
+ def process_emails(self, emails: list[dict[str, Any]]) -> list[ProcessedEmail]:
+ """Classify each email and generate draft replies when needed."""
+ if self.state.error:
+ return []
+
+ if not emails:
+ self.state.results = []
+ return []
+
+ crew = EmailProcessingCrew()
+ processed: list[ProcessedEmail] = []
+
+ for email_data in emails:
+ result = crew.process_email(email_data)
+ processed.append(ProcessedEmail(**result))
+
+ self.state.results = processed
+ return processed
+
+
+def run_email_flow() -> dict[str, Any]:
+ """Run the email flow and return processed results or an error."""
+ flow = EmailAutoResponderFlow()
+ flow.kickoff()
+
+ return {
+ "results": [result.model_dump() for result in flow.state.results],
+ "email_count": len(flow.state.emails),
+ "error": flow.state.error,
+ }
diff --git a/ai_agents/email_auto_responder/requirements.txt b/ai_agents/email_auto_responder/requirements.txt
new file mode 100644
index 0000000..8d49bc5
--- /dev/null
+++ b/ai_agents/email_auto_responder/requirements.txt
@@ -0,0 +1,4 @@
+crewai>=0.86.0
+streamlit>=1.32.0
+python-dotenv>=1.0.0
+openai>=1.0.0