Writing a good email can sometimes take more time than expected, especially when you need to maintain the right tone and include several important details. The AI Email Writer solves this by allowing users to provide a few basic details and automatically generating a complete email.
The application is built with Python and Streamlit, while the actual text generation is handled by Google's FLAN-T5 model through Hugging Face Transformers. The user can select the tone and length of the email, enter the purpose and important points, and the application generates a ready-to-use email.
One useful part of this project is that the AI model is only responsible for generating the email body. The application itself creates the subject, greeting, and closing. This gives the final email a more consistent structure.
Table of Contents
Technologies Used
The project uses four main technologies:
- Python – Handles the application logic.
- Streamlit – Creates the web interface.
- PyTorch – Loads and runs the AI model.
- Hugging Face Transformers – Provides the tokenizer and pretrained FLAN-T5 model.
The model used in the project is:
MODEL_NAME = "google/flan-t5-base"FLAN-T5 is a text-to-text Transformer model, which makes it suitable for tasks such as generating an email from a natural-language instruction.
Importing the Required Libraries
The application starts with these imports:import re import streamlit as st import torch from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
Here, re is used for cleaning unwanted text from the AI's response. Streamlit handles the user interface, while PyTorch is responsible for running the model.
The Hugging Face transformers library provides AutoTokenizer and AutoModelForSeq2SeqLM, which are used to prepare the input and load the FLAN-T5 model.
Loading the AI Model
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
The tokenizer converts the prompt into tokens that the model can understand. The AutoModelForSeq2SeqLM class loads the FLAN-T5 sequence-to-sequence model.
The application also checks whether a GPU is available:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
If CUDA is available, the model runs on the GPU; otherwise, it runs on the CPU.The function is decorated with:
@st.cache_resourceThis is important for Streamlit because the model does not need to be loaded again every time the application reruns.
How the Email Is Generated
The main AI generation happens inside the ai_body() function Instead of simply giving the model a few keywords, the application builds a detailed prompt:
prompt = f"""Write the body of an email about this request.
Request: {purpose}
Details to include:
{key_points}
Tone: {tone}
Length: {length_words}
...
"""
This is an example of prompt engineering. The application tells FLAN-T5 what the email is about, what information must be included, what tone should be used, and approximately how long the response should be.
The prompt also specifically tells the model not to generate the subject, greeting, signature, labels, or bullet points. The model should start directly with the email body.
Controlling Email Length
The user can select three lengths:
"Short": "about 45-70 words" "Medium": "about 80-120 words" "Detailed": "about 120-170 words"
The generation settings also change depending on the selected length:
max_new_tokens={
"Short": 100,
"Medium": 150,
"Detailed": 220
}[length]
This gives the user control over how much detail the generated email contains.Generating the Text with FLAN-T5
After creating the prompt, it is converted into tensors:
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=512
)
The model then generates the response:
output = model.generate(
**inputs,
max_new_tokens=...,
num_beams=5,
do_sample=False,
no_repeat_ngram_size=3,
repetition_penalty=1.15
)
A few settings are particularly important.
num_beams=5 uses beam search to consider multiple possible outputs and select a better one. do_sample=False makes the generation deterministic rather than randomly sampling words. no_repeat_ngram_size=3 helps prevent the model from repeatedly generating the same three-word sequence.
The repetition_penalty=1.15 further discourages repetitive text.
Cleaning the AI Output
Small language models can sometimes return unwanted labels such as:Email Body:
or repeat parts of the instructions.
The project handles this with the clean_ai_output() function. Regular expressions are used to remove unwanted labels such as "email body", "response", "recipient/context", and "important points".
This is a simple but useful post-processing step that makes the generated output cleaner.
Building the Complete Email
One of the interesting design choices in this project is that FLAN-T5 does not generate the entire email.
The model generates only the body. The application then creates the rest.
For example, the greeting changes according to the selected tone:
greeting = {
"Formal": "Dear Sir/Madam,",
"Professional": "Dear Sir/Madam,",
"Friendly": "Hello,",
"Polite": "Dear Sir/Madam,",
"Concise": "Hello,"
}[tone]
closing = {
"Formal": "Yours sincerely,\n[Your Name]",
"Professional": "Best regards,\n[Your Name]",
"Friendly": "Best,\n[Your Name]",
"Polite": "Kind regards,\n[Your Name]",
"Concise": "Regards,\n[Your Name]"
}[tone]
Finally, the application combines the subject, greeting, generated body, and closing into one complete email.Fallback Mechanism
The project also includes a fallback system.
Sometimes an AI model may produce an incomplete response or accidentally return part of the prompt instead of a proper email body. The application checks the generated text for problems such as:
"recipient/context:" "important points:" "write the body" "do not write" "tone:" "length:"
It also checks whether the generated body contains fewer than 20 words.
If the output fails these checks, fallback_body() creates a simple email using the user's purpose and important points.
This makes the application more reliable instead of depending completely on the model's output.
Streamlit User Interface
The user interface is created with Streamlit.
Users provide three main inputs:
- Recipient / Context
- Purpose of the Email
- Important Points
The sidebar provides two additional controls:
- Tone: Professional, Formal, Friendly, Polite, or Concise
- Length: Short, Medium, or Detailed
After clicking Generate Email, the application displays the generated email inside a text area.
The user can also download it as:
generated_email.txt
There is also a Clear button that resets the application.
Validation
Before generating an email, the application checks whether the required fields have been filled.
For example:
if not recipient.strip():
st.warning("Please enter the recipient or context.")
Similar checks are performed for the purpose and important points.
This prevents the model from being called with incomplete information.
How the Complete System Works
The overall workflow is quite straightforward:
User enters email details
↓
Selects tone and length
↓
Application creates a prompt
↓
FLAN-T5 generates the email body
↓
AI output is cleaned and validated
↓
Fallback is used if necessary
↓
Subject + Greeting + Body + Closing
↓
Complete email is displayed
↓
User can download the email
The combination of AI generation and application-controlled formatting is what makes the output more predictable.Requirements
The project uses the following dependencies:streamlit>=1.40.0 transformers>=4.45.0,<5.0.0 torch>=2.2.0 sentencepiece>=0.2.0The application can be started with:
pip install -r requirements.txt streamlit run app.py
Conclusion
The AI Email Writer combines a pretrained FLAN-T5 Transformer model with a simple Streamlit interface to make email writing faster and easier. Instead of asking the model to create everything, the application uses AI specifically for the email body and handles the subject, greeting, closing, formatting, validation, and fallback logic itself. This gives the application more control over the final output. With tone and length controls, output cleaning, GPU support, and a fallback mechanism, the project demonstrates how a pretrained language model can be integrated into a practical AI application.Frequently Asked Questions (FAQs)
1.Which AI model is used?2.Where is Hugging Face used?The project uses Google's google/flan-t5-base model.
3.Does the AI generate the complete email?Hugging Face Transformers is used through AutoTokenizer and AutoModelForSeq2SeqLM to load FLAN-T5 and generate the email body.
4.How is the email tone controlled?No. The AI generates only the email body. The application creates the subject, greeting, and closing.
5.What happens if the AI generates a bad response?The selected tone is included in the prompt, and the application also selects an appropriate greeting and closing.
6.Why is PyTorch used?The application checks the generated text and uses a predefined fallback email if the response is too short or contains unwanted prompt-like content.
7.Can the generated email be downloaded?PyTorch loads and runs the FLAN-T5 model and allows the application to use either a GPU or CPU.
Yes. The application provides a download button that saves the email as generated_email.txt.
0 Comments