Introduction
As AI agents become more autonomous in enterprise environments, the need for robust governance frameworks becomes critical. This tutorial will guide you through creating a basic AI agent governance system using Python, focusing on monitoring, logging, and decision tracking. You'll learn how to implement a governance layer that ensures AI agents operate within defined boundaries while maintaining accountability.
Prerequisites
- Python 3.8 or higher
- Basic understanding of AI/ML concepts and Python programming
- Installed libraries:
openai,python-dotenv,sqlite3,uuid - OpenAI API key (for demonstration purposes)
Step-by-Step Instructions
1. Set Up Your Environment
First, create a new Python project directory and install the required dependencies:
mkdir ai-agent-governance
cd ai-agent-governance
pip install openai python-dotenv
This creates a clean project structure and installs the necessary libraries for interacting with OpenAI's API and managing environment variables.
2. Create Environment Configuration
Create a .env file in your project root to store your API key:
OPENAI_API_KEY=your_actual_api_key_here
This approach keeps your API keys secure and separate from your codebase.
3. Initialize the Governance System
Create a governance.py file to set up the core governance framework:
import os
import sqlite3
from datetime import datetime
from uuid import uuid4
from dotenv import load_dotenv
load_dotenv()
# Initialize database
conn = sqlite3.connect('agent_governance.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS agent_activities (
id TEXT PRIMARY KEY,
timestamp TEXT,
action TEXT,
decision TEXT,
result TEXT,
user_id TEXT,
status TEXT
)
''')
conn.commit()
conn.close()
This establishes a SQLite database to track all agent activities, ensuring transparency and auditability.
4. Create the AI Agent Class
Develop the core AI agent with governance capabilities:
import openai
from governance import log_activity
class AI_Governance_Agent:
def __init__(self, user_id):
self.user_id = user_id
self.client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
def execute_task(self, task_prompt):
# Log the start of the task
activity_id = str(uuid4())
log_activity(activity_id, "task_execution", task_prompt, "started", self.user_id)
try:
# Execute the AI task
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": task_prompt}
],
max_tokens=150
)
result = response.choices[0].message.content
# Log the successful completion
log_activity(activity_id, "task_execution", task_prompt, result, self.user_id, "completed")
return result
except Exception as e:
# Log the error
log_activity(activity_id, "task_execution", task_prompt, str(e), self.user_id, "failed")
raise e
This class encapsulates the AI agent's functionality while ensuring all actions are logged for governance purposes.
5. Implement Logging Functionality
Add the logging functionality to your governance.py file:
import sqlite3
from datetime import datetime
def log_activity(activity_id, action, decision, result, user_id, status="executed"):
conn = sqlite3.connect('agent_governance.db')
cursor = conn.cursor()
cursor.execute('''
INSERT OR REPLACE INTO agent_activities
(id, timestamp, action, decision, result, user_id, status)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
activity_id,
datetime.now().isoformat(),
action,
decision,
result,
user_id,
status
))
conn.commit()
conn.close()
This function records every action taken by the agent, creating an audit trail for governance compliance.
6. Create a Governance Monitor
Build a monitoring system to review agent activities:
import sqlite3
from datetime import datetime
def get_agent_activities(user_id=None):
conn = sqlite3.connect('agent_governance.db')
cursor = conn.cursor()
if user_id:
cursor.execute('''
SELECT * FROM agent_activities
WHERE user_id = ?
ORDER BY timestamp DESC
''', (user_id,))
else:
cursor.execute('''
SELECT * FROM agent_activities
ORDER BY timestamp DESC
''')
activities = cursor.fetchall()
conn.close()
return activities
# Example usage
if __name__ == "__main__":
activities = get_agent_activities()
for activity in activities:
print(f"ID: {activity[0]}, Action: {activity[2]}, Status: {activity[6]}")
This monitor allows administrators to review agent activities and ensure compliance with governance policies.
7. Test the Governance System
Create a test script to demonstrate the governance in action:
from governance import get_agent_activities
from agent import AI_Governance_Agent
# Create agent instance
agent = AI_Governance_Agent(user_id="user_123")
# Execute some tasks
try:
result1 = agent.execute_task("Explain quantum computing in simple terms.")
print("Result 1:", result1)
result2 = agent.execute_task("Generate a list of 5 healthy breakfast ideas.")
print("Result 2:", result2)
except Exception as e:
print("Error occurred:", e)
# Review governance logs
print("\nGovernance Logs:")
activities = get_agent_activities(user_id="user_123")
for activity in activities:
print(f"{activity[1]} - {activity[2]} - {activity[6]}")
This test script demonstrates how the governance system tracks both successful and failed agent operations.
Summary
This tutorial demonstrated how to build a foundational AI agent governance system that tracks agent activities, maintains audit trails, and ensures accountability. By implementing this system, organizations can monitor autonomous AI agents while maintaining compliance with governance policies. The key components include database logging, activity tracking, and monitoring capabilities that can be extended with additional features like policy enforcement, risk assessment, and automated alerts.
As AI agents become more autonomous, systems like this become essential for maintaining control while leveraging AI's capabilities. This framework provides a starting point that can be enhanced with more sophisticated governance mechanisms such as decision validation, policy-based access control, and integration with enterprise security systems.



