In this lesson, you’ll learn how to build an automatic AI replier that reads an incoming email and writes a reply on behalf of an employee—in this case, Emily from Acme Corp. You’ve already learned how to parse emails and use different agents. Now, we’ll focus on how to generate and send a reply using the addReply method.
Before we dive in, let’s quickly review what you’ve already learned:
- Parsing Emails: You know how to read an email thread from a file and break it into structured objects using
parseEmailThread. - Agents: You’ve built and used two agents:
- The IntentAgent classifies the intent of an email (e.g., question, meeting request).
- The SummaryAgent summarizes the email, decides if a reply is needed, and drafts a reply.
Now, let’s see how to use the addReply method to automatically add a reply to an email thread.
The addReply function is the key to making your AI replier actually participate in an email conversation. It takes three arguments: the original email thread, the reply body (the text of the reply), and the email address of the replier (for example, Emily’s email).
The first thing addReply does is break the thread into individual emails, so it can figure out who sent the original message and what the subject was. It uses your existing parseEmailThread function for this:
Now, it prepares the fields for the reply. The from field is set to the agent’s email (e.g., emily@acme-corp.com). The to field is set to the original sender of the first email in the thread. The subject is set to include Re: if it’s not already present:
Next, it constructs the reply’s header and body, making sure the format matches the rest of the thread. The header includes the From, To, and Subject fields, followed by the reply body:
Finally, the function appends the reply to the end of the thread, separated by a line (\n---\n\n). This makes the reply appear as a new message in the conversation:
Here’s a short example showing how you might orchestrate your agents and use addReply to automatically generate and append a reply to an email thread:
In this example:
- The email thread is loaded from a file and parsed.
- The first email’s content is sent to the
IntentAgentto determine the intent. - The
SummaryAgentuses the email and its intent to decide if a reply is needed and, if so, drafts a reply. - If a reply is needed,
addReplyis called to append the draft reply to the thread as if it came from Emily. The updated thread is then printed.
If the original thread is:
After calling addReply, the thread will look like:
You now know how the addReply method works to append a new reply to an email thread, making it look like a real response from an employee. This is a key step in building an automatic AI replier that can participate in email conversations on behalf of your team.
