Background image representing the theme of this page: Building an autonomous AI loop.

Build an Autonomous Loop

Step 8 — Teach your agent to observe, plan, act, and reflect.

This is where your agent becomes more than a model. You’ll build a loop that lets your agent decide what to do next, call tools, and work toward a goal — all on its own.

Create an Autonomous Agent Loop

Autonomous agents don’t just respond — they think, plan, act, and evaluate. This pattern is at the heart of modern agent research, including frameworks like ReAct (Reason + Act) and LLM‑as‑Agents. By giving your agent a loop, you allow it to break tasks into steps, call tools when needed, and reflect on its progress.

The loop follows a simple but powerful cycle:

  • Observe — understand the current state
  • Plan — decide what to do next
  • Act — call a tool or take an action
  • Reflect — evaluate the result and update context

This cycle repeats until the agent reaches its goal or determines it has done enough — a core behavior behind autonomous systems.


1. Create loop.js

Create a new file for your autonomous loop:

touch loop.js

Add the following code:

import ollama from "ollama"; import { tools } from "./tools.js"; async function autonomousLoop(goal) { let context = []; for (let step = 1; step <= 5; step++) { console.log("\\n--- Step " + step + " ---"); // 1. Ask the model what to do next const response = await ollama.chat({ model: "llama3", messages: [ { role: "system", content: "You are an autonomous agent. Think step by step." }, { role: "user", content: `Goal: ${goal}` }, ...context ], stream: false }); const plan = response.message.content; console.log("Plan:", plan); // 2. Try to detect a tool call const match = plan.match(/use tool (\\w+) with args (.*)/i); if (match) { const [, toolName, rawArgs] = match; const args = JSON.parse(rawArgs); if (tools[toolName]) { const result = tools[toolName](...args); console.log("Tool result:", result); context.push({ role: "assistant", content: `Tool ${toolName} returned: ${JSON.stringify(result)}` }); } else { console.log("Unknown tool:", toolName); } } else { console.log("No tool call detected."); } } } autonomousLoop("List all files in this folder and summarize them.");

This loop runs for five iterations, giving your agent multiple chances to plan, act, and refine its approach. Even with simple tools, you’ll see surprisingly structured behavior emerge.


2. Run the Loop

node loop.js

You’ll see output like:

--- Step 1 --- Plan: I will use tool listFiles with args ["."] Tool result: ["agent.js","server.js","tools.js","loop.js"]

Each step builds on the last, creating a chain of reasoning and action — the essence of autonomous agents.


3. Customize the Goal

Try giving your agent different objectives:

autonomousLoop("Read agent.js and summarize what it does.");

Or something more creative:

autonomousLoop("Create a new file called summary.txt with a short poem.");

The more tools you provide, the more complex and interesting the agent’s behavior becomes.


4. Add More Tools

Autonomous loops become dramatically more powerful when paired with richer tools. Consider adding tools for:

  • fetching URLs or APIs
  • searching or summarizing logs
  • organizing folders or renaming files
  • generating structured reports
  • interacting with databases or local services

This is how real agentic systems are built: a loop, a set of tools, and a model capable of planning. For deeper inspiration, the AutoGPT and BabyAGI papers explore early autonomous agent architectures.


Troubleshooting

Agent doesn’t call tools

  • Give clearer instructions in the system prompt
  • Break the goal into smaller tasks

JSON parse errors

  • Models sometimes output invalid JSON — simplify your prompts
  • Try a more structured model like qwen

Loop stops early

  • Increase the step count
  • Improve the system prompt to encourage multi‑step reasoning

Next Step
Build a Multi‑Agent Workflow →