In the age of digital-first customer experience, rapid and intelligent email routing is a game changer. By automatically classifying and routing customer emails based on their sentiment, organizations can prioritize urgent issues, de-escalate negative experiences, and streamline support operations. As we covered in our complete guide to AI workflow automation for customer experience, sentiment-driven routing is a foundational use case that deserves a deep, practical look. In this hands-on tutorial, you’ll build a robust, testable AI workflow that classifies incoming emails by sentiment and routes them to the appropriate support queue, using modern open-source tools.
Prerequisites
- Python 3.10+ (tested with Python 3.11)
- pip (Python package manager)
- Basic knowledge of Python and REST APIs
- Basic command-line skills
- HuggingFace Transformers (for sentiment analysis)
- FastAPI (for creating the routing API endpoint)
- Optional: An email provider or test mailbox (e.g., Gmail, Outlook) for integration
- Optional: Docker (for containerization and deployment)
This tutorial is ideal for developers, solution architects, and technical CX leads looking to automate customer email workflows using AI. For more advanced workflow orchestration tips, see our sibling article How to Map End-to-End Customer Experience Journeys with AI Workflow Automation.
Overview of the Workflow
- Receive a customer email (via API or mailbox polling)
- Analyze sentiment using a pre-trained AI model
- Route the email to the appropriate support queue (e.g.,
priority,standard,escalation) based on sentiment - Expose a REST API endpoint for integration with other systems (e.g., CRM, helpdesk)
Step 1: Set Up Your Python Environment
-
Create and activate a virtual environment:
python3 -m venv ai-email-routing-env source ai-email-routing-env/bin/activate
-
Upgrade pip and install dependencies:
pip install --upgrade pip pip install fastapi[all] uvicorn transformers torch
fastapi[all]: For the API serveruvicorn: ASGI server to run FastAPItransformersandtorch: For running the sentiment model
-
Test your environment:
python -c "import fastapi, transformers, torch; print('All dependencies installed!')"
Screenshot description: Terminal showing successful installation of FastAPI, transformers, and torch, with the message "All dependencies installed!"
Step 2: Build the Sentiment Analysis Component
-
Create a new Python file:
touch sentiment_router.py
-
Paste the following code for sentiment analysis:
from transformers import pipeline sentiment_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english") def analyze_sentiment(text): result = sentiment_pipeline(text)[0] label = result['label'] score = result['score'] # Map HuggingFace labels to routing categories if label == 'NEGATIVE' and score > 0.8: return 'escalation' elif label == 'NEGATIVE': return 'priority' elif label == 'POSITIVE': return 'standard' else: return 'standard'- Explanation: This function uses HuggingFace’s DistilBERT model to classify text as
POSITIVEorNEGATIVE. High-confidence negatives are routed toescalation, others topriorityorstandard.
- Explanation: This function uses HuggingFace’s DistilBERT model to classify text as
-
Test the function interactively:
python
from sentiment_router import analyze_sentiment print(analyze_sentiment("I am very unhappy with your service!")) print(analyze_sentiment("Thank you for your quick help!"))- Expected output:
escalationandstandard
- Expected output:
Screenshot description: Python REPL showing results of sentiment analysis, with "escalation" and "standard" printed for negative and positive test emails.
Step 3: Expose a REST API for Email Routing
-
Add FastAPI integration to
sentiment_router.py:from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class EmailRequest(BaseModel): subject: str body: str @app.post("/route-email/") async def route_email(request: EmailRequest): # Combine subject and body for sentiment analysis text = f"{request.subject}\n{request.body}" try: queue = analyze_sentiment(text) return {"queue": queue} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) -
Run your API server locally:
uvicorn sentiment_router:app --reload --port 8000
- Your API will be available at
http://127.0.0.1:8000
- Your API will be available at
-
Test the endpoint using
curlorhttpie:curl -X POST "http://127.0.0.1:8000/route-email/" \ -H "Content-Type: application/json" \ -d '{"subject": "Unacceptable delay", "body": "My order is late and I am very upset."}'- Expected response:
{"queue": "escalation"}
- Expected response:
Screenshot description: Terminal with curl command and JSON response showing the routed queue as "escalation".
Step 4: Integrate with Email Ingestion (Optional)
For a production setup, you’ll want to connect this API to your actual email inbox. This could be a cron job polling an IMAP inbox, or a webhook from your email provider. Here’s a simple example using imaplib (for Gmail) to fetch unread emails and post them to your API:
import imaplib
import email
import requests
IMAP_SERVER = "imap.gmail.com"
EMAIL_ACCOUNT = "your.email@gmail.com"
PASSWORD = "your-app-password"
def fetch_unread_emails():
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL_ACCOUNT, PASSWORD)
mail.select("inbox")
status, messages = mail.search(None, '(UNSEEN)')
for num in messages[0].split():
typ, data = mail.fetch(num, '(RFC822)')
msg = email.message_from_bytes(data[0][1])
subject = msg["subject"]
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body += part.get_payload(decode=True).decode()
else:
body = msg.get_payload(decode=True).decode()
# Post to routing API
resp = requests.post("http://localhost:8000/route-email/",
json={"subject": subject, "body": body})
print(f"Email routed to: {resp.json()['queue']}")
mail.logout()
- Note: For Gmail, you may need to use an App Password and enable IMAP in your account settings.
Screenshot description: Terminal output showing emails being fetched and routed, with queue assignments printed for each email.
Step 5: (Optional) Containerize Your Workflow with Docker
-
Create a
Dockerfile:FROM python:3.11-slim WORKDIR /app COPY . /app RUN pip install --upgrade pip RUN pip install fastapi[all] uvicorn transformers torch EXPOSE 8000 CMD ["uvicorn", "sentiment_router:app", "--host", "0.0.0.0", "--port", "8000"] -
Build and run the container:
docker build -t ai-email-router . docker run -p 8000:8000 ai-email-router - Test the API as before, now running in Docker.
Screenshot description: Docker build and run output, with API available on port 8000 and routing requests succeeding.
Common Issues & Troubleshooting
-
Model download is slow or fails: The first run of the HuggingFace pipeline downloads the model. Ensure stable internet. If behind a proxy, set
HTTPS_PROXYandHTTP_PROXYenvironment variables. - API returns 500 errors: Check stack traces in your terminal. Most issues relate to missing fields in the POST request or Python exceptions in your code.
- IMAP authentication fails: For Gmail and other providers with 2FA, use an App Password and ensure IMAP is enabled.
-
Docker container fails to start: Double-check the
CMDandEXPOSEstatements, and ensuresentiment_router.pyis in your build context. - Performance: For high volume, consider deploying on a GPU instance or using a lighter model. Batch processing and async queueing can also help.
Next Steps: Scaling and Expanding Your AI Email Routing Workflow
Congratulations! You’ve built a fully operational AI workflow for sentiment-based email routing. This is just the beginning—production deployments can integrate with CRMs, ticketing systems, or even trigger automated responses. For advanced orchestration, see our guide to AI workflow integration for customer onboarding and comparison of top AI CX workflow platforms.
- Integrate with your helpdesk (e.g., Zendesk, Salesforce) via API triggers
- Expand sentiment categories (e.g., neutral, mixed, urgent keywords)
- Automate responses for high-priority or positive feedback
- Monitor and retrain your model with real customer data
- Set up CSAT feedback collection with AI workflows to close the loop
- Plan for disaster recovery and workflow resilience
For a broader strategy, revisit our 2026 Guide to AI Workflow Automation for Customer Experience.
Summary
AI-powered sentiment routing is a practical, high-impact workflow that can be implemented with open source tools and integrated into your customer experience stack. By following this tutorial, you’ve gained hands-on experience with Python, FastAPI, and HuggingFace, and are well-positioned to scale your automation initiatives. For more deep dives and workflow blueprints, explore our related articles on AI workflow automation for regulatory compliance and end-to-end onboarding workflows.