Digital Engines logoDigital Engines
←Back to Journal
AI·October 6, 2026·13 min read

How to build an AI agent: tools, the agent loop and guardrails

DE
Digital Engines
Design & Technology Studio
Planning the flow of an AI agent workflow
ESSAY · 13 min read

A chatbot replies with text. An AI agent can look up an order, check a calendar, update a CRM record or draft an email, because it can call the tools you give it. This guide explains how agents work and walks through the core loop we use to build agents for clients.

1. How an AI agent works

Under the hood, an agent repeats a simple loop: the model reads the goal and the conversation, decides whether it needs a tool, your code runs that tool and returns the result, and the model continues until it can give a final answer.

  • Instructions: the agent's role, rules and tone.
  • Tools: functions the model is allowed to request, such as getOrderStatus or createTicket.
  • Memory: the conversation so far, plus any retrieved knowledge (often via RAG).
  • Loop and limits: run until the task is done, but never more than a fixed number of steps.
  • Guardrails: validation, permissions and human approval for sensitive actions.
“An agent is a model in a loop with tools. The engineering is in choosing the tools, limiting the loop and guarding the actions.”
— Strategic Takeaway

2. Define the tools

Tools are described with a name, a description and a JSON Schema for their inputs. Strict mode makes the model's arguments match the schema exactly. Good descriptions are the most important part, because they're how the model decides which tool to use.

Installbash
npm install openai
agent/tools.tsts
export const tools = [
  {
    type: "function" as const,
    name: "get_order_status",
    description: "Look up the current status and delivery date of a customer's order by order number.",
    strict: true,
    parameters: {
      type: "object",
      properties: {
        orderNumber: { type: "string", description: "Order number, e.g. DE-10293" },
      },
      required: ["orderNumber"],
      additionalProperties: false,
    },
  },
  {
    type: "function" as const,
    name: "create_support_ticket",
    description: "Create a support ticket for a human agent when the issue cannot be solved automatically.",
    strict: true,
    parameters: {
      type: "object",
      properties: {
        summary: { type: "string" },
        priority: { type: "string", enum: ["low", "normal", "urgent"] },
      },
      required: ["summary", "priority"],
      additionalProperties: false,
    },
  },
];

// Your real business logic. Connect to your database, CRM or helpdesk here.
export async function runTool(name: string, args: any) {
  switch (name) {
    case "get_order_status":
      return { orderNumber: args.orderNumber, status: "shipped", eta: "2026-11-14" };
    case "create_support_ticket":
      return { ticketId: "T-" + Date.now(), created: true };
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
}
How to build an AI agent: tools, the agent loop and guardrails visual illustration
FIG. 01 — AI Study

3. Build the agent loop

This is the heart of the agent. Each turn, we send the conversation and tools to the model. If it requests tool calls, we run them, add the results to the conversation and loop again. If it doesn't, we have our final answer.

agent/run-agent.tsts
import OpenAI from "openai";
import { tools, runTool } from "./tools";

const openai = new OpenAI();
const MAX_STEPS = 6; // guardrail: never loop forever

export async function runSupportAgent(userMessage: string) {
  const input: any[] = [{ role: "user", content: userMessage }];

  for (let step = 0; step < MAX_STEPS; step++) {
    const response = await openai.responses.create({
      model: process.env.OPENAI_MODEL!,
      instructions:
        "You are the customer support agent for Digital Engines' client store. " +
        "Use tools to look up real data; never invent order details. " +
        "If you cannot solve the problem, create a support ticket and tell the customer.",
      tools,
      input,
    });

    const toolCalls = response.output.filter((item) => item.type === "function_call");

    // No tool requested: the model has its final answer
    if (toolCalls.length === 0) return response.output_text;

    // Keep the model's tool requests in the conversation history
    input.push(...response.output);

    for (const call of toolCalls) {
      if (call.type !== "function_call") continue;
      const result = await runTool(call.name, JSON.parse(call.arguments));
      input.push({
        type: "function_call_output",
        call_id: call.call_id,
        output: JSON.stringify(result),
      });
    }
  }

  return "Sorry, I couldn't complete that. A member of our team will follow up shortly.";
}

4. Guardrails that make agents safe for business

An agent that can act needs firm boundaries. These are the rules we apply on every client project.

  • Least privilege: give each agent only the tools it needs, with read-only access where possible.
  • Validate every tool input on the server. Never trust arguments blindly, even with strict schemas.
  • Check permissions inside tools: the agent should only see data the current user is allowed to see.
  • Human-in-the-loop: refunds, payments, deletions and outgoing emails wait for a person to approve.
  • Cap steps, timeouts and spend per conversation.
  • Log every tool call with its inputs and outputs for auditing and debugging.
  • Treat text from emails, web pages and documents as untrusted. It can contain instructions meant to mislead the agent.

5. Frameworks and next steps

The loop above is intentionally simple so you can see how agents really work. For larger systems, frameworks such as the OpenAI Agents SDK, the Vercel AI SDK and LangGraph add handoffs between agents, tracing, streaming and memory. The Model Context Protocol (MCP) is also becoming a standard way to connect agents to tools like Slack, GitHub and databases.

Our advice is to start with one narrow workflow, such as order enquiries or lead qualification, measure the time it saves, and expand from there.

Core Takeaways

Principles for deliberate execution

  • 1An agent = a model + tools (functions it may call) + a loop that runs until the task is done.
  • 2Give tools clear names, precise descriptions and strict input schemas. The model relies on them.
  • 3Always cap the number of steps, validate tool inputs and require approval for risky actions.
  • 4Start with one narrow, high-value workflow before building a general-purpose agent.
Tagged:#AI Agents#Function Calling#Automation#OpenAI#Guardrails
DE
Written by
Digital Engines

Digital Engines engineers SaaS platforms, high-performance websites, mobile apps and AI systems for ambitious teams worldwide. These guides come from the tools we use on real client projects every day.

Get in touch →
Continue reading

More from the journal

All essays →