---
title: "How to Create an AI Agent Step-by-Step in NodeJS"
description: "A comprehensive, step-by-step guide on how to build an autonomous AI agent from scratch using NodeJS and the OpenAI API. Includes detailed code examples."
slug: "how-to-create-ai-agent-step-by-step"
date: "2026-03-14"
author: "Jayesh Jain"
category: "Artificial Intelligence"
tags: ["AI", "AI Agents", "NodeJS", "Tutorial", "OpenAI"]
keywords: "how to create an AI agent, build AI agent step by step, nodejs ai agent tutorial, ai agent from scratch, openai api agent, create autonomous agent, ai agent tutorial"
excerpt: "Learn how to build your own autonomous AI agent step-by-step. This detailed guide covers creating tools, managing conversational loops, and using the OpenAI API in NodeJS."
featuredImage: "/blog/how-to-create-ai-agent-step-by-step.png"
cta: "Want to build custom AI agents for your business?"
ctaDescription: "Our team specializes in developing tailored autonomous AI agents. Contact us to automate your complex workflows."
---

# How to Create an AI Agent Step-by-Step in NodeJS

As we transition from basic chatbots to autonomous systems, knowing how to build an actively "doing" system is becoming an essential skill. While you *could* utilize complex frameworks like LangChain or AutoGen, it's incredibly valuable to understand how to build a basic agent from scratch.

In this tutorial, we are going to build an AI agent step-by-step using **NodeJS** and the **OpenAI API**. 

Our goal is to build a simple "Weather & News" agent. Rather than just making up answers, our agent will securely access external tools (functions we define) to fetch real-world data before constructing a response.

---

## Step 1: Setting Up the Environment

First, let's set up a new NodeJS project and install the necessary dependencies. Open your terminal and run the following commands:

```bash
# Create a new directory and enter it
mkdir my-first-ai-agent
cd my-first-ai-agent

# Initialize a new Node project
npm init -y

# Install the official OpenAI SDK and dotenv to manage your API key
npm install openai dotenv
```

Next, in the root of your project directory, create two files: **index.js** and **.env**.

In your **.env** file, add your OpenAI API Key:
```properties
OPENAI_API_KEY=sk-your-super-secret-api-key
```

*Don’t have an API key? You can grab one by creating an account on the [OpenAI Developer Platform](https://platform.openai.com/api-keys).*

---

## Step 2: The Logic Behind an AI Agent

Before we write code, we need to understand the fundamental architecture of what we're building. A standard agent operates on a **ReAct** (Reasoning + Acting) loop:

1. **User Input:** The human provides a goal or asks a question.
2. **Thought/Planning:** The LLM decides what information it needs to achieve the goal.
3. **Action:** The LLM requests to use a specific "Tool" (a function).
4. **Observation:** Your code executes the function and feeds the data *back* into the LLM.
5. **Repeat or Output:** The LLM looks at the data. If it has all the info it needs, it formulates a final response. If not, it loops back to step 2.

Let's begin writing **index.js** piece by piece.

---

## Step 3: Initializing the OpenAI Client

Open **index.js** and set up your imports and the OpenAI client. We will also add a simple prompt that governs the agent's behavior.

```javascript
import { OpenAI } from "openai";
import dotenv from "dotenv";

// Load environment variables
dotenv.config();

// Initialize the OpenAI client
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// The System Prompt gives the agent its identity and rules
const SYSTEM_PROMPT = `
You are a helpful, autonomous assistant. 
You can use external tools to answer the user's questions.
If you don't know the answer, try to use a tool to find out. 
Do not guess data like the weather or current news, always use tools.
`;
```

*(Note: To use **import**, ensure you add **"type": "module"** in your **package.json**, or use **require()** statements instead).*

---

## Step 4: Defining the Tools (Functions)

An agent is useless without tools to interact with the outside world. To allow an LLM to call a function, we must provide it with a **JSON Schema** describing the tool's name, description, and required arguments.

Let's define two mock tools: one for the weather, and one for stock prices.

```javascript
// 1. The definitions we send to OpenAI so it knows what tools exist
const availableTools = [
  {
    type: "function",
    function: {
      name: "getWeather",
      description: "Gets the current weather for a specific city.",
      parameters: {
        type: "object",
        properties: {
          city: { type: "string", description: "The city to check the weather in." }
        },
        required: ["city"]
      }
    }
  },
  {
    type: "function",
    function: {
      name: "getStockPrice",
      description: "Gets the current stock price for a company ticker symbol.",
      parameters: {
        type: "object",
        properties: {
          ticker: { type: "string", description: "The stock ticker symbol, e.g., AAPL or MSFT." }
        },
        required: ["ticker"]
      }
    }
  }
];

// 2. The actual Javascript functions that execute the work
async function getWeather({ city }) {
  console.log(`[Tool] Fetching weather for ${city}...`);
  // In a real app, you would use fetch() to call a weather API here.
  return { temperature: 24, conditions: "Partly Cloudy", unit: "Celsius" };
}

async function getStockPrice({ ticker }) {
  console.log(`[Tool] Fetching stock price for ${ticker}...`);
  // In a real app, you would use fetch() to call a financial API here.
  // Mocking realistic responses:
  const mockPrices = { "AAPL": 175.50, "MSFT": 410.20, "GOOGL": 140.10 };
  const price = mockPrices[ticker.toUpperCase()] || 100.00;
  return { ticker: ticker.toUpperCase(), current_price: price, currency: "USD" };
}
```

---

## Step 5: Creating the Agent Loop (The Heart of the Agent)

Now for the complex part. We need a function that handles the conversational history and loops through the **Thought -> Action -> Observation** cycle.

```javascript
async function runAgent(userPrompt) {
  console.log(`\nUser: "${userPrompt}"\n`);

  // We start the conversation with the System Rules and the User's goal
  const messages = [
    { role: "system", content: SYSTEM_PROMPT },
    { role: "user", content: userPrompt }
  ];

  // We will loop until the agent decides it has everything it needs
  let isTaskComplete = false;

  while (!isTaskComplete) {
    // Tell OpenAI to "Think" based on current messages and available tools
    const response = await openai.chat.completions.create({
      model: "gpt-4o", // You can use gpt-4-turbo or gpt-3.5-turbo as well
      messages: messages,
      tools: availableTools,
      tool_choice: "auto", // The model decides if it needs a tool or can just answer
    });

    const agentMessage = response.choices[0].message;
    
    // Append the agent's thought process to the conversation history
    messages.push(agentMessage);

    // ACTION Check: Did the agent request to use a tool?
    if (agentMessage.tool_calls && agentMessage.tool_calls.length > 0) {
      
      // The agent might want to use multiple tools at once, so we loop through its requests
      for (const toolCall of agentMessage.tool_calls) {
        const functionName = toolCall.function.name;
        const functionArgs = JSON.parse(toolCall.function.arguments);

        let toolResult;

        // Route the requested function to our actual Javascript code
        if (functionName === "getWeather") {
          toolResult = await getWeather(functionArgs);
        } else if (functionName === "getStockPrice") {
          toolResult = await getStockPrice(functionArgs);
        } else {
          toolResult = { error: "Unknown tool called." };
        }

        // OBSERVATION: Feed the result back into the message array
        messages.push({
          role: "tool",
          tool_call_id: toolCall.id,       // You MUST provide the ID so OpenAI knows which tool this links to
          content: JSON.stringify(toolResult) // The result must be passed as a string
        });
      }
      
      // Important: We do NOT set isTaskComplete = true here.
      // We want the loop to run again so the LLM can read the tool observation!

    } else {
      // If there are no tool_calls, the agent is providing its final answer to the user.
      console.log(`Agent:\n${agentMessage.content}\n`);
      isTaskComplete = true; // Break the loop
    }
  }
}
```

---

## Step 6: Testing the Agent

Finally, let's call our agent with a complex prompt that forces it to make multiple tool calls. Add this to the very bottom of your **index.js** file:

```javascript
// A prompt that requires two separate tool calls
runAgent("I'm heading to London tomorrow. Can you tell me what the weather will be like, and also check the current stock price for Apple?");
```

If you run this in your terminal using **node index.js**, you should see output similar to this:

```text
User: "I'm heading to London tomorrow. Can you tell me what the weather will be like, and also check the current stock price for Apple?"

[Tool] Fetching weather for London...
[Tool] Fetching stock price for Apple...

Agent:
The weather in London tomorrow will be partly cloudy with a temperature of around 24°C. 

As for Apple's stock, it is currently priced at $175.50 USD. 

Let me know if you need anything else!
```

**Congratulations!** You've just built an autonomous AI agent. 

When you gave it a prompt, the agent independently realized that to answer correctly, it needed to fetch both London's weather and Apple's stock. It called both of your functions, waited for the data, analyzed the results, and phrased a perfect final response.

---

## Where to go from here?

This simple loop is the foundation of every major agent framework, including the wildly popular Devin or AutoGen agents. To make this agent more powerful, you can:
- Give it tools that modify databases (like **createUser** or **updateOrderStatus**).
- Give it access to the **puppeteer** library to browse real websites and scrape data.
- Attach an older conversation history so it "remembers" what you talked about yesterday.

Building AI agents isn't just a trend; it's a paradigm shift in how we approach automation. Start small, give your agent custom tools relevant to your business, and watch as your productivity skyrockets.
