Introduction
In this tutorial, you'll learn how to create a basic work agent using Python that can help automate tasks like email processing and report generation. This is inspired by Mistral AI's new Vibe work agent that integrates with platforms like Google Workspace and Slack. While we won't be building the full Vibe agent, we'll create a simplified version that demonstrates core concepts like task automation and integration with external services.
Prerequisites
- A basic understanding of Python programming
- Python 3.7 or higher installed on your computer
- Access to a Gmail account for testing email automation
- Basic knowledge of how APIs work
- Installed Python packages:
requests,gmail,openai
Step-by-step instructions
Step 1: Set Up Your Python Environment
First, we need to create a project directory and install the required Python packages. Open your terminal or command prompt and run these commands:
1.1 Create a new project directory
mkdir work-agent-project
cd work-agent-project
1.2 Create a virtual environment (recommended)
python -m venv work-agent-env
work-agent-env\Scripts\activate # On Windows
# or
source work-agent-env/bin/activate # On macOS/Linux
1.3 Install required packages
pip install requests openai gmail
Why this step? A virtual environment isolates our project dependencies, preventing conflicts with other Python projects. The packages we install will be essential for interacting with APIs and automating tasks.
Step 2: Get Your Gmail API Credentials
To access your Gmail account programmatically, you'll need to enable the Gmail API and get credentials:
2.1 Visit the Google Cloud Console
Go to https://console.cloud.google.com/ and create a new project or select an existing one.
2.2 Enable the Gmail API
Navigate to APIs & Services > Library, search for "Gmail API", and enable it.
2.3 Create credentials
Go to APIs & Services > Credentials > Create Credentials > OAuth client ID. Choose "Desktop application" and download the JSON file as credentials.json into your project directory.
Why this step? Gmail API access allows us to read and process emails automatically, which is a core function of work agents like Vibe.
Step 3: Create a Basic Email Processor
Now, we'll create a Python script that can read and process emails:
3.1 Create the main script file
touch email_processor.py
3.2 Add the email processing code
import os
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def authenticate_gmail():
"""Authenticate and return Gmail service object"""
creds = None
# The file token.pickle stores the user's access and refresh tokens.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('gmail', 'v1', credentials=creds)
def get_latest_email(service):
"""Get the latest email from the inbox"""
results = service.users().messages().list(userId='me', maxResults=1).execute()
messages = results.get('messages', [])
if not messages:
print('No messages found.')
return None
message = service.users().messages().get(userId='me', id=messages[0]['id']).execute()
return message
def main():
service = authenticate_gmail()
message = get_latest_email(service)
if message:
print('Subject:', message['payload']['headers'][0]['value'])
print('Snippet:', message['snippet'])
if __name__ == '__main__':
main()
Why this step? This code sets up the authentication process and demonstrates how to retrieve information from your Gmail inbox, which is essential for any work agent that needs to process emails.
Step 4: Add AI Integration for Email Summarization
Next, we'll integrate OpenAI's API to summarize emails automatically:
4.1 Install OpenAI package
pip install openai
4.2 Update your email_processor.py script
import os
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from openai import OpenAI
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
# Initialize OpenAI client
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
def get_email_content(message):
"""Extract email content from message"""
payload = message['payload']
parts = payload.get('parts', [])
content = ''
for part in parts:
if part['mimeType'] == 'text/plain':
content += part['body']['data']
return content
def summarize_email(content):
"""Summarize email content using OpenAI"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant that summarizes emails."},
{"role": "user", "content": f"Summarize this email: {content}"}
]
)
return response.choices[0].message.content
def main():
service = authenticate_gmail()
message = get_latest_email(service)
if message:
print('Subject:', message['payload']['headers'][0]['value'])
content = get_email_content(message)
summary = summarize_email(content)
print('Summary:', summary)
if __name__ == '__main__':
main()
Why this step? Adding AI summarization transforms a simple email reader into a work agent that can quickly process and summarize information, which is a key feature of tools like Vibe.
Step 5: Create a Simple Task Automation Interface
Let's create a basic command-line interface for our work agent:
5.1 Add a task interface to your script
import os
import pickle
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from openai import OpenAI
import sys
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
# Initialize OpenAI client
client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))
def get_email_content(message):
"""Extract email content from message"""
payload = message['payload']
parts = payload.get('parts', [])
content = ''
for part in parts:
if part['mimeType'] == 'text/plain':
content += part['body']['data']
return content
def summarize_email(content):
"""Summarize email content using OpenAI"""
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant that summarizes emails."},
{"role": "user", "content": f"Summarize this email: {content}"}
]
)
return response.choices[0].message.content
def get_latest_email(service):
"""Get the latest email from the inbox"""
results = service.users().messages().list(userId='me', maxResults=1).execute()
messages = results.get('messages', [])
if not messages:
print('No messages found.')
return None
message = service.users().messages().get(userId='me', id=messages[0]['id']).execute()
return message
def process_email_task(service):
"""Process email and summarize it"""
message = get_latest_email(service)
if message:
print('Subject:', message['payload']['headers'][0]['value'])
content = get_email_content(message)
summary = summarize_email(content)
print('Summary:', summary)
return summary
return None
def main():
if len(sys.argv) < 2:
print('Usage: python email_processor.py [email|report]')
return
service = authenticate_gmail()
task = sys.argv[1]
if task == 'email':
process_email_task(service)
elif task == 'report':
print('Generating report...')
# Placeholder for report generation
print('Report generated successfully!')
else:
print('Unknown task')
if __name__ == '__main__':
main()
Why this step? This creates a simple command-line interface that allows you to specify different tasks for your work agent, making it more flexible and useful for different work scenarios.
Step 6: Test Your Work Agent
Now let's test our work agent:
6.1 Set up your OpenAI API key
export OPENAI_API_KEY='your_openai_api_key_here'
6.2 Run the script
python email_processor.py email
Why this step? Testing ensures that your work agent functions correctly and helps you identify any issues in the integration between Gmail API, OpenAI, and your automation logic.
Summary
In this tutorial, you've created a basic work agent that can access your Gmail account, read emails, and summarize them using AI. This demonstrates core concepts of how work agents like Vibe operate, combining API access with AI capabilities to automate routine tasks. While this is a simplified version, it shows the foundation upon which more complex agents can be built. You've learned how to authenticate with Gmail, extract email data, and integrate with OpenAI's API to perform automated summarization. These skills are essential for building more sophisticated work agents that can integrate with platforms like Google Workspace, Slack, or GitHub as mentioned in the article.



