Agents from scratch (TypeScript) · Chapter 1 of 18

What an agent is

By the end of this chapter you can explain what turns a chat model into an agent, describe a tool to a model, run the call it asks for, send the result back, and walk a two-step booking through by hand, in TypeScript. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The loop
  • 4 tasks
  • TypeScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

GharFix sends plumbers, electricians, carpenters and AC technicians to homes all over Bengaluru, and its customers book on WhatsApp: "kal subah Koramangala mein plumber chahiye", "AC service beku naale", "move my booking to Saturday". Meenakshi, who runs operations, has a team that does each one by hand: find a technician who does the job and covers the area, check his calendar, quote the rate card, book the slot, send the booking ID. A reschedule or a refund means reading the policy first.

Anjali, the founder, wants an assistant that does this work, not one that only chats about it. That is a different thing from what you may have built before. Answering a question is one call to a model. Booking a plumber is several steps, each depending on the last, with real effects: a slot taken, money promised. Get it wrong and two families wait for the same technician, or a customer is promised a refund the policy does not allow. Vikram, GharFix's staff engineer, will show you how it works from the inside, with no framework hiding it.

The lesson

A model can only write text

A language model reads the messages you send and writes a reply, one token at a time. It does not look anything up, and it cannot change anything: it has no hands. Ask it about GharFix and it answers from what it learned in training about companies like GharFix:

import OpenAI from 'openai';

const client = new OpenAI();
const response = await client.chat.completions.create({
  model: 'lab-chat',
  temperature: 0,
  messages: [
    { role: 'system', content: "You are GharFix's booking assistant. Today is 2026-10-22." },
    { role: 'user', content: 'Can I reschedule my booking?' },
  ],
});
console.log(response.choices[0].message.content);
You can reschedule as many times as you like, free of charge.

GharFix's policy (/workspace/data/policy.md, section 3) allows one free reschedule; every other one costs ₹99. The model did not know, so it wrote what such answers usually say. Now imagine asking it to book something. It has no calendar to read and no booking to write, yet a chat model is trained to be helpful, and it may well say it did the job. Task 1 asks it, and then looks in bookings.json for what really happened.

A few things about the code, since every chapter uses it:

  • create() returns a promise: the request goes over the network, so you await it. A .ts file in this lab is an ES module, so await works at the top of the file.
  • node file.ts runs it. Node strips the types and runs the JavaScript that is left; typecheck in the terminal checks the types.
  • lab-chat is this lab's own model: it runs inside your lab with the same API as OpenAI's, so the official openai package works unchanged. OPENAI_BASE_URL and OPENAI_API_KEY point the package at it; point them at a real provider with your own key and the same code talks to a real model.

Tools: the model asks, your code acts

The fix is not a better prompt. It is giving the model a way to ask your code to do things. You describe a function in the request's tools array: a name, a sentence on what it does, and its parameters as a JSON Schema:

import type { ChatCompletionTool } from 'openai/resources/chat/completions';

const tools: ChatCompletionTool[] = [
  {
    type: 'function',
    function: {
      name: 'get_booking',
      description: 'Look up a GharFix booking by its booking ID.',
      parameters: {
        type: 'object',
        properties: { booking_id: { type: 'string', description: 'GF and 6 digits' } },
        required: ['booking_id'],
      },
    },
  },
];

The type annotation matters in TypeScript. Without it, type: 'function' is widened to any string, and typecheck refuses the array when you pass it to create(): "Type 'string' is not assignable to type '"function"'". With it, your editor knows the shape and catches a misspelt descripton. (Inside parameters, which is plain JSON Schema, nothing is checked: chapter 2 builds the schema from types instead.)

Send it with a customer's question, tools, and the reply is not text. For "Is my booking GF326614 confirmed?":

const choice = response.choices[0];
console.log(choice.finish_reason);
console.log(choice.message);
tool_calls
{
  role: 'assistant',
  content: null,
  refusal: null,
  tool_calls: [
    {
      id: 'call_LAJVloFjJpZE9nAObH5qmYF2',
      type: 'function',
      function: [Object]
    }
  ]
}

and the call's function is { name: 'get_booking', arguments: '{"booking_id":"GF326614"}' }.

  • finish_reason is 'tool_calls': the model stopped to ask for a tool. content is null.
  • The model ran nothing. It wrote a request, the way it writes any text: a tool's name and the arguments it read from the message.
  • arguments is a string of JSON, not an object: JSON.parse turns it into one.
  • id names this call; the answer you send back must carry it.
  • type says what kind of call it is. The SDK's type for a call is a union, a function call or a custom tool call, and only a function call has .function. TypeScript makes you check call.type === 'function' before you read it.

It chose get_booking by its name and description and filled booking_id by the parameter's name, so write them for a reader. Task 2 describes a tool of your own.

The round trip

Now your code does the work. GharFix's booking system is already in this lab, shared/gharfix.ts, written by Vikram's team before anyone thought of AI: plain functions over /workspace/data. Each one takes one object of arguments, named exactly as the tool's parameters are, so the object the model sent can go straight in. getBooking looks the booking up. To give the model the result, resend the conversation with two more messages: the model's own message with its tool call, and a tool message carrying the result and the tool_call_id it answers:

import { getBooking } from '../../shared/gharfix.ts';

const message = response.choices[0].message;
const call = message.tool_calls![0];
if (call.type === 'function') {
  const result = getBooking(JSON.parse(call.function.arguments));
  messages.push(message);
  messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
}
const final = await client.chat.completions.create({ model: 'lab-chat', messages, tools });
Booking GF326614 on 2026-11-18 is confirmed, for ₹1499 (customer name: Nisha
Desai, area: Marathahalli, service: ac, job: ac-install, technician id: T13,
slot: evening).

messages is an array typed ChatCompletionMessageParam[] (from the same openai/resources/chat/completions), which takes every role, so the model's own message can be pushed onto it as it came back. The import ends in .ts: Node runs the file as it is, so the path names the real file.

The model remembers nothing between requests: the second request holds everything, the question, its own request for the tool and the result. content is text, so the result goes as a JSON string. The API checks the pairing, and its errors say exactly what is wrong. Leave out the tool message and the SDK throws a BadRequestError:

Error: 400 An assistant message with 'tool_calls' must be followed by tool
messages responding to each 'tool_call_id'. The following tool_call_ids did
not have response messages: call_LAJVloFjJpZE9nAObH5qmYF2

A tool message with no call before it is refused too ("messages with role 'tool' must be a response to a preceeding message with 'tool_calls'", the API's own spelling). Task 3 runs one round trip by hand, with all eight of GharFix's tools on offer: TOOLS describes them and FUNCTIONS finds each function by its tool's name (FUNCTIONS.get_booking is getBooking). lab tools lists them in the terminal.

An agent is a model, tools and a loop

A booking is more than one lookup. Here is Meenakshi's plumber request, the one from task 1, sent with GharFix's eight tools (temperature: 0, so it repeats):

step 1  asks find_technicians({"service":"plumbing","area":"Koramangala",
                               "date":"2026-10-23","slot":"morning"})
        result: [{"technician_id":"T05","name":"Naveen Reddy","rating":4.6,...},...]
step 2  asks book_slot({"technician_id":"T05","date":"2026-10-23","slot":"morning",
                        "job":"leak-fix","area":"Koramangala",
                        "customer_name":"Ravi Kumar","phone":"9876543210"})
        result: {"booking_id":"GF100001","customer_name":"Ravi Kumar",...}
step 3  answers: Booking GF100001 on 2026-10-23 is confirmed, for ₹349 (...)

The model could not ask for book_slot first: it needs a technician_id, and the message has none. So it asked for find_technicians, read the result, and only then had what book_slot needs. It turned "tomorrow" into 2026-10-23 because the system message gave today's date. Each step is one ordinary request; what makes it an agent is that your code keeps going until the model answers in text.

That is all an agent is:

  1. a model that decides what to do next,
  2. tools, your functions, that let it read and change the world,
  3. a loop, your code, that runs each call, sends the results back and asks again, until the model answers.

The model only ever writes requests. Your code decides what actually runs, with which arguments, how many times, and with what checks. That is where this whole lab lives.

Every step costs more

Each request resends the whole conversation, so a run grows. The three requests above sent 956, 1,154 and 1,351 prompt tokens. Tool descriptions are tokens too: the short question "How much is a tap repair?" costs 13 prompt tokens with no tools and 911 with GharFix's eight. Farooq, who pays the bills, will ask about this in chapter 15. lab steps in the terminal shows your last run the way it is shown above.

What can go wrong

A real model can ask for a tool that does not exist, send arguments your function rejects, ask for the same call forever, book a slot without checking it is free, or obey an instruction hidden in a customer's message. None of that is rare, and none of it is fixed by a better prompt alone. TypeScript's types do not stop it either: they are checked before the program runs, and the model's arguments only arrive while it runs. Chapters 3 to 12 build the loop that survives it: errors as results, budgets, validation, plans, state, confirmation before booking or refunding, permissions and traces.

Your turn

Send Meenakshi's request with no tools in task 1, and check the bookings yourself. Describe get_quote in task 2, run one call by hand in task 3, and in the interview question walk a booking through both of its tools.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    just-talk.ts: a model that can only talk

    Anjali wants to know what a plain chat model does with a real booking request. Send lab-chat two messages: a system message saying it is GharFix's booking assistant and that today is 2026-10-22, then Meenakshi's request as the user's message, exactly:

    Book a plumber in Koramangala tomorrow morning, a pipe is leaking under the sink. I am Ravi Kumar, phone 9876543210.

    Send no tools. Print only the reply's text. Then count the bookings in /workspace/data/bookings.json whose phone is 9876543210, and print the count as:

    Bookings found: N

  2. Task 2

    first-tool.ts: describe a tool

    Vikram wants the model to look prices up instead of guessing. Describe one tool yourself: its name is get_quote, it has a one-sentence description, and one required parameter, job, of type string.

    Send lab-chat the same system message as task 1 and the user's question, exactly:

    How much does a tap repair cost?

    with your tool. Print three lines: the first choice's finish reason, the name of the tool the model asked for, and its arguments as an object (console.log of the parsed object, not the JSON text).

  3. Task 3

    by-hand.ts: one tool call by hand

    Now do what the model asked. Offer lab-chat all of GharFix's tools (TOOLS from ../../shared/gharfix.ts), with the same system message and the user's question, exactly:

    What does it cost to fix a ceiling fan?

    Run each tool call the model asks for with GharFix's own function (FUNCTIONS maps a tool's name to it), send each result back as JSON in a second request, and print only the text of the model's final answer.

  4. Task 4 · interview question

    Interview: two-steps.ts, an agent by hand

    A booking needs two tools, one after the other. Offer lab-chat GharFix's tools with the same system message and Meenakshi's next request, exactly:

    Book an electrician in Jayanagar on 24 Oct, evening. The MCB keeps tripping. I am Divya Menon, phone 9811122233.

    Each time the model asks for tools, run every call with GharFix's function, print the tool's name, and send the results back. When it answers in text, print that answer and stop. Never send more than 5 requests.

What you will learn

  • Why a chat model alone cannot do the work, and what it does instead.
  • Tools: describing a function so a model can ask for it.
  • The round trip: the model asks, your code runs, the result goes back.
  • An agent is a model, tools and a loop, and a two-step booking by hand.

More in The loop

Build "What an agent is" yourself

GharFix, a Bengaluru home-services company, needs an assistant that books, reschedules and refunds safely. You build it in TypeScript. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.