Introduction
In this tutorial, you'll learn how to create a basic AI agent similar to Meta's Muse using Python and open-source tools. We'll build a simple AI assistant that can respond to text prompts, manage email-like messages, and simulate controlling a Mac interface. This hands-on project will teach you fundamental concepts of AI agent development while working with real-world applications.
Prerequisites
Before starting this tutorial, you'll need:
- A computer with Python 3.8 or higher installed
- Basic understanding of Python programming concepts
- Access to a command-line interface (terminal or command prompt)
- Internet connection for downloading packages
Step-by-Step Instructions
Step 1: Set Up Your Development Environment
Install Required Python Packages
First, we need to install the necessary Python packages for our AI agent. Open your terminal or command prompt and run:
pip install openai python-dotenv
Why we do this: The openai package allows us to connect to OpenAI's API, which provides the language model capabilities for our AI agent. The python-dotenv package helps us manage our API keys securely.
Create a Project Directory
Create a new folder for your project and navigate to it:
mkdir muse_ai_agent
cd muse_ai_agent
Why we do this: Organizing our code in a dedicated directory makes it easier to manage and prevents conflicts with other projects.
Step 2: Configure Your API Key
Create an Environment File
Create a new file named .env in your project directory:
touch .env
Add your OpenAI API key to this file:
OPENAI_API_KEY=your_actual_api_key_here
Why we do this: Storing API keys in a separate file keeps them secure and prevents accidental exposure in your code.
Load Environment Variables
Create a new Python file called config.py:
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('OPENAI_API_KEY')
Why we do this: This configuration file will load our API key securely so we can use it in our agent without hardcoding it in our main code.
Step 3: Create the Basic AI Agent
Build the Core Agent Class
Create a file named ai_agent.py:
import openai
from config import API_KEY
class MUSEAgent:
def __init__(self):
openai.api_key = API_KEY
self.messages = []
def get_response(self, user_input):
# Add user message to conversation history
self.messages.append({'role': 'user', 'content': user_input})
# Get response from OpenAI
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=self.messages
)
# Extract and store assistant response
assistant_response = response.choices[0].message['content']
self.messages.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
Why we do this: This class creates our AI agent with conversation history tracking, allowing it to remember previous interactions and provide more contextually relevant responses.
Initialize Your Agent
Create a file called main.py:
from ai_agent import MUSEAgent
# Create agent instance
muse = MUSEAgent()
# Test the agent
print("MUSE AI Agent is ready! Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
response = muse.get_response(user_input)
print(f"MUSE: {response}")
Why we do this: This creates a simple interactive interface where you can talk to your AI agent and see how it responds to different inputs.
Step 4: Add Email Simulation Functionality
Enhance the Agent with Email Capabilities
Modify your ai_agent.py file to include email simulation:
import openai
from config import API_KEY
import datetime
class MUSEAgent:
def __init__(self):
openai.api_key = API_KEY
self.messages = []
self.emails = []
def get_response(self, user_input):
# Add user message to conversation history
self.messages.append({'role': 'user', 'content': user_input})
# Get response from OpenAI
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=self.messages
)
# Extract and store assistant response
assistant_response = response.choices[0].message['content']
self.messages.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
def send_email(self, to, subject, content):
email = {
'to': to,
'subject': subject,
'content': content,
'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
self.emails.append(email)
return f"Email sent to {to} with subject '{subject}'"
def get_emails(self):
return self.emails
Why we do this: Adding email functionality simulates how Muse might handle communication tasks, showing how AI agents can manage digital correspondence.
Test Email Functionality
Update your main.py to test email features:
from ai_agent import MUSEAgent
# Create agent instance
muse = MUSEAgent()
# Test email functionality
print("MUSE AI Agent is ready! Type 'quit' to exit.")
print("Try commands like: 'send email to [email protected] about project update'")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
if 'send email' in user_input.lower():
# Simple parsing for demonstration
parts = user_input.split(' to ')
if len(parts) > 1:
to = parts[1].split(' about ')[0]
subject = parts[1].split(' about ')[1] if ' about ' in parts[1] else 'No subject'
response = muse.send_email(to, subject, "This is a test email content.")
print(f"MUSE: {response}")
else:
response = muse.get_response(user_input)
print(f"MUSE: {response}")
Why we do this: This demonstrates how our AI agent can process natural language commands to perform specific tasks like sending emails.
Step 5: Add Mac Control Simulation
Implement Basic Mac Control Simulation
Extend your ai_agent.py with Mac control capabilities:
import openai
from config import API_KEY
import datetime
class MUSEAgent:
def __init__(self):
openai.api_key = API_KEY
self.messages = []
self.emails = []
self.mac_status = 'off'
def get_response(self, user_input):
# Add user message to conversation history
self.messages.append({'role': 'user', 'content': user_input})
# Get response from OpenAI
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=self.messages
)
# Extract and store assistant response
assistant_response = response.choices[0].message['content']
self.messages.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
def send_email(self, to, subject, content):
email = {
'to': to,
'subject': subject,
'content': content,
'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
self.emails.append(email)
return f"Email sent to {to} with subject '{subject}'"
def get_emails(self):
return self.emails
def control_mac(self, command):
if command.lower() == 'turn on':
self.mac_status = 'on'
return "Mac is now turned on."
elif command.lower() == 'turn off':
self.mac_status = 'off'
return "Mac is now turned off."
elif command.lower() == 'open app':
return "Opening application..."
else:
return "Unknown command. Try 'turn on', 'turn off', or 'open app'."
def get_mac_status(self):
return f"Mac is currently {self.mac_status}"
Why we do this: This simulates how AI agents might interact with computer systems, demonstrating the concept of system control that Meta mentioned for Muse.
Test Mac Control Features
Update your main.py to include Mac control testing:
from ai_agent import MUSEAgent
# Create agent instance
muse = MUSEAgent()
# Test all functionalities
print("MUSE AI Agent is ready! Type 'quit' to exit.")
print("Try commands like: 'turn on mac', 'send email', or 'open app'")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
if 'send email' in user_input.lower():
# Simple parsing for demonstration
parts = user_input.split(' to ')
if len(parts) > 1:
to = parts[1].split(' about ')[0]
subject = parts[1].split(' about ')[1] if ' about ' in parts[1] else 'No subject'
response = muse.send_email(to, subject, "This is a test email content.")
print(f"MUSE: {response}")
elif 'turn' in user_input.lower() or 'open' in user_input.lower():
response = muse.control_mac(user_input)
print(f"MUSE: {response}")
else:
response = muse.get_response(user_input)
print(f"MUSE: {response}")
Why we do this: This final enhancement shows how AI agents can be extended to control various system functions, similar to how Meta's Muse can control Mac devices.
Summary
In this tutorial, you've built a basic AI agent similar to Meta's Muse with three key capabilities:
- Text-based conversation using OpenAI's language models
- Email simulation functionality
- Mac control simulation
You've learned how to set up a Python environment, manage API keys securely, and create an interactive AI agent that can process natural language commands and perform specific tasks. This foundation can be expanded to include more sophisticated features like actual system integration, voice control, or advanced machine learning capabilities.