How to Build AI Agents: A Beginner's Guide


Turn your chatbot into an action-taking assistant in 30 minutes
Ever wished your AI could actually do things instead of just talking about them?
Regular AI: "I can't check your email for you."
AI Agent: Actually checks your email and summarizes it
The difference? Function calling - teaching your AI what tools it can use and when to use them.
What You'll Learn
By the end of this guide, you'll understand:
How AI agents actually work (it's simpler than you think)
How to give your AI "superpowers" with functions
How to build your first working agent in under 50 lines of code
The Secret: It's Just Smart Function Calling
Here's the magic behind AI agents:
Your Question → AI Thinks → AI Says "I need to use tool X" → Tool Executes → AI Responds
Example:
You: "What's the weather like?"
AI: "I need to call the weather function with your location"
Function: Calls weather API
AI: "It's 72°F and sunny!"
Step 1: Define Your Tools
First, you tell the AI what tools are available. Here's how:
const tools = [
{
name: "get_weather",
description: "Get current weather for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City name, e.g. 'New York'"
}
},
required: ["location"]
}
},
{
name: "send_email",
description: "Send an email to someone",
parameters: {
type: "object",
properties: {
to: {
type: "string",
description: "Email address"
},
subject: {
type: "string",
description: "Email subject"
},
message: {
type: "string",
description: "Email content"
}
},
required: ["to", "subject", "message"]
}
}
];
Think of this as giving your AI a toolbox with labels on each tool.
Step 2: Send Everything to the AI
Here's how you actually talk to the AI with your tools:
async function askAI(userQuestion) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${YOUR_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: "gpt-4",
messages: [
{
role: "user",
content: userQuestion
}
],
tools: tools, // ← This is where the magic happens!
tool_choice: "auto"
})
});
const data = await response.json();
return data.choices[0].message;
}
That's it! The AI now knows it can use your tools.
Step 3: Handle the AI's Response
The AI will either give you a normal response OR tell you to use a tool:
async function handleAIResponse(aiResponse) {
// Check if AI wants to use a tool
if (aiResponse.tool_calls) {
console.log("AI wants to use a tool!");
// Execute the tool the AI requested
for (const toolCall of aiResponse.tool_calls) {
const toolName = toolCall.function.name;
const toolArgs = JSON.parse(toolCall.function.arguments);
console.log(`AI wants to call: ${toolName}`);
console.log(`With arguments:`, toolArgs);
// Actually run the tool
const result = await runTool(toolName, toolArgs);
console.log(`Tool result:`, result);
}
} else {
// Normal response
console.log("AI response:", aiResponse.content);
}
}
Step 4: Actually Run the Tools
Now you need to actually implement what happens when the AI calls each tool:
async function runTool(toolName, args) {
switch (toolName) {
case 'get_weather':
// Call a weather API
const weather = await fetch(`https://api.weather.com/current?city=${args.location}`);
return `The weather in ${args.location} is sunny and 72°F`;
case 'send_email':
// Send an actual email
console.log(`Sending email to ${args.to}: ${args.subject}`);
return `Email sent to ${args.to}`;
default:
return `Unknown tool: ${toolName}`;
}
}
Complete Working Example
Here's everything put together in a simple, working agent:
class SimpleAI {
constructor(apiKey) {
this.apiKey = apiKey;
this.tools = [
{
name: "calculate",
description: "Do math calculations",
parameters: {
type: "object",
properties: {
expression: {
type: "string",
description: "Math expression like '2 + 2'"
}
},
required: ["expression"]
}
},
{
name: "get_time",
description: "Get current time",
parameters: {
type: "object",
properties: {},
required: []
}
}
];
}
async ask(question) {
// 1. Send question + tools to AI
const aiResponse = await this.callAI(question);
// 2. Check if AI wants to use tools
if (aiResponse.tool_calls) {
// 3. Run the tools
for (const toolCall of aiResponse.tool_calls) {
const result = await this.runTool(toolCall);
console.log(`Tool result: ${result}`);
}
// 4. Get final answer (you'd normally send results back to AI)
return "Task completed!";
}
// 5. Return normal response
return aiResponse.content;
}
async callAI(message) {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: "gpt-4",
messages: [{ role: "user", content: message }],
tools: this.tools,
tool_choice: "auto"
})
});
const data = await response.json();
return data.choices[0].message;
}
async runTool(toolCall) {
const name = toolCall.function.name;
const args = JSON.parse(toolCall.function.arguments);
switch (name) {
case 'calculate':
return eval(args.expression); // Don't use eval in production!
case 'get_time':
return new Date().toLocaleTimeString();
default:
return `Unknown tool: ${name}`;
}
}
}
// Usage
const ai = new SimpleAI('your-openai-api-key');
ai.ask("What's 15 + 27?"); // AI will use calculate tool
ai.ask("What time is it?"); // AI will use get_time tool
How It Actually Works
When you ask "What's 15 + 27?":
AI receives: Your question + list of available tools
AI thinks: "I need to calculate something, I should use the calculate tool"
AI responds: "Use calculate tool with expression '15 + 27'"
Your code: Runs the calculation
Result: Returns "42"
The AI never actually runs the code - it just tells you what to run!
Try It Yourself
Start with this simple example:
// 1. Define one simple tool
const tools = [{
name: "flip_coin",
description: "Flip a coin and return heads or tails",
parameters: { type: "object", properties: {}, required: [] }
}];
// 2. Ask AI a question
const question = "Can you flip a coin for me?";
// 3. AI will respond with tool_calls asking you to run flip_coin
// 4. You run: Math.random() > 0.5 ? "heads" : "tails"
// 5. AI gets the result and responds: "The coin landed on heads!"
Common Beginner Mistakes
Mistake 1: Thinking the AI runs the code itself
- Reality: AI only tells you what to run, you execute it
Mistake 2: Making tool descriptions too vague
Bad: "Does stuff with data"
Good: "Calculates the average of a list of numbers"
Mistake 3: Forgetting to handle tool_calls
- Fix: Always check if
aiResponse.tool_calls
exists
What's Next?
Once you understand this basic pattern, you can:
Add more tools: Weather, email, calendar, database queries
Chain tool calls: Let AI use multiple tools in sequence
Add memory: Keep conversation history
Handle errors: What happens if a tool fails?
The core concept stays the same - you're just giving your AI more tools to work with!
Real-World Tools You Can Add
Here are some practical tools to get you started:
// Google Search
{
name: "search_google",
description: "Search Google for information",
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Search terms" }
},
required: ["query"]
}
}
// Read File
{
name: "read_file",
description: "Read contents of a file",
parameters: {
type: "object",
properties: {
filename: { type: "string", description: "Path to file" }
},
required: ["filename"]
}
}
// Save Note
{
name: "save_note",
description: "Save a note to file",
parameters: {
type: "object",
properties: {
content: { type: "string", description: "Note content" },
title: { type: "string", description: "Note title" }
},
required: ["content", "title"]
}
}
The Big Picture
AI agents aren't magic - they're just:
Smart function calling (AI decides which tool to use)
Good tool descriptions (so AI knows what each tool does)
Simple execution logic (you run what the AI requests)
Start simple, add one tool at a time, and before you know it, you'll have built a powerful AI assistant!
Ready to build your first agent? Copy the SimpleAI example above and start experimenting!
Questions? The key insight is that AI agents are just chatbots with the ability to use tools. Master this concept, and you've mastered AI agents.
Subscribe to my newsletter
Read articles from Aditya Srivastava directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
