Introduction
In this tutorial, you'll learn how to work with AI agents and understand the security considerations around AI systems. Based on recent news about unsecured OpenAI agents posting user data publicly, we'll explore how to build a basic AI agent system while implementing proper security measures. This hands-on guide will teach you to create a simple AI agent that can interact with users while protecting sensitive information.
Prerequisites
- Basic computer literacy
- Python installed on your system
- Internet connection
- Text editor (like VS Code or Notepad++)
Step-by-Step Instructions
1. Set Up Your Python Environment
First, we need to create a safe working environment for our AI agent. Open your terminal or command prompt and create a new folder for this project:
mkdir ai_agent_project
cd ai_agent_project
Next, we'll create a virtual environment to keep our dependencies isolated:
python -m venv agent_env
source agent_env/bin/activate # On Windows use: agent_env\Scripts\activate
Why this step? Creating a virtual environment ensures that our AI agent project doesn't interfere with other Python programs on your computer, and helps prevent dependency conflicts.
2. Install Required Libraries
Now we'll install the necessary Python libraries for our AI agent:
pip install openai python-dotenv
Why this step? The 'openai' library allows us to interact with OpenAI's API, while 'python-dotenv' helps us manage sensitive API keys securely.
3. Create Your API Key File
Before we can interact with AI services, we need to get an API key. Visit OpenAI's API keys page to create a new key. Then create a file called .env in your project folder:
OPENAI_API_KEY=your_actual_api_key_here
Why this step? Storing API keys in a separate file prevents accidentally sharing them in code repositories or public forums.
4. Create Your Basic AI Agent
Create a new file called ai_agent.py and add the following code:
import os
from dotenv import load_dotenv
import openai
# Load environment variables
load_dotenv()
# Initialize OpenAI client
openai.api_key = os.getenv('OPENAI_API_KEY')
class SecureAIAssistant:
def __init__(self):
self.conversation_history = []
def get_response(self, user_input):
# Add user input to conversation history
self.conversation_history.append({'role': 'user', 'content': user_input})
# Create a secure prompt that doesn't include sensitive data
prompt = f"You are a helpful assistant. Respond to the following user request: {user_input}"
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant that does not share or store personal information.'},
{'role': 'user', 'content': user_input}
],
max_tokens=150
)
# Get the assistant's response
assistant_response = response.choices[0].message.content
# Add assistant response to history
self.conversation_history.append({'role': 'assistant', 'content': assistant_response})
return assistant_response
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
# Main program
if __name__ == "__main__":
agent = SecureAIAssistant()
print("Secure AI Assistant is ready! Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
response = agent.get_response(user_input)
print(f"AI: {response}")
Why this step? This code creates a basic AI agent that can have conversations while being mindful of security best practices.
5. Test Your AI Agent
Run your AI agent by typing:
python ai_agent.py
Try asking questions like "What can you help me with?" or "Tell me about AI security." Notice how the agent doesn't store or share your personal information.
Why this step? Testing helps you understand how the agent works and ensures it's functioning correctly before adding more features.
6. Add Data Protection Features
Let's enhance our agent with better data protection by modifying the ai_agent.py file:
import os
from dotenv import load_dotenv
import openai
import hashlib
# Load environment variables
load_dotenv()
# Initialize OpenAI client
openai.api_key = os.getenv('OPENAI_API_KEY')
class SecureAIAssistant:
def __init__(self):
self.conversation_history = []
self.user_id = self.generate_user_id()
def generate_user_id(self):
# Generate a unique identifier for this session
return hashlib.md5(os.urandom(16)).hexdigest()[:8]
def get_response(self, user_input):
# Log that we're processing user input but don't store it
print(f"Processing input from user {self.user_id}")
# Create a secure prompt
prompt = f"You are a helpful assistant. Respond to the following user request: {user_input}"
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant that does not store or share personal information. Do not ask for personal details.'},
{'role': 'user', 'content': user_input}
],
max_tokens=150
)
assistant_response = response.choices[0].message.content
# Log the interaction without storing personal data
print(f"Interaction processed for user {self.user_id}")
return assistant_response
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
# Main program
if __name__ == "__main__":
agent = SecureAIAssistant()
print("Secure AI Assistant is ready! Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
response = agent.get_response(user_input)
print(f"AI: {response}")
Why this step? Adding a user ID and preventing data storage demonstrates how to build security into AI systems from the start.
7. Implement Data Sanitization
Let's add one more security feature to prevent accidentally sharing sensitive information:
import os
from dotenv import load_dotenv
import openai
import re
# Load environment variables
load_dotenv()
# Initialize OpenAI client
openai.api_key = os.getenv('OPENAI_API_KEY')
# Define sensitive patterns to avoid
SENSITIVE_PATTERNS = [
r'\b\d{4}-?\d{4}-?\d{4}-?\d{4}\b', # Credit card numbers
r'\b\d{3}-?\d{2}-?\d{4}\b', # SSN
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' # Email
]
class SecureAIAssistant:
def __init__(self):
self.conversation_history = []
self.user_id = self.generate_user_id()
def generate_user_id(self):
return hashlib.md5(os.urandom(16)).hexdigest()[:8]
def sanitize_input(self, user_input):
# Check for sensitive information
for pattern in SENSITIVE_PATTERNS:
if re.search(pattern, user_input):
return "I cannot process inputs that contain sensitive information. Please remove any personal data."
return user_input
def get_response(self, user_input):
# Sanitize the input before processing
sanitized_input = self.sanitize_input(user_input)
if sanitized_input != user_input:
return sanitized_input
print(f"Processing input from user {self.user_id}")
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant that does not store or share personal information. Do not ask for personal details.'},
{'role': 'user', 'content': user_input}
],
max_tokens=150
)
assistant_response = response.choices[0].message.content
print(f"Interaction processed for user {self.user_id}")
return assistant_response
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
# Main program
if __name__ == "__main__":
agent = SecureAIAssistant()
print("Secure AI Assistant is ready! Type 'quit' to exit.")
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
response = agent.get_response(user_input)
print(f"AI: {response}")
Why this step? This security feature prevents accidentally processing sensitive personal information that could be misused.
Summary
In this tutorial, you've learned how to build a basic AI agent with security considerations. You created a Python program that:
- Uses a virtual environment to isolate dependencies
- Manages API keys securely using environment variables
- Protects user privacy by not storing personal information
- Sanitizes inputs to prevent accidental sharing of sensitive data
This approach demonstrates how to build AI systems responsibly, addressing the security concerns highlighted in recent news about unsecured AI agents. Remember that building secure AI systems requires constant attention to data protection and privacy best practices.