DIY AI: Building Your AI Apps on a Shoestring Budget
Artificial Intelligence has become an integral part of modern software applications, as it is known to add extended functionalities to traditional applications. This tutorial will guide you on a simplistic approach to building an AI application.
Image by Editor | Canva
Artificial Intelligence (AI) has become an integral part of modern software applications, as it is known to add extended functionalities that traditional applications that existed before AI could not do; Voice recognition, image detection/classification, and natural language processing (NLP) to say but a few.
AI applications are known to be robust and smarter. Many large companies have adopted AI at the core of their application, and many more companies will continue to adopt this technology as AI advances and they see the need to apply it to solve a particular business need.
You can also build an AI application—it does not have to be as big as Netflix or Instagram, at least for now.
Prerequisites
The tutorial's content is moderately technical; for full utilization, you must have a background in Python programming and web development. The code snippets in this tutorial are written in Python, JavaScript, HTML5, and CSS3.
Objectives
By going through this tutorial you should be able to:
- Understand AI applications and what makes them different from traditional software applications
- Build a basic AI application all by yourself
- Importance of AI applications over the traditional non-AI applications
What is an AI Application?
AI apps refer to software (web, mobile, or any other platform application) that partially or entirely uses AI to solve tasks that typically require human intelligence.
There are many AI applications currently running, many of which we use every day without even knowing; Instagram, Facebook, WhatsApp, Netflix, Google, ChatGPT, and ClaudeAi, to mention but a few, are all popular AI applications that use AI in one way or another.
The AI components of these apps learn from datasets, from which they can understand patterns and intricacies and use this information to solve tasks passed to them. For example, the Google search engine utilizes LLMs (Large Language Models) in carrying out text auto-completion and semantic search, and not just a keyword search on queries passed to it; this enables it to retrieve results that are in the same context or closest in meaning to what the user intends to search for, even if he types in his search prompts using different keywords.
Also, Google Lens utilizes the power of computer vision for image search because it has been trained on large datasets containing images; it is capable of classifying images; it can tell you what image is what. Instagram utilizes AI as part of its recommendation algorithm by showing users targeted ads and posts that match their preferences through a method known as unsupervised machine learning. These are some of the cool implementations of AI in an AI app.
Differences Between AI and Non-AI apps
The main differences between AI and non-AI apps lie in how they handle data, make decisions, and adapt over time.
- AI Apps can make decisions based on probabilistic models, often using techniques like machine learning, natural language processing, or computer vision. For instance, a recommendation system in an AI app can suggest items based on a user's past behavior. Meanwhile, a non-AI app relies on a fixed set of instructions to execute tasks. Their decisions are predetermined, and they do not consider new data or user-specific nuances without additional programming
- AI apps learn from datasets using predefined algorithms, from which they can make decisions without being explicitly programmed. Whereas, Non-AI apps follow a set of hard-coded programming rules “if-else”, aside from which they cannot make decisions
- AI apps can easily adapt to new situations, recognizing new patterns and providing related feedback. Meanwhile, non-AI apps are not as flexible, they can only handle structures and predictable situations
Different Types of AI Apps
Depending on the use case and the problem the app is intended to solve, there are numerous ways AI can be used to build smart applications. Below are some of the popular ways AI apps are implemented.
- Natural Language Processing: These are apps that understand what you’re saying or typing, like Siri or Alexa. They’re good for voice commands and chatbots that answer questions or help with customer support
- Computer Vision: Think of apps that "see" for you—like when your phone recognizes your face to unlock or when Google Photos sorts your pics. These AI apps are used in everything from social media to security systems
- Recommender Systems: are the engines behind your Netflix recommendations or Spotify playlists. They determine what you might like based on your past choices and can personalize your experience: These are the engines behind your Netflix recommendations or Spotify playlists. They determine what you might like based on your past choices and can make your experience more personalized
- Automated Task Apps: If you’ve used a chatbot to answer common questions or a tool that scans and organizes documents, you’ve experienced this type of AI. It’s great for handling repetitive tasks without human intervention
- Creative AI Apps: AI can be surprisingly creative! These apps make art, write stories, or even generate personalized designs based on your input, like AI art generators or text-writing tools
- Self-Driving and Autonomous Systems: Think self-driving cars, robotic vacuums, or independently operating drones. They’re all about using AI to handle complex tasks without constant guidance
A Quick Guide to Building an AI App on your Own
As seen above, AI can be utilized in numerous ways to build smart applications, but for this tutorial, we will stick to a minimalistic approach to building an LLM-backed AI chatbot.
Procedure:
Select a preferred publicly available pre-trained LLM whose API key you will use to access their API. In this case, we are using OpenAI’s GPT-4.
Create a folder on your desktop called “AI_APP”, install VSCode, and navigate to the folder. I assume you already have Python downloaded and installed on your computer; if not, then do that before going to the next step.
Create a virtual environment. If you are using Linux OS (operating system), run these commands in your command prompt to create and activate the virtual environment.
python3 -m venv myvenv
source myvenv/bin/activate
If you are using Windows OS, then run these commands instead
python -m venv myenv
myenv\Scripts\activate
Install dependencies for the project(Flask, requests)
pip install flask requests
Set up your application structure:
AI_APP/
├── app.py # where your application instance and logic will be
├── templates/
└── index.html # html template to display the front end of your app
└── static/
└── style.css # for styling your front-end/templates
After setting up the structure of your application in VSCode, you can start coding your application immediately.
Inside your app.py file, you instantiate your Flask application, create routes, receive the prompt message passed from the front end, and send a ‘POST’ request to the OpenAI API using the ‘requests’ library. You then receive the text response, process it, and pass it to the front end, as shown in the code snippet below.
from flask import Flask, render_template, request, jsonify
import requests
import os
app = Flask(__name__)
# Load your API key securely (consider using environment variables)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # Set this in your environment or replace it with the actual key.
@app.route("/")
def home():
return render_template("index.html")
@app.route("/ask_question", methods=["POST"])
def ask():
user_message = request.json["message"]
# Call GPT-4 API with the user's message
response = openai_call(user_message)
return jsonify({"response": response})
def openai_call(message):
headers = {
"Authorization": f"Bearer {OPENAI_API_KEY}",
"Content-Type": "application/JSON",
}
data = {
"model": "gpt-4",
"messages": [{"role": "user", "content": message}],
}
# Make the request to OpenAI API
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
return "Error: Could not reach the OpenAI API"
if __name__ == "__main__":
app.run(debug=True)
Inside your index.html file, write the code below to create a basic front-end that a user can interact with. The prompt message is entered by the user, converted to JSON through Javascript, and finally sent to the backend for further processing, as shown in the code snippet above. Below is a basic front-end implementation for the AI app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="chat-container">
<div id="chat-box"></div>
<input type="text" id="user-input" placeholder="Please type your message here..." />
<button onclick="sendMessage()">Send</button>
</div>
<script>
function addMessage(content, isUser) {
const chatBox = document.getElementById("chat-box");
const messageDiv = document.createElement("div");
messageDiv.className = isUser ? "user-message" : "bot-message";
messageDiv.textContent = content;
chatBox.appendChild(messageDiv);
chatBox.scrollTop = chatBox.scrollHeight;
}
async function sendMessage() {
const userInput = document.getElementById("user-input").value;
addMessage(userInput, true);
// Send user input to the server
const response = await fetch("/ask", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: userInput })
});
const data = await response.json();
addMessage(data.response, false);
document.getElementById("user-input").value = "";
}
</script>
</body>
</html>
Let's style the front end of our application. Add the code snippet below to your style.css file
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.chat-container {
width: 400px;
height: 500px;
display: flex;
flex-direction: column;
border: 2px solid #ddd;
border-radius: 8px;
background-color: #fff;
overflow: hidden;
}
#chat-box {
flex: 1;
padding: 10px;
overflow-y: auto;
}
.user-message {
text-align: right;
padding: 8px;
margin: 4px;
background-color: #a6e1fa;
border-radius: 8px;
}
.bot-message {
text-align: left;
padding: 8px;
margin: 4px;
background-color: #e0e0e0;
border-radius: 8px;
}
input[type="text"] {
width: calc(100% - 60px);
padding: 10px;
border: none;
outline: none;
}
button {
padding: 10px;
width: 60px;
border: none;
background-color: #007BFF;
color: white;
font-weight: bold;
cursor: pointer;
}
There you go, you have a basic AI-powered chatbot.
Conclusion
AI is revolutionizing how modern applications function, increasing performance and user experience when used strategically. Building an AI application can be a rewarding investment if a use case has been identified for it; it could be slightly or way more complex than what has been demonstrated in this tutorial; It can be a spam detection, fraud detection, recommendation system, or even an image classification application. Rest assured that it is worthwhile so long as it is rightly implemented.
Shittu Olumide is a software engineer and technical writer passionate about leveraging cutting-edge technologies to craft compelling narratives, with a keen eye for detail and a knack for simplifying complex concepts. You can also find Shittu on Twitter.