The world is moving from the simple AI chat boats to answer our questions to full systems that are very capable. AI agents can not only answer our questions, but also do the work we give them freely, which can make them more powerful and useful.
In this tutorial, you will create an advanced, web -based agent that works as your virtual study planner. This AI agent will be able to work to understand, make decisions and achieve your goals.
This project goes beyond the basic conversation. You will learn to be a round -based agent with two important abilities:
Memorandum: The agent will remember the whole date of your conversation, which will provide follow -up advice based on your feedback and adopt its plans.
Use of Tolls: The agent will be able to use the search tool to find the relevant online resources, which will make it a more powerful assistant that relies fully on its internal knowledge.
You will learn to create a complete system with a simple web UI built with Flask and Tail Wind CSS, which will provide a solid foundation for building even more complex agents in the future. So, let’s start.
Table of contents:
Provisions
Before following this tutorial, you should be:
Basic knowledge
The basics of web development
Is installed 3+ on your machine
Install VS code or any other IDE of your choice
This study planner agent to build You’l, you will need some ingredients:
Google Gemini API: This is the basic AI service that provides a generative model. It allows our agent to produce reactions like natural language, cause, and humans.
Flask: This is a lightweight web framework for Azigar. We will use it to make our web server (ie back). Its main purpose here is to handle web applications from the user’s browser, to take action and respond back.
Tel Wind CSS: This is a CSS framework for the construction of the user interface (ie Front &). Instead of writing custom CSS, you use default classes
bg-blue-300For, for, for, for,.m-4And so, styling the page directly into your HTML.Uzar-Dutino: This library helps us manage environmental variables.
Looking for Dick Dickgo: This library provides an easy way to conduct real -time web search. It acts as a “tool” for our AI agent. When a user asks a question that requires external information, our agent can use this tool to find relevant resources on the web and use this information to compile the answer.
Understanding AI agents
Before jumping into the code, let’s cover the basics so you understand what the AI ​​agent is and worth it.
What are AI agents? How many types are there?
AI agent is software that can operate on the user’s behalf. AI agents work to achieve their surroundings, process information and user goals. Unlike fixed programs, an agent can reasonable and adapt.
There are some different types of agents, including:
Simple reflex (Works on the current input, such as thermostat)
Based on the model (Uses internal maps, such as robots vacuums)
Round -based (Subscribed to goals like a study planner)
Based on utility (Choose the best results, such as trading boats)
The learning agent (Improve over time, such as recommendations system).
How are AI agents unique than other AI tools?
AI agents use technologies like LLM, but they are separated because of their sovereignty and ability to act. Let’s understand these different types of AI tools in more detail:
Large language models (llms): LLMS are the brain of operation. They are trained on a very large datastate to understand and process consumer questions in natural language to produce human -like production. There are all examples of Open AIKGPT, Google’s Gemini, and Anthropic Claude LLM.
Recovery from the collective race (RAG): RAG is a process or a technique that allows LLM to answer not only from training data but also from external sources, such as a database or document library. Although the chord retrieves information, it does not decide to freely plan a process or plan a step to achieve a goal.
AI agent: As described above, the agents are the systems that can perform the user’s work using LLM as their primary reasoning engine. The full architecture of an agent allows him to understand his environment, plan, process, and learning (based on memory, past conversation).
In this tutorial, you are going to use an agent for an LLM (Gemini) as well as a web search engine, Dick Dickgo Search,. So, now we move towards the next step.
How to configure your environment
Before you can create your virtual study planner AI agent, you will need to establish your development environment. These are the steps you will need to follow:
1. Make the Project Directory
First, create a new folder with any name and move to this directory:
mkdir study-planner
cd study-planner
2. Create a virtual environment
In the meantime, it is always recommended to work in a virtual environment. So, make one and activate it like this:
python -m venv venv
Now activate the virtual environment:
source venv/bin/activate
venv\Scripts\activate
3. Install dependent
We will need a couple of packages or dependence to build an AI Study Planner Agent, and they include:
flask: Web servergoogle-generativeai: Gemini clientpython-dotenv: .env load the gym_P_Prequests: Useful http helper (good)duckduckgo-search: Real Web Search
You can install them with a command:
pip install flask google-generativeai python-dotenv requests duckduckgo-search
4. Get your gym API key
Barley Google AI Studio And create a new account (if you don’t already have).

Next, get yourself a new API key by clicking Make the API key By API Keys Section

Note: Once the API key is ready, save it somewhere else. You may not find the same API key again.
5. Add to your key .env File
A .env Within the file backend/ And add your API key.
GEMINI_API_KEY=your_api_key_here
Now you should have successfully configured your development environment. You are ready to make a virtual study planner AI agent. Let’s start!
How to build real time agent logic
The main part of this project is a permanent loop that accepts the user’s input, maintains the date of conversation, and sends this date to Gemini API to create a response. That way we give memory to the agent.
Create Gemini Client (with web search)
Create a new file backend/gemini_client.py:
import os
from typing import List, Dict
import google.generativeai as genai
from dotenv import load_dotenv
from duckduckgo_search import DDGS
load_dotenv()
def perform_web_search(query: str, max_results: int = 6) -> List(Dict(str, str)):
"""Perform a DuckDuckGo search and return a list of results.
Each result contains: title, href, body.
"""
results: List(Dict(str, str)) = ()
try:
with DDGS() as ddgs:
for result in ddgs.text(query, max_results=max_results):
if not isinstance(result, dict):
continue
title = result.get('title') or ''
href = result.get('href') or ''
body = result.get('body') or ''
if title and href:
results.append({
'title': title,
'href': href,
'body': body,
})
return results
except Exception as e:
print(f"DuckDuckGo search error: {e}")
return ()
class GeminiClient:
def __init__(self):
try:
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
self.model = genai.GenerativeModel('gemini-1.5-flash')
self.chat = self.model.start_chat(history=())
except Exception as e:
print(f"Error configuring Gemini API: {e}")
self.chat = None
def generate_response(self, user_input: str) -> str:
"""Generate an AI response with optional web search when prefixed.
To trigger web search, start your message with one of:
- "search: "
- "/search "
Otherwise, the model responds directly using chat history.
"""
if not self.chat:
return "AI service is not configured correctly."
try:
text = user_input or ""
lower = text.strip().lower()
search_query = None
if lower.startswith("search:"):
search_query = text.split(":", 1)(1).strip()
elif lower.startswith("/search "):
search_query = text.split(" ", 1)(1).strip()
if search_query:
web_results = perform_web_search(search_query, max_results=6)
if not web_results:
return "I could not retrieve web results right now. Please try again."
refs_lines = ()
for idx, item in enumerate(web_results, start=1):
refs_lines.append(f"({idx}) {item('title')} — {item('href')}\n{item('body')}")
refs_block = "\n\n".join(refs_lines)
system_prompt = (
"You are an AI research assistant. Use the provided web search results to answer the user query. "
"Synthesize concisely, cite sources inline like (1), (2) where relevant, and include a brief summary."
)
composed = (
f"\n{system_prompt}\n \n"
f"\n{search_query}\n \n"
f"\n{refs_block}\n "
)
response = self.chat.send_message(composed)
return response.text
response = self.chat.send_message(text)
return response.text
except Exception as e:
print(f"Error generating response: {e}")
return "I'm sorry, I encountered an error processing your request."
Let’s understand what is happening in the above code:
Flask Passead and Make Front End
Next, we will set the Flask Web server to connect our agent logic to a simple web interface.
Flask backpack
Make a new backend Folder inside the Study Planner Directory, and add a new file app.py:
import os
from flask import Flask, render_template, request, jsonify
from gemini_client import GeminiClient
app = Flask(__name__, template_folder='../templates')
client = GeminiClient()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/chat', methods=('POST'))
def chat():
payload = request.get_json(silent=True) or {}
user_message = payload.get('message', '').strip()
if not user_message:
return jsonify({'error': 'No message provided'}), 400
try:
response_text = client.generate_response(user_message)
return jsonify({'response': response_text})
except Exception as e:
return jsonify({'error': 'Error generating response'}), 500
if __name__ == '__main__':
app.run(debug=True)
What does it do:
@app.route('/'): This is a homepage. When a user navigate to the main URL, such as,http://localhost:5000), Runs flaskindex()Function, which offers easilyindex.htmlThis browser prove to the entire user interface when you do not want to use the command line interface.Next, we have created
@app.route('/api/chat', methods=('POST'))API closing point. When the user clicks “Send” on Front End, JavaScript sends onePOSTApply this URL.chat()Then the function receives the user’s message, gives it to himGeminiClientTo get the answer and then send this reaction back to Front End as a JSON object.
Flask Front End
Create a new folder whose name is templates In the Route Directory of your project. Inside it, make a file index.html.
html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AI Study Plannertitle>
<script src="https://cdn.tailwindcss.com">script>
<style>
body {
background-color: #f3f4f6;
}
.chat-container {
max-width: 768px;
margin: 0 auto;
display: flex;
flex-direction: column;
height: 100vh;
}
.typing-indicator {
display: flex;
align-items: center;
padding: 0.5rem;
color: #6b7280;
}
.typing-dot {
width: 8px;
height: 8px;
margin: 0 2px;
background-color: #6b7280;
border-radius: 50%;
animation: typing 1s infinite ease-in-out;
}
.message-bubble {
padding: 1rem;
border-radius: 1.5rem;
max-width: 80%;
margin-bottom: 1rem;
}
.user-message {
background-color: #3b82f6;
color: white;
align-self: flex-end;
}
.agent-message {
background-color: #e5e7eb;
color: #374151;
align-self: flex-start;
}
style>
head>
<body class="bg-gray-100">
<div class="chat-container">
<header
class="bg-white shadow-sm p-4 text-center font-bold text-xl text-gray-800"
>
AI Study Planner
header>
<main id="chat-history" class="flex-1 overflow-y-auto p-4 space-y-4">
<div class="message-bubble agent-message">
Hello! I'm your AI Study Planner. What topic would you like to study
today?
div>
main>
<footer class="bg-white p-4">
<div class="flex items-center">
<input
type="text"
id="user-input"
class="flex-1 p-3 border-2 border-gray-300 rounded-full focus:outline-none focus:border-blue-500"
placeholder="Type your message..."
/>
<button
id="send-btn"
class="ml-4 px-6 py-3 bg-blue-500 text-white rounded-full font-semibold hover:bg-blue-600 transition-colors"
>
Send
button>
div>
footer>
div>
<script>
const chatHistory = document.getElementById("chat-history");
const userInput = document.getElementById("user-input");
const sendBtn = document.getElementById("send-btn");
function addMessage(sender, text) {
const messageElement = document.createElement("div");
messageElement.classList.add(
"message-bubble",
sender === "user" ? "user-message" : "agent-message"
);
messageElement.textContent = text;
chatHistory.appendChild(messageElement);
chatHistory.scrollTop = chatHistory.scrollHeight;
}
async function sendMessage() {
const message = userInput.value.trim();
if (message === "") return;
addMessage("user", message);
userInput.value = "";
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ message: message }),
});
const data = await response.json();
if (data.response) {
addMessage("agent", data.response);
} else if (data.error) {
addMessage("agent", `Error: ${data.error}`);
} else {
addMessage("agent", "Unexpected response from server.");
}
} catch (error) {
console.error("Error:", error);
addMessage("agent", "Sorry, something went wrong. Please try again.");
}
}
sendBtn.addEventListener("click", sendMessage);
userInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
sendMessage();
}
});
script>
body>
html>
This is the whole UI. This is just a page with a text box and a send button. This includes an easy JavaScript function to handle the interaction of the chat. How does it work:
How to test AI agent
At this point, your project structure should look like:
study-planner/
├── backend/
│ ├── .env
│ ├── app.py
│ └── gemini_client.py
└── templates/
└── index.html
Now, get on backend Directory, and run:
cd backend
python app.py
If everything has been configured, you will start the flask app Or http://localhost:5000.
Open this URL in your browser. Just, you have finally created an AI agent for yourself!
Try to ask ordinary questions such as:
Or you can also mobilize the web search like:
When you use the search prefix as above, the agent brings a handful of links and asks Gymnony To synthesize them with short inline references such as (1), (2). This is great for a quick research summary.
Wrap
Congratulations! Now you have a working study planner agent that remembers your chats and can even see things online.
From here, you can further enhance this agent:
Saving user dates in the database.
Adding verification, handling several users.
Concentrated calendars or task managers, and more.
This Foundation provides a solid point for the construction of more sophisticated AI agents according to your specific needs.
If you have been this tutorial helpful and would like to discuss AI development or software development, contact me without hesitation X/TwitterFor, for, for, for,. LinkedOr check my portfolio Blog. I regularly share insights about AI, development, technical writing, etc., and would love to see what you make with this foundation.
Happy coding!