Back to Blog
Tutorials 8 min read February 22, 2026

Building Your First AI Agent in JavaScript: A Step-by-Step Guide

Forget the hype. This tutorial walks you through building a working AI agent from scratch in under 100 lines of JavaScript — no frameworks required.

DevForge Team

DevForge Team

AI Development Educators

Clean code on a laptop screen showing JavaScript and AI agent implementation

What You'll Build

A working AI agent that can use tools, maintain conversation history, and know when to stop — in under 100 lines of JavaScript. No LangChain. No frameworks. Just the Anthropic SDK and a clear mental model.

Prerequisites

  • Node.js 18+
  • An Anthropic API key
  • Basic JavaScript/async familiarity

Setup

bash
mkdir my-agent && cd my-agent
npm init -y
npm install @anthropic-ai/sdk

Step 1: Define Your Tools

Tools are functions the agent can call. Each tool needs a name, description, and input schema:

javascript
export const tools = [
  {
    name: "calculator",
    description: "Perform arithmetic calculations. Returns the numeric result.",
    input_schema: {
      type: "object",
      properties: {
        expression: {
          type: "string",
          description: "A valid JavaScript arithmetic expression, e.g. '(15 * 847) / 100'"
        }
      },
      required: ["expression"]
    }
  },
  {
    name: "get_date",
    description: "Get today's date and current time in ISO format.",
    input_schema: { type: "object", properties: {} }
  }
];

export function executeTool(name, input) {
  switch (name) {
    case "calculator": {
      try {
        const result = Function('"use strict"; return (' + input.expression + ')')();
        return String(result);
      } catch {
        return "Error: invalid expression";
      }
    }
    case "get_date":
      return new Date().toISOString();
    default:
      return "Unknown tool: " + name;
  }
}

Step 2: Build the Agent Loop

This is the core pattern — the heartbeat of every agent system:

javascript
import Anthropic from "@anthropic-ai/sdk";
import { tools, executeTool } from "./tools.js";

const client = new Anthropic();

async function runAgent(userGoal, options = {}) {
  const { maxIterations = 10, model = "claude-haiku-4-20250514" } = options;
  const messages = [{ role: "user", content: userGoal }];

  for (let i = 0; i < maxIterations; i++) {
    const response = await client.messages.create({
      model,
      max_tokens: 4096,
      tools,
      messages,
      system: "You are a helpful assistant. Use your tools to answer questions accurately."
    });

    messages.push({ role: "assistant", content: response.content });

    const toolUseBlocks = response.content.filter(b => b.type === "tool_use");

    if (response.stop_reason === "end_turn" && toolUseBlocks.length === 0) {
      return response.content.filter(b => b.type === "text").map(b => b.text).join("\n");
    }

    const toolResults = toolUseBlocks.map(block => ({
      type: "tool_result",
      tool_use_id: block.id,
      content: executeTool(block.name, block.input)
    }));

    messages.push({ role: "user", content: toolResults });
  }

  return "Max iterations reached without completing the task.";
}

Understanding What Happened

  1. You sent a goal → agent added it to the message history
  2. LLM reasoned → decided which tools to call
  3. Agent executed tools → called your JavaScript functions
  4. Results fed back → added to message history as tool results
  5. LLM reasoned again → produced final answer with all the information
  6. Loop exited → stop_reason was "end_turn" with no tool calls

This is the complete agent loop. Every framework (LangChain, CrewAI, Vercel AI SDK, OpenAI Agents SDK) is a wrapper around exactly this pattern.

The Agentic AI Developer Certification covers all extensions of this pattern: MCP integration, multi-agent orchestration, memory systems, and production security.

#AI Agents#JavaScript#Tutorial#Beginner#Anthropic#Claude