top of page

LBSocial

Writer's pictureXuebin Wei

OpenAI Assistant: Automating Email Replies for Professors and Students

Updated: Jan 1

 


Today, we will introduce OpenAI’s Assistant API, a powerful tool that simplifies building intelligent assistants and managing vector databases. As of December 2024, this feature is in beta, but it already offers exciting possibilities for users.



Key Features of the OpenAI Assistant API

  • Ease of Use: OpenAI provides a web-based graphical interface for creating assistants and vector databases. Alternatively, users can achieve the same results programmatically using Python, making it accessible for technical and non-technical users.

  • Seamless Integration: The API integrates well with OpenAI-hosted tools such as file storage and the code interpreter, allowing you to create robust systems without extensive setup.

  • Flexible Storage Options: While OpenAI’s vector storage is convenient, it may not be cost-effective for large datasets. In such cases, alternative solutions like MongoDB can be a more economical choice.


Creating an Assistant

Step 1: Set Up an Assistant

Navigate to the OpenAI dashboard to create a new assistant. You can name your assistant and provide system-level instructions. For example, we created an assistant named “Data Mining Class TA” with the instruction to answer student emails based on provided documents.

Step 2: Configure Features

  • Enable file search to allow the assistant to retrieve information from uploaded documents.

  • Enable the code interpreter to execute Python code within the assistant’s environment.

Adjust settings like temperature and the number of response candidates as needed. Once configured, save and create the assistant.


Setting Up a Vector Database

Step 1: Create the Database

Go to the vector storage section on OpenAI and create a new database. For instance, we named ours “Data Mining Documents.”

Step 2: Upload Files

Upload documents such as a course syllabus and project instructions. These documents will serve as the assistant's knowledge base. For example:

  • Syllabus: Includes office hours, course schedule, learning objectives, and required textbooks.

  • Final Project Instructions: Lists steps for completing the project, including data collection, analysis, and creating a dashboard.

Step 3: Connect to the Assistant

Link the vector database to the assistant by copying the database’s unique ID and pasting it into the assistant’s configuration. This connection allows the assistant to retrieve relevant information when responding to queries.


Testing the Assistant

Example Queries

Use OpenAI’s playground to test the assistant’s functionality. For instance:

  • Question: “When is the final exam?”

  • Response: The assistant retrieves the date and relevant details from the syllabus.


Code Interpreter Demonstration

Upload a dataset and ask the assistant to analyze it. For example:

  • Dataset: A text file containing diamond data (weight, color, clarity, price).

  • Request: Ask the assistant to calculate the average weight or create a bar chart showing the average price per color.

The assistant generates Python code, executes it, and produces the desired output.


Real-World Application: Responding to Emails

Automating Email Replies

We will now demonstrate how to use the assistant to reply to student emails:

Setup:

  • Store OpenAI credentials and the assistant ID in a local configuration file.

[openai]
api_key = <your API key>

[openai-assistant]
assistant_id = <your assistant id>

Retrieve Credentials

import configparser

config = configparser.ConfigParser(interpolation=None)
config.read('config.ini')

openai_api_key = config['openai']['api_key']
assistant_id = config['openai-assistant']['assistant_id']

Code to Retrieve and Respond to Emails

Step 1: Set Up the Assistant Client

from openai import OpenAI

client = OpenAI(api_key=openai_api_key)

# Provide the assistant id below
assistant = client.beta.assistants.retrieve(assistant_id)

Step 2: Ask the Assistant a Question

def ask_assistant(question):
    thread = client.beta.threads.create()
    
    client.beta.threads.messages.create(
        thread_id=thread.id,
        role="user",
        content=question
    )
    
    run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant.id
    )
    
    while run.status != 'completed':
        run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
    
    messages = client.beta.threads.messages.list(thread_id=thread.id)
    return messages.data[0].content[0].text.value

# Test the function
answer = ask_assistant("name xuebin, body: when is the final exam")
print(answer)

Step 3: Automate Email Reply Workflow

This code runs locally to retrieve received emails in Outlook. If the sender's address matches specific patterns, the sender's name and message are passed to the OpenAI Assistant function. The automatically created reply will be saved as a draft.

import win32com.client
import re

def extract_name(email):
    pattern = r"^([^@]+)@"
    match = re.search(pattern, email)
    return match.group(1) if match else email

Step 4: Process Emails and Reply

def process_emails(sender_filter):
    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    messages = inbox.Items
    messages.Sort("[ReceivedTime]", True)

    for message in messages:
        if sender_filter.lower() in message.SenderEmailAddress.lower():
            if message.UnRead :
                sender_name = message.SenderName
                body_text = message.Body
    
                print(f"Sender: {sender_name}")
                print(f"Body: {body_text[:100]}...")  # Print first 100 characters
    
                reply = message.Reply()
                reply_body = ask_assistant(f"sender: {sender_name}, body:{body_text}")
                reply.Body = f"{reply_body}\n\n--- Original Message ---\n{message.Body}"
              
                reply.Save()

# Test emails
sender_filter = "weixuebin@gmail.com"  # Replace with the desired sender domain or email
process_emails(sender_filter)

Conclusion

The OpenAI Assistant API offers a straightforward way to build intelligent systems for education, customer support, and more. By combining tools like vector storage and code interpretation, you can create assistants that efficiently handle real-world tasks, such as automating email replies and analyzing datasets. Whether you're answering student inquiries or processing large amounts of data, the Assistant API provides a flexible and user-friendly solution.



65 views0 comments
bottom of page