Written by: ekwoster.dev on Wed Aug 27

🧠 Building Autonomous AI Agents with Node.js: Your First Digital Worker in 100 Lines of Code

🧠 Building Autonomous AI Agents with Node.js: Your First Digital Worker in 100 Lines of Code

Cover image for 🧠 Building Autonomous AI Agents with Node.js: Your First Digital Worker in 100 Lines of Code

🧠 Building Autonomous AI Agents with Node.js: Your First Digital Worker in 100 Lines of Code

What if you could build a mini Jarvis to monitor your emails, collect contact info from websites, book your meetings, and even reply to clients—all within a single script using tools you already know?

Welcome to your crash course in building AI agents with Node.js.


Artificial Intelligence is no longer just a buzzword. With the rise of Large Language Models (LLMs), autonomous AI agents—bots that perceive, reason, and act on your behalf—are now within reach for every developer, even YOU.

In this article, we go beyond chatbot toys.

You're going to build a basic autonomous agent using:

  • 🧠 OpenAI's GPT for reasoning
  • 🌐 Puppeteer for web automation
  • 📥 Node-fetch for API calls
  • 🗂️ Simple JSON-based memory

All in under 100 lines of JavaScript.


🚀 What Are AI Agents (Really)?

AI agents aren't just LLMs wrapped in a prompt. They're systems that:

  1. Perceive their environment (via sensors or APIs)
  2. Reason about the task (LLMs)
  3. Act in the environment (via tools like web automation, API calls, or databases)
  4. Remember previous states or tasks

You can think of them as digital interns—ones that can read, type, summarize, and make decisions.


🧱 What We'll Build

A digital research assistant that:

  1. Takes a topic (e.g., "best JavaScript frameworks for startups")
  2. Uses GPT to generate search queries
  3. Visits pages via Puppeteer
  4. Summarizes key points found
  5. Saves info to a local memory file

Let’s dive in.


⚙️ Setup

1. Prerequisites

  • Node.js >= 18
  • OpenAI API key
mkdir ai-agent-js && cd ai-agent-js
npm init -y
npm install openai puppeteer node-fetch

Create a .env file:

OPENAI_API_KEY=your-api-key-here

2. Basic Agent Structure

Create agent.js

import fetch from 'node-fetch';
import { Configuration, OpenAIApi } from 'openai';
import puppeteer from 'puppeteer';
import fs from 'fs';
import dotenv from 'dotenv';

dotenv.config();

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY
});
const openai = new OpenAIApi(configuration);

const MEMORY_PATH = './memory.json';
if (!fs.existsSync(MEMORY_PATH)) fs.writeFileSync(MEMORY_PATH, '[]');

async function askLLM(prompt) {
  const res = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: prompt }]
  });

  return res.data.choices[0].message.content;
}

async function searchAndScrape(topic) {
  const query = await askLLM(`Generate a Google search query to research: ${topic}`);
  console.log('Search Query:', query);

  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto(`https://www.google.com/search?q=${encodeURIComponent(query)}`);

  const links = await page.evaluate(() =>
    Array.from(document.querySelectorAll('a')).map(anchor => anchor.href).filter(h => h.startsWith('http'))
  );

  const usefulLinks = links.slice(0, 3);

  const summaries = [];
  for (const url of usefulLinks) {
    try {
      await page.goto(url);
      const text = await page.evaluate(() => document.body.innerText);
      const summary = await askLLM(`Summarize the following:

${text.slice(0, 3000)}`);
      summaries.push({ url, summary });
    } catch (err) {
      summaries.push({ url, summary: 'Failed to scrape.' });
    }
  }

  await browser.close();
  return summaries;
}

async function saveToMemory(topic, data) {
  const memory = JSON.parse(fs.readFileSync(MEMORY_PATH));
  memory.push({ topic, data, date: new Date().toISOString() });
  fs.writeFileSync(MEMORY_PATH, JSON.stringify(memory, null, 2));
}

(async () => {
  const topic = process.argv[2] || 'Next-gen JavaScript frameworks';
  const results = await searchAndScrape(topic);
  console.log(results);
  await saveToMemory(topic, results);
})();

⚡️ Run the Agent

node agent.js "Top React alternatives in 2024"

Sample Output:

[
  {
    "url": "https://example.com/some-article",
    "summary": "SolidJS is gaining popularity due to its fine-grained reactivity and zero-cost abstraction. It's considered a strong replacement for React in high-performance UI apps."
  },
  ...
]

This is your first autonomous AI agent. It thinks, browses, reads, and writes—all automated.


🧠 Next Level Ideas

Want to expand? Try:

  • Adding memory scoring (relevance over time)
  • Using vector embeddings for semantic recall
  • Connecting to a Notion DB or Airtable
  • Scheduling the agent to run daily

🧙‍♂️ Final Thoughts

We’re not just building chatbots anymore. With just Node.js and a few libraries, we stepped into the world of digital workers—tools that don’t just reply but act.

LLMs are not the product. The agent is.

This is your entry point to AI automation that delivers real productivity gains.

So... what task will your next agent automate?


💬 Let's Talk

Drop your questions, ideas, or tell me what your agent does in the comments. Share and star if you'd like a full framework for building smart agents.


Happy Automating 🤖✨

🚀 If you're excited about building intelligent apps or research automation, we offer tailored R&D services like this.