Meta’s AI agent is a cute little guy who’s great at spending my money
Back to Tutorials
aiTutorialbeginner

Meta’s AI agent is a cute little guy who’s great at spending my money

September 23, 202649 views5 min read

Learn to build a basic AI-powered task management assistant that can understand natural language commands and help organize your daily tasks.

Introduction

In this tutorial, you'll learn how to create a simple AI-powered task management assistant using Python and OpenAI's API. This assistant will help you organize your daily tasks and even make smart suggestions about what to do next. Think of it as your personal AI assistant that can help you tackle that endless to-do list that seems to grow no matter how much you accomplish.

By the end of this tutorial, you'll have built a basic AI agent that can understand natural language commands, create new tasks, and prioritize your existing ones. This is the kind of technology that Meta is developing for their AI agents, but we'll build something simpler and more accessible for beginners.

Prerequisites

Before starting this tutorial, you'll need:

  • A computer with Python 3.7 or higher installed
  • An OpenAI API key (free to get at platform.openai.com)
  • Basic understanding of Python programming concepts
  • Internet connection to access the OpenAI API

Step-by-Step Instructions

1. Set Up Your Development Environment

First, we need to create a new Python project directory and install the required packages. Open your terminal or command prompt and run:

mkdir ai-task-assistant
 cd ai-task-assistant
 python -m venv venv
 source venv/bin/activate  # On Windows: venv\Scripts\activate

This creates a new project folder and sets up a virtual environment to keep our dependencies isolated.

2. Install Required Python Packages

Now install the OpenAI Python library which will allow us to communicate with the AI:

pip install openai

We're using the official OpenAI Python library because it handles all the API communication complexities for us, making it easier to focus on building our assistant.

3. Create Your API Key Configuration

Create a new file called config.py in your project directory:

import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Your OpenAI API key
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

This file will store your API key securely. We use environment variables instead of hardcoding the key in our program for security reasons.

4. Set Up Environment Variables

Create a file called .env in your project directory and add your API key:

OPENAI_API_KEY=your_actual_api_key_here

Replace your_actual_api_key_here with your real OpenAI API key. This file should never be shared publicly or committed to version control.

5. Create the Main Task Management System

Create a file called task_manager.py:

import openai
import json
from config import OPENAI_API_KEY

# Initialize the OpenAI client
openai.api_key = OPENAI_API_KEY

class TaskManager:
    def __init__(self):
        self.tasks = []
        
    def add_task(self, description):
        """Add a new task to the list"""
        self.tasks.append({
            'id': len(self.tasks) + 1,
            'description': description,
            'completed': False
        })
        print(f"Added task: {description}")
        
    def list_tasks(self):
        """Display all tasks"""
        if not self.tasks:
            print("No tasks in your list.")
            return
        
        print("\nYour tasks:")
        for task in self.tasks:
            status = "✓" if task['completed'] else "○"
            print(f"{status} {task['id']}. {task['description']}")
        
    def complete_task(self, task_id):
        """Mark a task as completed"""
        for task in self.tasks:
            if task['id'] == task_id:
                task['completed'] = True
                print(f"Completed task {task_id}")
                return
        print(f"Task {task_id} not found.")

This creates the basic structure for managing tasks. We're building a simple class that can add, list, and complete tasks.

6. Add AI Integration for Smart Task Management

Now we'll add the AI capabilities to our task manager:

def analyze_and_suggest(self, user_input):
        """Use AI to understand user input and suggest actions"""
        prompt = f"""
You are an intelligent task management assistant. The user has said: '{user_input}'

Based on this, please provide:
1. A summary of what they want to do
2. A list of suggested actions (if any)
3. A priority rating (high, medium, low)

Respond in JSON format with keys: summary, actions, priority
"""
        
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are a helpful task management assistant."},
                    {"role": "user", "content": prompt}
                ],
                max_tokens=200,
                temperature=0.5
            )
            
            result = response.choices[0].message.content
            return json.loads(result)
        except Exception as e:
            print(f"AI processing error: {e}")
            return None

This AI integration analyzes what the user wants to do and provides smart suggestions. The AI helps make sense of natural language input and suggests appropriate actions.

7. Create the Main Interactive Interface

Create the main program file main.py:

from task_manager import TaskManager

# Initialize the task manager
manager = TaskManager()

print("Welcome to your AI Task Assistant!")
print("Type 'help' for commands or 'quit' to exit.")

while True:
    user_input = input("\nWhat would you like to do? ").strip()
    
    if user_input.lower() in ['quit', 'exit']:
        break
    elif user_input.lower() == 'help':
        print("Commands: add [task], list, complete [id], ai [query], help, quit")
    elif user_input.lower().startswith('add '):
        task_description = user_input[4:].strip()
        manager.add_task(task_description)
    elif user_input.lower() == 'list':
        manager.list_tasks()
    elif user_input.lower().startswith('complete '):
        try:
            task_id = int(user_input[8:].strip())
            manager.complete_task(task_id)
        except ValueError:
            print("Please provide a valid task ID.")
    elif user_input.lower().startswith('ai '):
        ai_query = user_input[3:].strip()
        # Here we would call the AI analysis
        print(f"AI is thinking about: {ai_query}")
        print("AI assistant would suggest actions based on your query.")
    else:
        print("I didn't understand that command. Type 'help' for available commands.")

print("Goodbye!")

This creates the interactive interface where users can manage their tasks through natural language commands.

8. Test Your AI Task Assistant

Run your assistant with:

python main.py

Try commands like:

  • add Buy groceries
  • add Call mom
  • list
  • complete 1
  • ai What should I do today?

This will help you understand how your AI assistant responds to different inputs and commands.

Summary

In this tutorial, you've built a basic AI-powered task management assistant that can understand natural language commands, manage tasks, and even provide intelligent suggestions. While this is a simplified version compared to Meta's sophisticated AI agents, it demonstrates the core concepts of how AI can help with daily task management.

The assistant you've created shows how AI can make sense of your natural language input and help organize your to-do list. As you continue learning, you can expand this system to include features like task categorization, time estimation, and even integration with calendar applications.

Remember to keep your API key secure and consider exploring other OpenAI models for different capabilities. This foundation gives you the building blocks to create more sophisticated AI assistants tailored to your specific needs.

Source: The Verge AI

Related Articles