Building an AI-Powered Email Formatting Web App with OpenAI and Langchain
Introduction
In today‘s fast-paced digital world, we often find ourselves dashing off emails without much thought to formatting, tone, or dialect. But what if there was a way to quickly convert those rough, unstructured thoughts into polished, professional emails at the click of a button?
Enter the AI-powered email assistant. By leveraging the cutting-edge language models from OpenAI and the helpful abstractions provided by the Langchain framework, we can build a web app that takes an informal email input and returns a formatted, tonally-appropriate version in just seconds.
In this step-by-step guide, we‘ll walk through the process of creating this email formatting app from scratch. Whether you‘re an experienced developer looking to experiment with AI or a tech-savvy writer searching for ways to streamline your composition process, this project has something for you.
So let‘s dive in and see how OpenAI and Langchain can supercharge your email game!
What the Email Formatting App Will Do
At a high level, our email assistant app will provide a simple web interface where users can:
- Paste in the rough content of their email
- Select options for the desired tone (formal or informal) and dialect (American or British English)
- Enter their OpenAI API key to access the language model
- Click a button to generate the formatted email output
Behind the scenes, the app will take the user‘s raw email input, construct a prompt instructing the OpenAI model to reformat the text with the specified tone and dialect, send that prompt to the API, and display the model‘s output in the browser.
Why Use OpenAI and Langchain
You may be wondering, why bother with a fancy AI model and specialized tools like Langchain for a seemingly straightforward task like email formatting? While it‘s true that you could build a basic formatter using standard string methods and regular expressions, the AI-driven approach has some major advantages:
-
OpenAI‘s models, like the powerful GPT-3.5, have been trained on massive amounts of online data, allowing them to understand and replicate human languages with remarkable nuance and fluency. By leveraging this preexisting "knowledge," we can build an email assistant that feels truly intelligent and contextualized.
-
Langchain provides a suite of tools for working with OpenAI and other language models, handling low-level details like API requests, prompt serialization, memory management, and more. Rather than spending time on plumbing, we can focus on prompt engineering and UX.
-
This app serves as a great testbed and jumping-off point for exploring more ambitious AI projects down the line. Once you‘ve mastered the basics of Streamlit, Langchain, and OpenAI, you can start building everything from chatbots to knowledgebases to storytellers and beyond!
Now that we‘ve established our app concept and stack, let‘s get into the nitty-gritty of implementation.
Setting Up the Streamlit App
To kick things off, we‘ll need to install the Streamlit package, which will serve as our web framework:
pip install streamlit
With that done, let‘s create a new Python script for our app and add some boilerplate to get a Streamlit application up and running:
import streamlit as st
st.set_page_config(page_title=‘Email Formatter‘, page_icon=‘:e-mail:‘, layout=‘wide‘)
st.title(‘✉️ Email Formatter‘)
Here we import the streamlit library, configure the page title and icon, and add a top-level title. Already we can run this script and see a live-updating Streamlit app in the browser!
streamlit run emailapp.py
Streamlit makes it incredibly easy to turn a Python script into an interactive web experience. Throughout this tutorial, we‘ll see how declarative functions like st.text_input, st.select_box, and st.button allow us to paint an interface without writing a single line of HTML or JavaScript.
Building the User Interface
Now that we have our Streamlit scaffold in place, let‘s flesh out the UI for collecting user input. We‘ll need:
- A multi-line text input box for pasting in a draft email
- Dropdown selectors for tone and dialect
- A text input box for the user‘s OpenAI API key
- A button to load a sample email for demonstration purposes
Here‘s how that translates to Streamlit code:
with st.form(key=‘formatter_inputs‘):
email_input = st.text_area("Paste your draft email here:", height=300)
col1, col2 = st.columns(2)
with col1:
tone = st.selectbox("Desired tone:", ["Formal", "Informal"])
with col2:
dialect = st.selectbox("English dialect:", ["American", "British"])
api_key = st.text_input("Enter your OpenAI API key:", type="password")
submitted = st.form_submit_button("Format email")
if st.button("Load example"):
email_input = """
Hey there! I was wondering if you‘d like to grab coffee someday
I‘d love to pick your brain about AI and stuff
No worries if you‘re too busy though
Anyways have a good one!
"""
Let‘s break this down:
-
We use a with block and st.form to group all our inputs into a single submittable form. This way, the formatting request will only trigger when the user explicitly clicks the submit button.
-
The draft email goes into a st.text_area, which creates an expandable box suitable for longer snippets of text. We set a default height of 300 pixels.
-
For tone and dialect, we use st.select_box to provide a dropdown of options. These widgets are arranged side by side using Streamlit‘s column system.
-
The API key input leverages st.text_input with the "password" type to mask the entered value. This is important since API keys should be kept secret!
-
Submitting the form triggers the email formatting (which we‘ll implement next), while an external st.button allows the user to populate the text area with a sample email for testing.
With just a dozen lines of code, we‘ve put together a complete interface for collecting user preferences. The real magic, though, happens when we pass this information to the OpenAI model. Let‘s look at how to construct an effective prompt.
Prompt Engineering with Langchain
The key to getting good results from a language model is crafting a clear, specific prompt that elicits the desired output. In our case, we want to provide the model with:
- The user‘s draft email content
- The desired tone (formal or informal)
- The target English dialect (American or British)
- Explicit formatting instructions
While we could construct this prompt using simple Python string interpolation, Langchain provides a cleaner approach via its PromptTemplate class. Here‘s how we might define our prompt:
from langchain import PromptTemplate
template = """
Your task is to format the email below with the following settings:
Tone: {tone}
Dialect: {dialect}
Here are some formatting guidelines:
- Adopt a friendly but respectful tone
- Ensure the email has a clear greeting, body, and closing
- Use {dialect} vocabulary, grammar, and spellings
Email draft:
{email}
Formatted email:
"""
prompt = PromptTemplate(
input_variables=["tone", "dialect", "email"],
template=template
)
This prompt template is a bit like a Mad Libs that we can fill in with user-supplied values. The {tone}, {dialect}, and {email} placeholders will be replaced with the actual tone, dialect, and draft email content when we format the prompt.
We also provide some explicit instructions for the model, specifying the tone, dialect, and expected structure of the output. This helps to focus the model‘s efforts and improves the consistency and quality of its generations.
Langchain‘s PromptTemplate takes care of the gory details of serializing our prompt and input variables. Now we‘re ready to feed it into OpenAI and see what comes back!
Leveraging OpenAI‘s Language Model
To make use of OpenAI‘s language models, we first need to sign up for an API key. This can be done through the OpenAI website (link). It‘s important to keep this key secure and not share it publicly.
Armed with an API key, we can load up an OpenAI model using Langchain‘s OpenAI class:
from langchain.llms import OpenAI
llm = OpenAI(
model_name="text-davinci-003",
temperature=0.7,
openai_api_key=api_key
)
Here we‘re specifying the model we want to use (text-davinci-003, one of the most capable GPT-3 models), as well as a temperature value that controls the "creativity" of the model‘s outputs. Higher temperatures will produce more varied and surprising generations, while lower values hew closer to the most likely output.
We pass our formatted prompt to this model using Langchain‘s predict method:
formatted_email = llm.predict(
tone=tone,
dialect=dialect,
email=email_input
)
The model will churn for a second or two (during which we can display a spinner or progress bar in our Streamlit app) and then return a formatted version of the email, adhering to the tone and dialect specifications we provided.
Displaying Model Output in Streamlit
To complete the loop and show the model-generated email in our app, we simply use Streamlit‘s st.markdown function:
st.markdown(formatted_email)
This will display the formatted email in the app, below the input form. We use st.markdown rather than st.write so that any formatting in the model output (like line breaks or bullet points) is preserved.
At this point, our app is fully functional! Users can input an email draft, set their desired tone and dialect, and click "Format" to see the AI-powered result. But to make it truly accessible, we need to deploy it beyond our local development environment.
Deploying the App with Streamlit Sharing
Streamlit offers a free hosting solution called Streamlit Sharing that makes it dead simple to deploy an app publicly. Just sign up for an account, then navigate to the "New app" page to connect your GitHub repo.
Within the repo settings, you‘ll point Streamlit to the app script you want to run (in our case, emailapp.py) and then click "Deploy." In a couple minutes, your email formatter will be live on the web for anyone to use!
As an added perk, any time you push changes to your GitHub repo, Streamlit Sharing will automatically redeploy the app. This makes it easy to iterate and improve your app over time.
Putting It All Together – Full Code Walkthrough
[Include the complete email formatter code here, with detailed comments explaining each section]Potential Enhancements
While our email formatter is pretty nifty as is, there are plenty of ways you could extend and improve it:
- Add support for additional tones (e.g. persuasive, humorous, apologetic) and dialects
- Implement login functionality to securely store user API keys
- Allow users to send the formatted emails directly from the app
- Train a custom model on a dataset of high-performing emails for even better results
The possibilities are endless, and the core techniques we‘ve covered – Streamlit for UI, Langchain for prompt management, OpenAI for language modeling – can be readily adapted to all sorts of exciting applications.
Conclusion
Through this tutorial, we‘ve seen how the potent combination of OpenAI, Langchain, and Streamlit empowers us to build impressive AI apps quickly and with a minimum of fuss. You‘re now equipped with the skills to turn an idea into a functional prototype in just an afternoon‘s work.
But perhaps more important than the technical knowledge is the newfound ability to wield AI as a creative tool. By learning to leverage language models through prompts, you can tap into a vast wealth of knowledge and capability to augment your own efforts, whether that‘s drafting emails, coding up programs, brainstorming ideas, or beyond.
So keep exploring, keep tinkering, and see what other clever AI apps you can dream up. The future is wide open, and you‘ve now got some powerful allies to help you navigate it.
Happy coding!
Frequently Asked Questions
Q: Can I use this app for free?
A: The app itself is free to deploy and use, but OpenAI‘s language models are priced on a per-request basis. You‘ll need to sign up for an API key and pay for any model usage beyond the initial free credit. See OpenAI‘s pricing page for details.
Q: How can I customize the app for my own tone/dialect options?
A: To add or modify tone and dialect choices, simply update the options passed to st.selectbox in the Streamlit app code. You may also need to modify the prompt template to ensure the model understands how to format the email for the new settings.
Q: Can I trust the model output to be grammatically correct and tonally appropriate?
A: While OpenAI‘s models are remarkably capable, they‘re not perfect. It‘s always a good idea to proofread and sanity-check any generated text before using it in a professional context. The model may occasionally produce biased, inconsistent, or nonsensical outputs.
Q: How can I learn more about prompt engineering?
A: There are a number of great resources for learning the art of prompt engineering, including:
- The official OpenAI docs and examples
- Prompt engineering guides from Anthropic and LearnPrompting
- Example prompts in the Langchain GitHub repo
Q: What other types of AI apps can I build with these tools?
A: The combination of Langchain, Streamlit, and OpenAI can be used to create all sorts of language-based applications, like:
- Chatbots and virtual assistants
- Content generators and summarizers
- Language learning tools
- Data extraction and classification interfaces
- Writing aids and storytelling games
- And much, much more!