AI Agents Explained Without the Hype
Build a minimal AI agent with tool calling, permissions, and observability. Learn by running code, not reading theory.
Before you start
You have heard agents are the future. Vendors promise autonomous software that books flights and writes code. But when you open the docs, you find abstractions on top of abstractions, and the examples stop working the moment you change a model name. This article strips that away. You will build a minimal agent from first principles, using only the OpenAI SDK, Node.js, and a few environment variables.
The goal is not to ship a production framework. It is to understand the moving parts: the loop, the tool schema, the permission boundary, and the observability trail. Once you see those, every agent framework on the market becomes a thin wrapper over the same pattern.
You need Node.js 18 or newer, an OpenAI API key, and about twenty minutes. No GPU, no vector database, no Kubernetes. We will use the chat completions API with function calling, which is now the standard way to give a model tools.
- Node.js 18+ installed
- An OpenAI API key with a small credit balance
- A terminal and a text editor
- Basic familiarity with async/await in JavaScript
Step 1: Set up the project
Create a new directory and initialize a Node project. We will keep dependencies to a minimum: the OpenAI SDK and dotenv for configuration. Later we add a simple HTTP server for the permission prompt, but that is optional.
mkdir minimal-agent
cd minimal-agent
npm init -y
npm install openai dotenv
mkdir src- Use CommonJS or ESM; the code below uses ESM, so add "type": "module" to package.json
- Store your API key in a .env file, never commit it
Step 2: Define the tool schema
An agent is only as useful as its tools. In the OpenAI API, tools are declared as JSON Schema objects. The model sees these schemas and decides when to call them. We will create two tools: one to get the current time, and one to run a shell command. The second is dangerous, so we will add a permission gate later.
Create a file src/tools.js that exports an array of tool definitions. Each tool has a type, a function, and a description. The description matters: the model uses it to decide which tool fits the user request.
// src/tools.js
export const tools = [
{
type: 'function',
function: {
name: 'get_current_time',
description: 'Get the current date and time in ISO format',
parameters: {
type: 'object',
properties: {},
required: []
}
}
},
{
type: 'function',
function: {
name: 'run_shell_command',
description: 'Run a shell command and return its stdout',
parameters: {
type: 'object',
properties: {
command: {
type: 'string',
description: 'The command to execute'
}
},
required: ['command']
}
}
}
];Step 3: Implement the agent loop
The core loop is simple: send the conversation to the model, check if it wants to call a tool, execute the tool, append the result, and repeat. You stop when the model returns a plain message without tool calls. This is the same pattern every agent framework uses, just with more abstractions.
Create src/agent.js. The agent function takes a user prompt and returns the final answer. We will use the OpenAI SDK with the gpt-4o-mini model, which is cheap and fast enough for experiments.
// src/agent.js
import OpenAI from 'openai';
import { tools } from './tools.js';
import { executeTool } from './executor.js';
const client = new OpenAI();
export async function runAgent(userPrompt) {
const messages = [{ role: 'user', content: userPrompt }];
for (let i = 0; i < 5; i++) {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages,
tools,
tool_choice: 'auto',
});
const message = response.choices[0].message;
messages.push(message);
if (message.tool_calls) {
for (const call of message.tool_calls) {
const result = await executeTool(call.function.name, call.function.arguments);
messages.push({
role: 'tool',
tool_call_id: call.id,
content: JSON.stringify(result),
});
}
} else {
return message.content;
}
}
throw new Error('Agent exceeded max iterations');
}Step 4: Execute tools safely
Now we need the executor. This is where you add guardrails. The run_shell_command tool can execute anything, so we will add a permission check that prints the command and asks for confirmation. In a production system you would use an allowlist or a separate sandbox, but for a local demo this interactive gate is enough.
Create src/executor.js. It parses the arguments, checks the tool name, and runs the appropriate function. For the shell command, we use child_process.exec with a timeout.
// src/executor.js
import { exec } from 'child_process';
import { promisify } from 'util';
import readline from 'readline';
const execAsync = promisify(exec);
export async function executeTool(name, argsString) {
const args = JSON.parse(argsString);
if (name === 'get_current_time') {
return { iso: new Date().toISOString() };
}
if (name === 'run_shell_command') {
const ok = await confirmCommand(args.command);
if (!ok) return { error: 'Permission denied by user' };
try {
const { stdout } = await execAsync(args.command, { timeout: 10000 });
return { stdout };
} catch (err) {
return { error: err.message };
}
}
throw new Error(`Unknown tool: ${name}`);
}
function confirmCommand(command) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(`Allow command? ${command} (y/n) `, (answer) => {
rl.close();
resolve(answer.toLowerCase() === 'y');
});
});
}Step 5: Wire it together and run
Create src/index.js that loads the environment, reads a prompt from the command line, and calls runAgent. Then run it with a prompt that asks for the current time and then for a simple shell command like 'echo hello'.
// src/index.js
import 'dotenv/config';
import { runAgent } from './agent.js';
const prompt = process.argv[2];
if (!prompt) {
console.error('Usage: node src/index.js "your prompt"');
process.exit(1);
}
const answer = await runAgent(prompt);
console.log('\nAgent:', answer);- Run with: node src/index.js "What time is it?"
- Then try: node src/index.js "Run echo hello and tell me the output"
- When prompted, type y to allow the command
Verify it worked
If the setup is correct, the first prompt should print the current time. The second prompt should ask for permission and then print the stdout. If you see an error about tools not being supported, check your OpenAI API key and model access.
node src/index.js "What time is it?"
# Agent: The current time is 2025-04-08T14:32:11ZWhat I would do: add observability
A black-box agent is a debugging nightmare. The moment you add more tools, you need to see what the model decided and why. I recommend logging every API call and tool result to a file. This is the minimum viable observability for any agent.
Add a simple logger that appends each request and response to agent.log. You can also print the tool calls to stderr so they appear in your terminal without polluting the final answer.
// Add to agent.js after each API call
import fs from 'fs';
function logEvent(event) {
fs.appendFileSync('agent.log', JSON.stringify(event) + '\n');
}
// Inside the loop, after messages.push(message):
logEvent({ type: 'model', content: message });
// After each tool result:
logEvent({ type: 'tool', name: call.function.name, result });- Log the full message object, including tool_calls
- Log the tool result even if it is an error
- Use a structured format like JSON so you can grep and analyze later
Recommended setup: permission model
The interactive prompt works for a demo, but for any real deployment you need a policy. The simplest policy is an allowlist of commands. Here is a version of executeTool that only allows a few safe commands and rejects everything else.
// src/executor.js (allowlist version)
const ALLOWED_COMMANDS = ['echo', 'date', 'whoami', 'ls'];
export async function executeTool(name, argsString) {
const args = JSON.parse(argsString);
if (name === 'run_shell_command') {
const cmd = args.command.trim().split(/\s+/)[0];
if (!ALLOWED_COMMANDS.includes(cmd)) {
return { error: `Command not allowed: ${cmd}` };
}
// ... run as before, no prompt needed
}
// ... rest
}Troubleshooting
If the model does not call the tool, check the tool descriptions. Vague descriptions lead to the model ignoring them. Be explicit about when to use each tool.
If you get a 400 error about tools, make sure you are using a model that supports tool calling, such as gpt-4o-mini or gpt-4o. Older models like gpt-3.5-turbo may not support the tools parameter with the same syntax.
If the permission prompt hangs, ensure you are running the script in an interactive terminal, not a background process.
If the agent loops forever, the max iterations guard will throw an error. Increase it only if you are sure the tool results are correct.
FAQ
Answers to the questions that come up most often on this topic.
- Q: Do I need a framework like LangChain to build agents? A: No. This minimal loop is the foundation. Frameworks add convenience but also complexity and hidden behavior.
- Q: How do I add memory or context? A: You can append previous interactions to the messages array, but beware of token limits. For long-term memory, use a vector store or summarization.
- Q: What about multi-agent systems? A: They are just multiple loops that pass messages to each other. Start with one agent and one tool, then expand.
- Q: Is function calling the same as tool calling? A: Yes, OpenAI uses the terms interchangeably in their API.
Next action
Create the files above, run the agent, and then extend it with one more tool of your own. A good exercise is a tool that reads a file from disk. Add it to the schema, implement the executor branch, and test it with a prompt like 'Read the contents of src/agent.js'. You will see how the model decides to use it.
Run this command to get started:
node src/index.js "Read the contents of src/agent.js"Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agents for?
- Working developers who need a practical take on ai agents explained without the hype — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published November 13, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.