Creating your first Simple AI Agent: End-to-End Guide


Part 1: Building the AI Agent
1. Understanding the AI Agent Concept
An AI agent is a system that perceives its environment through sensors and acts upon that environment through actuators. For our simple agent, we'll create a rule-based chatbot that can answer questions about specific topics.
2. Choosing the Tech Stack
For this project, we'll use:
Python: The programming language
Flask: Web framework for the interface
NLTK: For basic natural language processing
Rule-based approach: Simple pattern matching
3. Implementation Steps
Step 1: Setting Up the Environment
mkdir simple-ai-agent
cd simple-ai-agent
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install flask nltk
Step 2: Creating the Agent Logic
import re
import random
from nltk.chat.util import Chat, reflections
# Define response pairs
pairs = [
[
r"my name is (.*)",
["Hello %1! How can I help you today?",]
],
[
r"what is your name?",
["I'm SudhinBot, your AI assistant.",]
],
[
r"how are you?",
["I'm functioning optimally, thank you!", "I'm just a program, but I'm running well!"]
],
[
r"(.*) (weather|temperature) (.*)",
["I'm not connected to weather services, but you can check your favorite weather app!",]
],
[
r"quit",
["Goodbye! It was nice talking to you.", "See you later!"]
],
[
r"(.*)",
["I'm not sure I understand. Can you rephrase that?",]
]
]
class SimpleAIAgent:
def __init__(self):
self.chatbot = Chat(pairs, reflections)
def respond(self, input_text):
return self.chatbot.respond(input_text)
# Example usage
if __name__ == "__main__":
print("Simple AI Agent initialized. Type 'quit' to exit.")
agent = SimpleAIAgent()
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
response = agent.respond(user_input)
print("Bot:", response)
Step 3: Building the Web Interface
from flask import Flask, request, jsonify
from agent import SimpleAIAgent
app = Flask(__name__)
agent = SimpleAIAgent()
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
user_input = data.get('message', '')
response = agent.respond(user_input)
return jsonify({'response': response})
if __name__ == '__main__':
app.run(debug=True)
Step 4: Creating the Frontend
<!DOCTYPE html>
<html>
<head>
<title>Simple AI Agent</title>
<style>
#chatbox { height: 300px; border: 1px solid #ccc; overflow-y: scroll; padding: 10px; }
#userInput { width: 80%; }
</style>
</head>
<body>
<h1>Simple AI Agent</h1>
<div id="chatbox"></div>
<input type="text" id="userInput" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<script>
function sendMessage() {
const input = document.getElementById('userInput');
const message = input.value;
input.value = '';
// Display user message
const chatbox = document.getElementById('chatbox');
chatbox.innerHTML += `<p><strong>You:</strong> ${message}</p>`;
// Send to backend
fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: message })
})
.then(response => response.json())
.then(data => {
chatbox.innerHTML += `<p><strong>Bot:</strong> ${data.response}</p>`;
chatbox.scrollTop = chatbox.scrollHeight;
});
}
// Allow sending with Enter key
document.getElementById('userInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
Step 5: Updating the backend
from flask import Flask, request, jsonify, render_template
from agent import SimpleAIAgent
app = Flask(__name__)
agent = SimpleAIAgent()
@app.route('/')
def home():
return render_template('index.html')
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
user_input = data.get('message', '')
response = agent.respond(user_input)
return jsonify({'response': response})
if __name__ == '__main__':
app.run(debug=True)
Running the Agent
python app.py
Result
Challenges and Learnings
While building this simple agent, I learned:
Rule-based systems are limited but great for learning
Natural language understanding is complex
Even simple AI can feel surprisingly interactive
Next Steps
To improve this agent, you could:
Add machine learning for better understanding
Connect to APIs for real data
Implement memory for context awareness
Conclusion
Building this simple AI agent was a great learning experience. While it's basic, it demonstrates core AI concepts and provides a foundation for more complex projects.
Subscribe to my newsletter
Read articles from Sudhin Karki directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Sudhin Karki
Sudhin Karki
I am a Machine Learning enthusiast with a motivation of building ML integrated apps. I am currently exploring the groundbreaking ML / DL papers and trying to understand how this is shaping the future.