Home/Blog/Building Your First AI Agent: A Step-by-Step Tutorial

Building Your First AI Agent: A Step-by-Step Tutorial

Building Your First AI Agent: A Step-by-Step Tutorial

AI agents are the hottest topic in tech right now — and for good reason. An AI agent is software that can autonomously plan, execute, and learn from tasks. Unlike a chatbot that just responds to questions, an agent takes action.

In this tutorial, we'll build a simple but functional AI agent from scratch.

What You'll Build

By the end of this tutorial, you'll have an agent that can:

Prerequisites

Step 1: The Agent Loop

Every AI agent follows the same core loop:

async function agentLoop(task) {
  const memory = loadMemory();
  const context = { task, memory, steps: [] };

  while (!context.complete) {
    // 1. Think: What should I do next?
    const plan = await think(context);

    // 2. Act: Execute the planned action
    const result = await act(plan);

    // 3. Observe: What happened?
    context.steps.push({ plan, result });

    // 4. Decide: Am I done?
    context.complete = await evaluate(context);
  }

  saveMemory(context);
  return context.steps;
}

This Think-Act-Observe loop is the foundation of every agent, from simple scripts to complex autonomous systems.

Step 2: The Think Function

The "think" step sends the current context to an LLM and asks it to decide the next action:

async function think(context) {
  const prompt = \`You are an AI agent. Your task: ${context.task}

Steps completed so far:
${context.steps.map((s, i) => \`${i+1}. ${s.plan.action}: ${s.result}\`).join('\n')}

What should I do next? Respond with a JSON action:
{"action": "search|write|read|complete", "params": {...}}\`;

  const response = await callLLM(prompt);
  return JSON.parse(response);
}

Step 3: The Act Function

The "act" step executes whatever the LLM decided:

async function act(plan) {
  switch (plan.action) {
    case 'search':
      return await webSearch(plan.params.query);
    case 'write':
      return await writeFile(plan.params.path, plan.params.content);
    case 'read':
      return await readFile(plan.params.path);
    case 'complete':
      return 'Task complete';
    default:
      return 'Unknown action';
  }
}

Step 4: Memory

Agents need memory to work across sessions. The simplest approach is a JSON file:

function loadMemory() {
  try {
    return JSON.parse(fs.readFileSync('memory.json', 'utf8'));
  } catch {
    return { facts: [], completedTasks: [] };
  }
}

function saveMemory(context) {
  const memory = loadMemory();
  memory.completedTasks.push({
    task: context.task,
    steps: context.steps.length,
    timestamp: new Date().toISOString()
  });
  fs.writeFileSync('memory.json', JSON.stringify(memory, null, 2));
}

Step 5: Safety Rails

Never let an agent run without guardrails:

const MAX_STEPS = 20;
const ALLOWED_ACTIONS = ['search', 'write', 'read', 'complete'];

async function safeAgentLoop(task) {
  const context = { task, steps: [], complete: false };

  while (!context.complete && context.steps.length < MAX_STEPS) {
    const plan = await think(context);

    if (!ALLOWED_ACTIONS.includes(plan.action)) {
      context.steps.push({ plan, result: 'BLOCKED: unauthorized action' });
      continue;
    }

    const result = await act(plan);
    context.steps.push({ plan, result });
    context.complete = plan.action === 'complete';
  }

  return context;
}

Key Takeaways

  1. Start simple — The think-act-observe loop is all you need
  2. Add tools gradually — Start with 2-3 tools, expand as needed
  3. Memory matters — Even basic JSON memory makes a huge difference
  4. Safety first — Always limit steps, validate actions, log everything
  5. Iterate — Your agent will get better as you refine its prompts and tools

What's Next?

Once you have a basic agent working:

The AI agent ecosystem is evolving fast. The skills you build now will be incredibly valuable. Start building, start experimenting, and see what your agent can do.

#tutorial#ai agent#development#automation#beginner

Try AuditX Free

Scan your website for SEO issues and AI search readiness in under 2 minutes.

Start Free Scan

Stay ahead of the curve

Get weekly insights on AI, SEO, and automation delivered to your inbox.