Introduction
In this tutorial, you'll learn how to create a basic AI agent that can help with everyday tasks like booking reservations and detecting potential security threats. Inspired by the Instinct AI agent mentioned in the Wired article, we'll build a simple yet functional AI assistant that can interact with APIs and make decisions based on user input. This project will teach you fundamental concepts of AI agent development while demonstrating practical applications.
Prerequisites
- Basic understanding of Python programming
- Python 3.7 or higher installed on your computer
- Internet connection
- Text editor or IDE (like VS Code or PyCharm)
- API keys from OpenWeatherMap and a restaurant reservation service (for demonstration purposes)
Step 1: Set Up Your Development Environment
Install Required Libraries
First, we need to install the necessary Python libraries. Open your terminal or command prompt and run:
pip install requests openai python-dotenv
This command installs the requests library for making HTTP requests, OpenAI library for AI interactions, and python-dotenv for managing environment variables.
Step 2: Create Your AI Agent Structure
Create the Main Agent Class
Let's start by creating the basic structure for our AI agent. Create a new file called ai_agent.py:
import os
import requests
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
class AIAgent:
def __init__(self):
self.name = "Instinct"
self.api_key = os.getenv('OPENAI_API_KEY')
self.weather_api_key = os.getenv('WEATHER_API_KEY')
def process_request(self, user_input):
# This method will handle user requests
pass
# Create an instance of the agent
agent = AIAgent()
print(f"AI Agent {agent.name} initialized")
This creates the foundation of our AI agent with basic initialization. The agent will have a name (similar to Instinct) and will be able to access API keys from environment variables.
Step 3: Implement Weather Information Functionality
Add Weather Data Retrieval
Let's add functionality to get weather information, which is one of the useful features mentioned in the article:
def get_weather(self, city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={self.weather_api_key}&units=metric"
try:
response = requests.get(url)
data = response.json()
if response.status_code == 200:
temperature = data['main']['temp']
description = data['weather'][0]['description']
return f"The current weather in {city} is {temperature}°C with {description}."
else:
return "Sorry, I couldn't fetch weather information."
except Exception as e:
return f"Error getting weather: {str(e)}"
This function allows our AI agent to retrieve weather data for any city. It demonstrates how AI agents can integrate with external APIs to provide useful information.
Step 4: Add Reservation Booking Capabilities
Create a Reservation System
def book_reservation(self, restaurant_name, time, party_size):
# Simulate booking a reservation
# In a real implementation, this would connect to a restaurant API
reservation_details = {
'restaurant': restaurant_name,
'time': time,
'party_size': party_size,
'status': 'confirmed'
}
return f"Reservation booked at {restaurant_name} for {party_size} people at {time}. Confirmation: {reservation_details['status']}"
This method simulates booking a restaurant reservation. In a real-world scenario, this would connect to actual restaurant APIs to make real reservations.
Step 5: Implement Security Threat Detection
Add Phishing Detection Logic
def detect_phishing(self, message):
# Simple phishing detection logic
phishing_keywords = ['urgent', 'immediate action', 'click here', 'verify account', 'password reset']
message_lower = message.lower()
for keyword in phishing_keywords:
if keyword in message_lower:
return True
return False
This basic phishing detection looks for common keywords that appear in phishing messages. While not as sophisticated as advanced AI systems, it demonstrates how AI agents can help protect users from security threats.
Step 6: Create the Main Processing Loop
Implement User Request Handling
def process_request(self, user_input):
user_input = user_input.lower()
if 'weather' in user_input:
# Extract city name (simplified)
city = user_input.split('weather in ')[-1]
return self.get_weather(city)
elif 'book' in user_input and 'reservation' in user_input:
# Extract restaurant details (simplified)
return "Reservation booking functionality would be implemented here."
elif 'phishing' in user_input or 'security' in user_input:
return "Security threat detection would be implemented here."
else:
return "I can help with weather, reservations, or security threats. Try asking about these topics."
# Update the main code to use the processing function
if __name__ == "__main__":
agent = AIAgent()
# Example usage
print(agent.process_request("What's the weather in London?"))
print(agent.process_request("Book a reservation at The Golden Spoon"))
This processing loop allows our AI agent to understand and respond to different types of user requests, similar to how Instinct was described in the article.
Step 7: Set Up Environment Variables
Create .env File
Create a file named .env in your project directory with your API keys:
OPENAI_API_KEY=your_openai_api_key_here
WEATHER_API_KEY=your_openweathermap_api_key_here
This approach keeps your API keys secure and separate from your code, which is essential for security.
Step 8: Test Your AI Agent
Run the Complete Implementation
Save your complete code in ai_agent.py and run it:
python ai_agent.py
You should see output showing your AI agent responding to different requests. This demonstrates the core functionality of an AI agent that can handle multiple tasks.
Summary
In this tutorial, you've built a basic AI agent that can perform several key functions similar to the Instinct AI mentioned in the Wired article. You've learned how to:
- Create a structured AI agent with multiple capabilities
- Integrate with external APIs for weather information
- Implement basic reservation booking functionality
- Add security threat detection features
- Use environment variables for secure API key management
While this is a simplified version, it demonstrates the fundamental concepts behind AI agents like Instinct. Real AI agents are much more sophisticated, but this foundation gives you a practical understanding of how such systems work and how they can provide value in daily life while also highlighting potential risks like those mentioned in the article.