Build Your First AI Agent in Python
Build a terminal AI agent with tool calling, memory, and reasoning in Python.
Introduction
30 Second Summary
Jab tum Google Assistant ya ChatGPT se kuch puchte ho, wo sirf text generate nahi karta. Wo sochta hai, tools use karta hai (jaise calculator ya search), aur phir answer deta hai. Yahi hai ek AI Agent.
In this project, you will apna khud ka AI Agent banao jo tumhare terminal mein chalega. Ye agent math solve karega, words ke meanings batayega, aur tumhari purani baatein yaad rakhega.
What You'll Build
A Smart Study Buddy AI Agent that runs in your terminal, uses tools to answer questions, and remembers your conversation history.
By the end of this project, you'll have:
- A working AI Agent that decides which tool to use (calculator or dictionary) based on your question.
- Hands-on understanding of Tool Calling, Prompt Engineering, and Conversation Memory patterns used in production AI systems.
- A reusable Python project structure that you can extend with more tools and capabilities.
- Secret Mission: Add a Wikipedia Search tool so your agent can fetch real information from the internet.
Are there any prerequisites?
Koi bhi nahi. This project includes full setup instructions for Python, VS Code, and the Groq API. Tum bilkul zero se shuru kar sakte ho.
Install Python and VS Code
AI Agent banane ke liye tumhare computer pe kuch tools chahiye. Python wo programming language hai jismein hum apna agent code likhenge.
VS Code ek code editor hai jo coding ko easy banata hai. Aur Groq ek free API service hai jo humein AI model access deti hai.
In this step, get ready to:
- Python 3.14 install karo aur verify karo.
- VS Code install karo with Python extension.
- Groq ka free account banao aur API key generate karo.
Python 3.14 download aur install karo
Python wo language hai jismein humara agent code chalega. Tumhein version 3.14 ya usse naya chahiye kyunki humari libraries isko support karti hain.
- Apna browser kholo aur python.org/downloads pe jaao.
- **Download Python 3.14.5** button pe click karo (ya latest 3.14 version jo dikhaye).
- Windows Installer (64-bit) download karo.
- Downloaded file pe double-click karke installer kholo.
- Installer ke pehle page pe "Add Python to PATH" checkbox ko tick karo. Ye bahut zaroori hai.
- Click Install Now.
- Installation complete hone tak wait karo, phir Close click karo.
Why is Add Python to PATH important?
PATH ek system setting hai jo batati hai ki terminal mein commands kahan se dhundhni hain. Bina PATH ke, terminal ko python command nahi milegi aur tumhara code nahi chalega.
Ab verify karte hain ki Python sahi se install hua hai.
- Press the Windows key to open your search bar.
- Type PowerShell and press Enter to open it.
- Python version check karo by running this command:
python --version
✔️ I see Python 3.14 or higher
Badhai ho! Python sahi se install ho gaya hai. Agle step pe chalo.
ⓧ I see an older version
Tumhare system pe ek purani Python version installed hai. Naya version install karna hoga.
- python.org/downloads pe jaao aur Python 3.14.5 ka Windows Installer (64-bit) download karo.
- Installer run karo. Agar Upgrade Now option dikhe toh use click karo.
- Agar Upgrade Now na dikhe, toh "Add Python to PATH" tick karke Install Now click karo.
- PowerShell band karo aur dubara kholo.
- Phir se python --version run karo. Ab 3.14 dikhna chahiye.
Still seeing the old version?
Purani Python installation ko uninstall karo Settings > Apps > Apps & features se. Phir naye installer ko dubara run karo with PATH checkbox ticked.
Help me fix my Python version issue.
ⓧ Command not found
Python abhi install nahi hai tumhare system pe. Install karte hain.
- python.org/downloads pe jaao.
- Download Python 3.14.5 (Windows Installer 64-bit).
- Downloaded file pe double-click karo.
- "Add Python to PATH" checkbox zaroor tick karo.
- Click Install Now aur complete hone tak wait karo.
- PowerShell band karo aur dubara kholo (ye zaroori hai taaki PATH update ho).
- Ab python --version run karo. Tumhein Python 3.14.5 dikhna chahiye.
Still not working after install?
Agar install ke baad bhi command not found aa raha hai, toh PATH mein Python add nahi hua. Installer dubara run karo, Modify select karo, aur PATH option enable karo.
Help me fix my Python PATH issue on Windows.
VS Code download aur install karo
VS Code ek free code editor hai jismein hum apna Python code likhenge. Isme built-in terminal bhi hai jo bahut kaam aayega.
- Apne browser mein code.visualstudio.com pe jaao.
- Download for Windows button pe click karo.
- Downloaded installer pe double-click karo aur default settings ke saath install karo.
- Installation ke baad, VS Code open karo. Press the Windows key, type Visual Studio Code, and press Enter.
Ab Python extension install karte hain jo VS Code ko Python ke liye smart banata hai.
- VS Code ke left sidebar mein Extensions icon pe click karo (ya press Ctrl+Shift+X).
- Search bar mein Python type karo.
- Microsoft ke "Python" extension pe click karo (publisher: ms-python).
- Click Install.
What does the Python extension do?
Ye extension VS Code ko Python ke liye superpower deta hai. Code completion, error highlighting, debugging, aur built-in terminal activation sab iske through milta hai.
- Confirm karo ki extension install ho gaya. Extensions panel mein "Python" ke neeche Disable aur Uninstall buttons dikhne chahiye.
Extension install nahi ho raha?
Check karo ki tumhara internet connection chal raha hai. Agar proxy ya firewall issue hai, toh VS Code restart karo aur dubara try karo.
Help me install the Python extension in VS Code.
Groq ka free account banao aur API key lo
Groq ek AI inference platform hai jo humein free mein LLM (Large Language Model) access deta hai. Humara agent iske through sochega aur jawab dega.
- Browser mein console.groq.com pe jaao.
- Sign up karo Google ya GitHub account se. Koi credit card nahi chahiye.
- Sign up complete hone ke baad, left sidebar mein API Keys pe click karo.
- Click Create API Key.
- Key ka naam study-buddy rakh do (ya kuch bhi).
- Click Submit.
- Jo API key dikhe, usse copy karo aur kisi safe jagah paste karo (Notepad, Notes app, ya password manager).
API key sirf ek baar dikhti hai
Groq tumhein API key sirf creation ke waqt dikhata hai. Agar tum bina copy kiye page band kar doge, toh wo key dobara nahi dikhegi. Tumhein naya key banana padega.
What is an API key?
API key ek password jaisa hai jo tumhare code ko Groq ke AI models se baat karne ki permission deta hai. Jab tumhara agent AI se kuch poochega, ye key prove karegi ki tum authorized ho.
Sign up mein problem?
Agar Google se sign up nahi ho raha, toh GitHub try karo ya email se register karo. Groq ka free tier completely free hai with no credit card required.
Help me create a Groq account and get my API key.
Tumhara setup ready hai. Python installed hai, VS Code ready hai, aur Groq API key tumhare paas hai. Agle step mein hum apna project folder banayenge aur pehla AI call karenge.
Set Up Project and Make First API Call
Ab tumhare paas Python, VS Code, aur Groq API key ready hai. Ab hum apna project folder banayenge aur AI se pehli baat karenge.
Is step mein tum ek virtual environment set up karoge, Groq library install karoge, aur apna pehla API call banaoge.
In this step, get ready to:
- Project folder aur virtual environment create karo.
- Groq library install karo aur API key configure karo.
- Apna pehla AI chat completion call banao aur Hinglish response dekho.
Create project folder aur virtual environment
Sabse pehle apne project ke liye ek dedicated folder chahiye. Virtual environment Python packages ko isolated rakhta hai taaki different projects ke packages ek dusre se conflict na karein.
- VS Code mein terminal kholo by pressing Ctrl+` (backtick key, usually above Tab).
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir study-buddy-agent
cd study-buddy-agent
- Ab is folder ko VS Code mein open karo. Click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop, select the study-buddy-agent folder, and click Select Folder.
- Agar VS Code pooche "Do you trust the authors of the files in this folder?" toh Yes, I trust the authors click karo.
- Naya terminal kholo by pressing Ctrl+` again (ya Terminal > New Terminal click karo).
Ab terminal automatically study-buddy-agent folder mein open hoga.
- Virtual environment banao by running this command:
python -m venv venv
What does this command do?
python -m venv venv Python ko bolta hai ki ek isolated environment banao venv naam ke folder mein.
Is environment mein jo bhi packages install karoge, wo sirf is project ke liye honge. Tumhare computer ke baaki Python projects affected nahi honge.
- Virtual environment activate karo by running this command:
Windows
venv\Scripts\activate
Terminal mein (venv) dikhna chahiye line ke start mein.
macOS
source venv/bin/activate
Terminal mein (venv) dikhna chahiye line ke start mein.
(venv) nahi dikh raha?
Windows pe agar error aaye ki scripts run karna allowed nahi hai, toh pehle ye command run karo:
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
Phir dubara activate command try karo. Help me activate my virtual environment
- Groq library install karo by running this command:
pip install groq==1.2.0
Installation complete hone ke baad Successfully installed message dikhega terminal mein.
Install fail ho raha hai?
Check karo ki (venv) terminal mein dikh raha hai. Agar nahi hai toh pehle activate command dubara run karo.
Agar internet connection error aaye toh apna WiFi check karo aur dubara try karo. Help me install the groq package
Pehla API call banao
Ab tumhara environment ready hai. Chalo ek .env file mein API key store karein aur phir apna pehla AI call likhen.
- VS Code ke Explorer sidebar mein (left side), click the New File icon (page with a + sign).
- File ka naam .env rakho aur Enter press karo.
- Is file mein apni Groq API key paste karo:
GROQ_API_KEY=your-api-key-here
- Replace your-api-key-here with the actual API key you copied from Groq console.
- Save the file (Ctrl+S).
Why a .env file?
.env file ek safe jagah hai API keys store karne ke liye. Ye file tumhare code se alag rehti hai taaki accidentally kisi ko share na ho jaaye.
Abhi hum terminal mein manually key set karenge. Lekin .env file mein likha rehna helpful hai taaki key kho na jaaye.
- Terminal mein apni API key ko environment variable mein set karo:
Windows
$env:GROQ_API_KEY="your-api-key-here"
macOS
export GROQ_API_KEY="your-api-key-here"
- Ab ek naya file banao called agent.py (same process: New File icon click karo, naam likho agent.py).
- Is file mein ye code paste karo:
import os
import json
from groq import Groq
# --- Groq Client Setup ---
client = Groq(
api_key=os.environ.get("GROQ_API_KEY"),
)
MODEL = "llama-3.3-70b-versatile"
if __name__ == "__main__":
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "user", "content": "Hello! Tum kaun ho?"}
],
)
print(response.choices[0].message.content)
What does this code do?
- Groq client create hota hai tumhari API key ke saath.
- MODEL variable mein llama-3.3-70b-versatile set hai. Ye ek powerful LLM hai jo Groq pe free mein available hai.
- client.chat.completions.create() Groq API ko ek message bhejta hai aur AI ka response wapas laata hai.
- response.choices[0].message.content se AI ka actual text jawab milta hai.
- Save agent.py (Ctrl+S).
- Terminal mein apna agent run karo:
python agent.py
Tumhe AI ka ek response dikhega terminal mein. Ye response English mein hoga kyunki abhi humne AI ko koi special instructions nahi diye.
Error aa raha hai?
Agar authentication error aaye toh check karo ki tumne $env:GROQ_API_KEY (Windows) ya export GROQ_API_KEY (macOS) sahi se set kiya hai.
Agar module not found error aaye toh check karo ki (venv) terminal mein dikh raha hai. Help me fix my agent.py error
System prompt add karo for Hinglish persona
AI ne abhi generic English mein jawab diya. Hum chahte hain ki wo Hinglish mein baat kare aur ek helpful study buddy ki tarah behave kare.
Iske liye hum Prompt Engineering use karenge. Matlab AI ko clear instructions dena ki kaise behave kare. Ye instructions ek "system prompt" mein jaati hain.
- agent.py mein MODEL = "llama-3.3-70b-versatile" ke neeche ye code add karo:
# --- System Prompt (Prompt Engineering) ---
SYSTEM_PROMPT = """You are "Study Buddy" - ek smart AI assistant jo students ki help karta hai.
Rules:
- Hinglish mein baat karo (Hindi + English mix) - jaise Indian students normally baat karte hain
- Jab math question aaye, ALWAYS use the calculate tool
- Jab word meaning poocha jaaye, ALWAYS use the get_meaning tool
- Friendly aur encouraging tone rakho
- Short aur clear answers do
- Jab tool use karo, result ko natural language mein explain karo
"""
What does this system prompt do?
System prompt AI ko "personality" deta hai. Ye rules AI har ek response mein follow karega.
Humne AI ko bola ki Hinglish mein baat kare, tools use kare (ye tools hum next step mein banayenge), aur friendly rahe. Ye same technique hai jo production chatbots mein use hoti hai.
Ab hum is system prompt ko API call mein add karenge.
- agent.py mein neeche messages list mein find karo ye code:
messages=[
{"role": "user", "content": "Hello! Tum kaun ho?"}
],
- Replace it with this code that adds the system prompt before the user message:
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Hello! Tum kaun ho?"}
],
System vs User messages mein kya fark hai?
"system" role wale messages AI ke behavior rules set karte hain. Ye user ko nahi dikhte lekin AI har response mein in rules ko follow karta hai.
"user" role wale messages wo hain jo user ne actually type kiya. AI in dono ko mila ke apna response generate karta hai.
- Save agent.py (Ctrl+S).
- Dubara run karo:
python agent.py
Ab AI ka response Hinglish mein aayega. Wo apna introduction dega as a "Study Buddy" aur friendly tone mein baat karega.
Response abhi bhi English mein aa raha hai?
Check karo ki SYSTEM_PROMPT variable MODEL line ke baad aur if __name__ block se pehle hai.
Messages list mein system message pehle hona chahiye, user message baad mein. Help me fix my system prompt
✔️ Awesome, I've got everything!
Great. Double check you've saved agent.py and move on to the next step.
ⓧ I'd like to double check the full code
Yahan hai tumhare agent.py ka full code abhi tak:
import os
import json
from groq import Groq
# --- Groq Client Setup ---
client = Groq(
api_key=os.environ.get("GROQ_API_KEY"),
)
MODEL = "llama-3.3-70b-versatile"
# --- System Prompt (Prompt Engineering) ---
SYSTEM_PROMPT = """You are "Study Buddy" - ek smart AI assistant jo students ki help karta hai.
Rules:
- Hinglish mein baat karo (Hindi + English mix) - jaise Indian students normally baat karte hain
- Jab math question aaye, ALWAYS use the calculate tool
- Jab word meaning poocha jaaye, ALWAYS use the get_meaning tool
- Friendly aur encouraging tone rakho
- Short aur clear answers do
- Jab tool use karo, result ko natural language mein explain karo
"""
if __name__ == "__main__":
response = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Hello! Tum kaun ho?"}
],
)
print(response.choices[0].message.content)
Aur tumhari .env file:
GROQ_API_KEY=your-api-key-here
Tumhara AI agent ab Hinglish mein baat kar raha hai. Next step mein hum isko tools denge. Calculator aur Dictionary tools banayenge taaki agent math solve kar sake aur word meanings bata sake.
Build the Tools - Calculator and Dictionary
Your AI can chat in Hinglish now, but that's all it can do. If you ask it "25 times 47 kitna hota hai?" it will guess the answer or hallucinate a wrong number.
In this step, you will build two tools that give your agent real capabilities. A calculator tool will solve math accurately, and a dictionary tool will provide word meanings. You will also define the tool schemas that tell the AI what tools are available and how to use them.
In this step, get ready to:
- Create a calculator tool that safely evaluates math expressions.
- Create a dictionary tool with meanings of common tech words.
- Write tool definitions in JSON schema format so the AI knows what tools are available.
Create the calculator function
Python's eval function can evaluate math expressions from a string, but it is dangerous if you pass it unrestricted input. Your calculator will use an allowed_chars set to ensure only numbers and basic math operators are allowed.
- Create a new file called tools.py in your study-buddy-agent folder by clicking the new file icon in the VS Code Explorer sidebar.
- Add the import and the calculator function by pasting this code into tools.py:
import json
# --- Tool 1: Calculator ---
def calculate(expression: str) -> str:
"""Safely evaluate a mathematical expression."""
try:
# Only allow safe math operations
allowed_chars = set("0123456789+-*/().% ")
if not all(char in allowed_chars for char in expression):
return "Error: Only numbers and basic math operators (+, -, *, /, %) are allowed."
result = eval(expression)
return f"Result: {expression} = {result}"
except Exception as e:
return f"Error calculating: {str(e)}"
What does this code do?
- allowed_chars is a set containing only digits and basic math symbols. Any expression with other characters (like letters or system commands) gets rejected immediately.
- eval(expression) evaluates the math string and returns the result. The allowed_chars check above makes this safe because only numbers and operators can reach eval.
- The try/except block catches errors like division by zero and returns a friendly message instead of crashing.
- Save tools.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
Seeing red underlines in VS Code?
If VS Code shows red underlines under import json, make sure your virtual environment is selected as the Python interpreter. Click the Python version in the bottom status bar and select the one inside your venv folder.
Still having issues?
Add the dictionary function
The dictionary tool uses a Python dictionary (hashmap) to store word meanings. This keeps things simple and fast without needing an internet connection.
- Add the dictionary function below the calculate function in tools.py by pasting this code at the bottom of the file:
# --- Tool 2: Dictionary ---
def get_meaning(word: str) -> str:
"""Get the meaning of an English word."""
dictionary = {
"algorithm": "A step-by-step procedure or formula for solving a problem. Programming mein ek set of instructions jo ek specific task complete karta hai.",
"api": "Application Programming Interface - ek set of rules jo allow karta hai different software applications ko ek dusre se communicate karne ke liye.",
"variable": "Programming mein ek named storage location jo data hold karta hai. Iska value change ho sakta hai during program execution.",
"function": "Ek reusable block of code jo ek specific task perform karta hai. Isko baar baar call kar sakte ho.",
"loop": "Ek programming construct jo ek block of code ko repeatedly execute karta hai jab tak condition true hai.",
"agent": "AI mein ek autonomous system jo perceive karta hai environment ko, decisions leta hai, aur actions perform karta hai goals achieve karne ke liye.",
"prompt": "AI model ko diya gaya input text jo usse batata hai ki kya karna hai ya kya generate karna hai.",
"token": "Text ka smallest unit jo language model process karta hai. Ek word mein 1-3 tokens ho sakte hain.",
"inference": "Jab ek trained AI model naye data pe predictions ya outputs generate karta hai.",
"embedding": "Text ko numbers (vectors) mein convert karna taaki computer usse mathematically process kar sake.",
}
word_lower = word.lower().strip()
if word_lower in dictionary:
return f"'{word}' ka meaning: {dictionary[word_lower]}"
else:
return f"Sorry, '{word}' ka meaning mere paas nahi hai. Main sirf kuch common tech/programming words jaanta hun."
What does this code do?
- dictionary is a Python dictionary (hashmap) that maps 10 common tech words to their meanings in Hinglish.
- word.lower().strip() converts the input to lowercase and removes extra spaces so that "Algorithm", "ALGORITHM", and "algorithm" all match.
- If the word is not in the dictionary, the function returns a friendly "sorry" message instead of crashing.
- Save tools.py.
- Test both functions by running this command in your terminal:
python -c "from tools import calculate, get_meaning; print(calculate('25 * 47')); print(get_meaning('algorithm'))"
You should see Result: 25 * 47 = 1175 followed by the meaning of "algorithm" in Hinglish.
Seeing ModuleNotFoundError?
Make sure your terminal is in the study-buddy-agent folder (where tools.py lives). Also check that your virtual environment is still activated. You should see (venv) at the start of your terminal prompt.
Help me debug this ModuleNotFoundError.
Write the tool definitions for the AI
Your functions work, but the AI does not know they exist yet. You need to describe each tool in a specific JSON schema format that the Groq API understands. Think of this as a "menu card" for the AI.
- Add the tool definitions at the bottom of tools.py by pasting this code below the get_meaning function:
# --- Tool Definitions (JSON Schema for Groq API) ---
tool_definitions = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate a mathematical expression. Use this when the user asks to calculate something, do math, or solve a numerical problem.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate, e.g. '25 * 47' or '(10 + 5) * 3'",
}
},
"required": ["expression"],
},
},
},
{
"type": "function",
"function": {
"name": "get_meaning",
"description": "Get the meaning/definition of an English word. Use this when the user asks what a word means or wants a definition.",
"parameters": {
"type": "object",
"properties": {
"word": {
"type": "string",
"description": "The English word to look up the meaning of",
}
},
"required": ["word"],
},
},
},
]
What does this code do?
Each tool definition tells the AI three things: the function's name, what it does (description), and what inputs it expects (parameters). The AI reads these descriptions to decide which tool to call and what arguments to pass.
This is exactly the format that the Groq API expects. The description field is especially important. The clearer your description, the better the AI knows when to use each tool.
- Save tools.py.
Test the tool definitions
The tool definitions are the bridge between your Python functions and the AI. Printing them out helps you see exactly what the AI will read when deciding which tool to use.
- Print the tool definitions by running this command in your terminal:
python -c "from tools import tool_definitions; import json; print(json.dumps(tool_definitions, indent=2))"
You should see a nicely formatted JSON output showing both tool definitions with their names, descriptions, and parameter schemas.
Why is this like a menu card?
When you send these definitions to the Groq API, the AI reads them like a restaurant menu. It sees "calculate" can solve math and "get_meaning" can look up words. Based on the user's question, it picks the right tool from this menu.
The AI never runs your Python code directly. It just says "I want to call calculate with expression '25 * 47'". Your code then executes the function and sends the result back. This is tool calling in action.
Seeing a SyntaxError?
Check that all your curly braces and square brackets are properly closed in the tool_definitions list. Each tool object has nested function and parameters dictionaries, so missing a closing brace is common.
Help me fix this SyntaxError in my tool definitions.
✔️ Awesome, I've got everything!
Great. Double check you have saved tools.py and both test commands printed correct output.
ⓧ I'd like to double check the full code
Here is the complete tools.py file. Make sure yours matches exactly:
import json
# --- Tool 1: Calculator ---
def calculate(expression: str) -> str:
"""Safely evaluate a mathematical expression."""
try:
# Only allow safe math operations
allowed_chars = set("0123456789+-*/().% ")
if not all(char in allowed_chars for char in expression):
return "Error: Only numbers and basic math operators (+, -, *, /, %) are allowed."
result = eval(expression)
return f"Result: {expression} = {result}"
except Exception as e:
return f"Error calculating: {str(e)}"
# --- Tool 2: Dictionary ---
def get_meaning(word: str) -> str:
"""Get the meaning of an English word."""
dictionary = {
"algorithm": "A step-by-step procedure or formula for solving a problem. Programming mein ek set of instructions jo ek specific task complete karta hai.",
"api": "Application Programming Interface - ek set of rules jo allow karta hai different software applications ko ek dusre se communicate karne ke liye.",
"variable": "Programming mein ek named storage location jo data hold karta hai. Iska value change ho sakta hai during program execution.",
"function": "Ek reusable block of code jo ek specific task perform karta hai. Isko baar baar call kar sakte ho.",
"loop": "Ek programming construct jo ek block of code ko repeatedly execute karta hai jab tak condition true hai.",
"agent": "AI mein ek autonomous system jo perceive karta hai environment ko, decisions leta hai, aur actions perform karta hai goals achieve karne ke liye.",
"prompt": "AI model ko diya gaya input text jo usse batata hai ki kya karna hai ya kya generate karna hai.",
"token": "Text ka smallest unit jo language model process karta hai. Ek word mein 1-3 tokens ho sakte hain.",
"inference": "Jab ek trained AI model naye data pe predictions ya outputs generate karta hai.",
"embedding": "Text ko numbers (vectors) mein convert karna taaki computer usse mathematically process kar sake.",
}
word_lower = word.lower().strip()
if word_lower in dictionary:
return f"'{word}' ka meaning: {dictionary[word_lower]}"
else:
return f"Sorry, '{word}' ka meaning mere paas nahi hai. Main sirf kuch common tech/programming words jaanta hun."
# --- Tool Definitions (JSON Schema for Groq API) ---
tool_definitions = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate a mathematical expression. Use this when the user asks to calculate something, do math, or solve a numerical problem.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate, e.g. '25 * 47' or '(10 + 5) * 3'",
}
},
"required": ["expression"],
},
},
},
{
"type": "function",
"function": {
"name": "get_meaning",
"description": "Get the meaning/definition of an English word. Use this when the user asks what a word means or wants a definition.",
"parameters": {
"type": "object",
"properties": {
"word": {
"type": "string",
"description": "The English word to look up the meaning of",
}
},
"required": ["word"],
},
},
},
]
Your tools are built and described. The AI now has a menu card showing what it can do. Next up, you will wire these tools into the agent loop so the AI can actually call them when it needs to solve math or look up a word.
Build the Agent Loop
Ab tak tumhare paas tools ready hain aur AI tumse Hinglish mein baat kar raha hai. Lekin abhi AI ko pata nahi ki tools exist karte hain.
Is step mein hum agent loop banayenge. Ye woh core pattern hai jahan AI sochta hai (reasoning), decide karta hai konsa tool use karna hai, tool execute karta hai, aur phir final answer deta hai.
In this step, get ready to:
- Connect your tools to the agent.
- Build the agent loop that sends messages, checks for tool calls, executes tools, and gets the final response.
- Test the agent with math and dictionary questions.
Connect tools.py to agent.py
Right now, agent.py has no idea that tools.py exists. We need to import our tool functions and their definitions so the agent can use them.
- In agent.py, find this line at the top:
from groq import Groq
- Add this new import line directly below it:
from tools import calculate, get_meaning, tool_definitions
- Now scroll to the bottom of agent.py and delete the entire if __name__ == "__main__": block (the test code from the previous step).
Why delete the old test block?
We're about to replace it with the proper agent loop that knows how to use tools. The old block was just a simple chat test.
Build the agent loop with tool execution
The agent loop is the heart of every AI agent. It follows a simple cycle: send the user's message to the AI along with available tools, check if the AI wants to call a tool, execute that tool, then send the result back to get the final answer.
- In agent.py, add the following code below the SYSTEM_PROMPT variable (where the old test block used to be):
# --- Available Functions Map ---
available_functions = {
"calculate": calculate,
"get_meaning": get_meaning,
}
def run_agent(conversation_history: list) -> str:
"""Run one turn of the agent loop with tool calling."""
# Step 1: Send messages to Groq API with tools
response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
tools=tool_definitions,
tool_choice="auto",
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
# Step 2: Check if AI wants to use a tool
if tool_calls:
# Add AI's response (with tool call request) to history
conversation_history.append(response_message)
# Step 3: Execute each tool call
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
# Call the actual function
function_response = function_to_call(**function_args)
print(f" 🔧 Tool used: {function_name}({function_args})")
print(f" 📋 Result: {function_response}")
# Add tool result to conversation
conversation_history.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
# Step 4: Get final response from AI after seeing tool results
final_response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
)
assistant_message = final_response.choices[0].message.content
else:
# No tool needed - direct response
assistant_message = response_message.content
return assistant_message
What does this code do?
The available_functions dictionary maps tool names (strings) to actual Python functions. When AI says "call calculate", this map tells our code which function to actually run.
The run_agent function is the full agent loop. It sends the conversation to Groq with tool_choice="auto" so the AI can decide on its own whether to use a tool.
If tool_calls exist in the response, the code parses the arguments with json.loads, calls the real function, adds the result back as a "tool" role message, then makes a second API call so AI can write a natural language answer using that result.
- Save agent.py.
Seeing a red underline on the imports?
Make sure tools.py is saved and is in the same folder as agent.py. Both files must be inside your study-buddy-agent folder.
help me fix the import error in agent.py
Test the agent with tools
Ab dekhte hain ki AI actually tools use karta hai ya nahi. Hum ek math question bhejenge aur observe karenge ki agent calculator tool call karta hai.
- At the bottom of agent.py, add this test block:
if __name__ == "__main__":
history = [{"role": "system", "content": SYSTEM_PROMPT}]
history.append({"role": "user", "content": "What is 25 * 47?"})
print(run_agent(history))
What does this test do?
This creates a conversation history starting with the system prompt, adds a math question, and passes it to run_agent. The AI should recognize that this needs the calculate tool and call it automatically.
- Save agent.py and run it with this command:
python agent.py
- You should see output showing the tool being called, the result, and then a final Hinglish answer from the AI explaining that 25 * 47 = 1175.
This is reasoning in action
Notice what happened: the AI received a math question, decided on its own to use the calculator tool (not the dictionary), executed it, got the result, and then wrote a friendly answer. You did not tell it which tool to pick.
This is exactly how production AI agents work. The model reads the tool descriptions and reasons about which one fits the user's intent.
- Now test the dictionary tool by changing the user message in your test block to "What does algorithm mean?" and running python agent.py again.
- This time you should see the get_meaning tool being called instead of calculate.
- Once you've tested both, change the message back to "What is 25 * 47?" and save.
Getting an error when running?
Make sure your virtual environment is still active (you should see (venv) in your terminal prompt). If not, run venv\Scripts\activate again.
Also confirm that your GROQ_API_KEY environment variable is set in this terminal session.
help me debug my agent.py errors
✔️ Awesome, I've got everything!
Great. Double check that you've saved agent.py with the test message set back to "What is 25 * 47?".
ⓧ I'd like to double check the full code
Here's the complete agent.py file at this point:
import os
import json
from groq import Groq
from tools import calculate, get_meaning, tool_definitions
# --- Groq Client Setup ---
client = Groq(
api_key=os.environ.get("GROQ_API_KEY"),
)
MODEL = "llama-3.3-70b-versatile"
# --- System Prompt (Prompt Engineering) ---
SYSTEM_PROMPT = """You are "Study Buddy" - ek smart AI assistant jo students ki help karta hai.
Rules:
- Hinglish mein baat karo (Hindi + English mix) - jaise Indian students normally baat karte hain
- Jab math question aaye, ALWAYS use the calculate tool
- Jab word meaning poocha jaaye, ALWAYS use the get_meaning tool
- Friendly aur encouraging tone rakho
- Short aur clear answers do
- Jab tool use karo, result ko natural language mein explain karo
"""
# --- Available Functions Map ---
available_functions = {
"calculate": calculate,
"get_meaning": get_meaning,
}
def run_agent(conversation_history: list) -> str:
"""Run one turn of the agent loop with tool calling."""
# Step 1: Send messages to Groq API with tools
response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
tools=tool_definitions,
tool_choice="auto",
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
# Step 2: Check if AI wants to use a tool
if tool_calls:
# Add AI's response (with tool call request) to history
conversation_history.append(response_message)
# Step 3: Execute each tool call
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
# Call the actual function
function_response = function_to_call(**function_args)
print(f" 🔧 Tool used: {function_name}({function_args})")
print(f" 📋 Result: {function_response}")
# Add tool result to conversation
conversation_history.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
# Step 4: Get final response from AI after seeing tool results
final_response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
)
assistant_message = final_response.choices[0].message.content
else:
# No tool needed - direct response
assistant_message = response_message.content
return assistant_message
if __name__ == "__main__":
history = [{"role": "system", "content": SYSTEM_PROMPT}]
history.append({"role": "user", "content": "What is 25 * 47?"})
print(run_agent(history))
Tumhara agent ab tools use karke intelligent answers de raha hai. Next up, we'll give it memory so it remembers your entire conversation.
Add Memory - Give the Agent a Brain
Tumhara agent ab tools use karke smart answers de sakta hai. Lekin abhi ek badi problem hai. Agar tum agent ko apna naam batao aur phir kuch aur poocho, agent tumhara naam bhool jayega.
Real AI assistants (jaise ChatGPT) purani baatein yaad rakhte hain kyunki wo conversation memory use karte hain. In this step, we'll give our agent a brain that remembers the entire conversation.
In this step, get ready to:
- Implement conversation memory that stores all messages.
- Build an interactive chat loop so you can talk to your agent continuously.
- Test that the agent remembers your name across multiple turns.
Understand how conversation memory works
Right now, your agent handles one message at a time with no memory of what came before. Every API call starts fresh.
What is conversation memory?
Conversation memory is a list that stores every message in the chat. User messages, AI responses, and tool results all go into this list.
Each time you send a new message to the API, you send the ENTIRE history. This is how the AI "remembers" what was said before. Without this list, each API call would be like talking to someone with amnesia.
- In agent.py, scroll to the bottom of the file and find this block:
if __name__ == "__main__":
history = [{"role": "system", "content": SYSTEM_PROMPT}]
history.append({"role": "user", "content": "What is 25 * 47?"})
print(run_agent(history))
- Delete this entire block. You'll replace it with the full interactive main() function next.
Build the interactive chat loop with memory
Now you'll write a main() function that keeps a running list of all messages and loops continuously until the user types "quit".
- Where you deleted the old code, paste the following main() function and entry point:
def main():
"""Main chat loop with memory."""
print("=" * 50)
print("🤖 Study Buddy Agent - Tumhara AI Study Partner!")
print("=" * 50)
print("Mujhse kuch bhi poocho - math, word meanings, ya kuch bhi!")
print("Type 'quit' to exit.\n")
# Conversation memory - stores all messages
conversation_history = [
{"role": "system", "content": SYSTEM_PROMPT}
]
while True:
# Get user input
user_input = input("👤 You: ").strip()
if user_input.lower() in ["quit", "exit", "bye"]:
print("\n🤖 Study Buddy: Bye bye! Happy learning! 🎉")
break
if not user_input:
continue
# Add user message to memory
conversation_history.append({"role": "user", "content": user_input})
# Run agent
print("\n🤖 Study Buddy: ", end="")
response = run_agent(conversation_history)
print(response)
# Add AI response to memory
conversation_history.append({"role": "assistant", "content": response})
print()
if __name__ == "__main__":
main()
What does this code do?
- conversation_history starts with just the system prompt. Every new message (user + assistant) gets appended to this list.
- while True creates an infinite loop that only breaks when the user types "quit", "exit", or "bye".
- After each user message, we append it to conversation_history BEFORE calling run_agent(). This means the API always sees the full conversation.
- After getting the AI's response, we also append it to conversation_history. This way the AI remembers what it said too.
Why does this give the agent memory?
LLMs have no built-in memory between API calls. Every call is independent. The trick is to send the ENTIRE conversation history with every new message.
If you told the agent your name in message 1, that message is still in conversation_history when you ask your question in message 5. The AI reads the full list and "remembers" everything. Production AI systems like ChatGPT work the same way.
- Save agent.py.
✔️ Awesome, I've got everything!
Great. Double check you've saved your file before moving on.
ⓧ I'd like to double check the full code
import os
import json
from groq import Groq
from tools import calculate, get_meaning, tool_definitions
# --- Groq Client Setup ---
client = Groq(
api_key=os.environ.get("GROQ_API_KEY"),
)
MODEL = "llama-3.3-70b-versatile"
# --- System Prompt (Prompt Engineering) ---
SYSTEM_PROMPT = """You are "Study Buddy" - ek smart AI assistant jo students ki help karta hai.
Rules:
- Hinglish mein baat karo (Hindi + English mix) - jaise Indian students normally baat karte hain
- Jab math question aaye, ALWAYS use the calculate tool
- Jab word meaning poocha jaaye, ALWAYS use the get_meaning tool
- Friendly aur encouraging tone rakho
- Short aur clear answers do
- Jab tool use karo, result ko natural language mein explain karo
"""
# --- Available Functions Map ---
available_functions = {
"calculate": calculate,
"get_meaning": get_meaning,
}
def run_agent(conversation_history: list) -> str:
"""Run one turn of the agent loop with tool calling."""
# Step 1: Send messages to Groq API with tools
response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
tools=tool_definitions,
tool_choice="auto",
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
# Step 2: Check if AI wants to use a tool
if tool_calls:
# Add AI's response (with tool call request) to history
conversation_history.append(response_message)
# Step 3: Execute each tool call
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
# Call the actual function
function_response = function_to_call(**function_args)
print(f" 🔧 Tool used: {function_name}({function_args})")
print(f" 📋 Result: {function_response}")
# Add tool result to conversation
conversation_history.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
# Step 4: Get final response from AI after seeing tool results
final_response = client.chat.completions.create(
model=MODEL,
messages=conversation_history,
)
assistant_message = final_response.choices[0].message.content
else:
# No tool needed - direct response
assistant_message = response_message.content
return assistant_message
def main():
"""Main chat loop with memory."""
print("=" * 50)
print("🤖 Study Buddy Agent - Tumhara AI Study Partner!")
print("=" * 50)
print("Mujhse kuch bhi poocho - math, word meanings, ya kuch bhi!")
print("Type 'quit' to exit.\n")
# Conversation memory - stores all messages
conversation_history = [
{"role": "system", "content": SYSTEM_PROMPT}
]
while True:
# Get user input
user_input = input("👤 You: ").strip()
if user_input.lower() in ["quit", "exit", "bye"]:
print("\n🤖 Study Buddy: Bye bye! Happy learning! 🎉")
break
if not user_input:
continue
# Add user message to memory
conversation_history.append({"role": "user", "content": user_input})
# Run agent
print("\n🤖 Study Buddy: ", end="")
response = run_agent(conversation_history)
print(response)
# Add AI response to memory
conversation_history.append({"role": "assistant", "content": response})
print()
if __name__ == "__main__":
main()
Seeing an indentation error?
Make sure the entire while True block is indented inside the main() function. Python uses indentation to determine what belongs inside a function.
Also check that if __name__ == "__main__": is NOT indented. It should be at the very left edge of the file, outside any function.
Help me fix my indentation error in agent.py
Test your agent's memory
Time to prove that your agent actually remembers things. You'll have a multi-turn conversation and check if it recalls information from earlier messages.
- Make sure your GROQ_API_KEY environment variable is set in your terminal. Run your agent by entering this command:
python agent.py
You should see the welcome banner with "Study Buddy Agent - Tumhara AI Study Partner!" and a prompt waiting for your input.
- Type this as your first message and press **Enter**:
Mera naam Rahul hai
- The agent should respond with something friendly acknowledging your name. Now ask something unrelated:
What is 100 / 4?
- You should see the calculator tool fire and the agent respond with the answer. Now test memory by asking:
Mera naam kya hai?
The agent should correctly recall "Rahul" even though you asked a math question in between. This proves conversation memory is working.
- Type quit to exit the agent when you're done testing.
Why does this work?
When you asked "Mera naam kya hai?", the API received ALL previous messages: your name introduction, the math question, the tool results, and the AI's responses. The LLM reads this full history and finds your name from earlier in the conversation.
This is exactly how production AI systems maintain context. The memory is just a growing list of messages passed to the API on every turn.
Agent not remembering your name?
Check that you have both append lines in your loop. One appends the user message BEFORE calling run_agent(), and the other appends the assistant response AFTER. If either is missing, the history is incomplete.
Also make sure conversation_history is defined OUTSIDE the while True loop. If it's inside the loop, it resets every turn.
Help me debug why my agent doesn't remember previous messages
Your agent is now complete. It can think, use tools, and remember conversations. Next up is the Secret Mission where you'll give it the power to search Wikipedia for real information.
Secret mission
Wikipedia Search Tool Add Karo
Tumhara agent abhi sirf calculator aur dictionary use kar sakta hai. Agar agent ko internet se real information chahiye toh? Is secret mission mein tum ek Wikipedia Search tool banao ge jo agent ko duniya bhar ki knowledge de dega.
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. This project runs entirely locally with a free-tier API, so there are no ongoing costs.
Resources you used:
- study-buddy-agent project folder (contains agent.py, tools.py, .env, and venv virtual environment).
- Groq API key (stored in .env and on the Groq Console).
Keep everything running
No action needed. Choose this if you're still actively building or plan to add more tools to your agent.
- Your study-buddy-agent folder stays on your Desktop with all code intact.
- Your Groq API key remains active. The free tier has no charges, so leaving it active costs nothing.
- Your Python virtual environment (venv) stays inside the project folder. Reactivate it any time with venv\Scripts\activate to continue working.
Pause - I'll come back to this later
Shut down running processes to free up memory. Your files and API key stay ready for when you return.
- Close the terminal running your agent (type quit or press Ctrl+C).
- Deactivate your virtual environment by running:
- Your project files and Groq API key remain untouched for next time.
deactivate
When you return, reactivate the virtual environment and run your agent again.
Delete - I don't want to use this again
Remove all project resources and revoke your API key to start fresh.
- Close the terminal running your agent (type quit or press Ctrl+C).
- Deactivate your virtual environment by running:
deactivate
- Delete the entire project folder. On macOS/Linux, run:
cd ~/Desktop
rm -rf study-buddy-agent
- On Windows (PowerShell), run:
cd ~/Desktop
Remove-Item -Recurse -Force study-buddy-agent
- Revoke your Groq API key. Go to https://console.groq.com/keys, find the API key you created for this project, and delete it from the list.
That's a Wrap!
That's a Wrap!
Badhai ho! Tum ne apna pehla AI Agent bana liya jo tools use karke intelligent answers deta hai. Ye exact same pattern hai jo companies production mein use karti hain.
You've learned how to:
- Implement Tool Use (Function Calling) with the Groq API, where the AI autonomously decides which tool to call based on the user's question.
- Build a complete Agent Loop that follows the think-decide-act pattern: send available tools to the LLM, receive tool call requests, execute functions locally, and return results for a final response.
- Add Conversation Memory so the agent remembers context from earlier in the chat, just like production AI systems.
- Extend your agent with a Wikipedia Search tool that fetches real information from the internet, giving your Study Buddy access to live knowledge.
Ready to quiz yourself?