Agents from scratch (TypeScript) · Chapter 6 of 18
Budgets and loops
By the end of this chapter you can make sure an agent always stops: a cap on its requests with a clear reason, a guard that notices the model repeating a call, a forced answer with tool_choice: 'none', and a budget in tokens and rupees that ends a run before it gets expensive. 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
- In the all labs plan
The first 2 chapters of Agents from scratch (TypeScript) are free. This one comes with the all labs plan.
Why you need this
Farooq in finance found it first: one Tuesday night the lab bill had a single conversation that cost more than a hundred ordinary ones. A customer had asked to move a booking, the model asked for reschedule_booking, got the result, and asked for it again. And again. The loop from chapter 3 runs "while the model asks for tools", and the model never stopped asking.
Real models do this. They loop on a result they do not understand, on an error they cannot fix, or for no reason anyone can see, and every turn is a paid request that resends a longer conversation. A loop that trusts the model to stop is a bill with no ceiling, and a customer waiting for an answer that never comes. The model decides what to do next; your code decides when it is over.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
max-steps.ts: a cap with a stop reason
Write and export runAgent(question, { model = 'lab-chat', maxSteps = 6 } = {}) in max-steps.ts: chapter 3's loop, with a system message that says today is 2026-10-22, the question as the user's message, GharFix's TOOLS, every call run with GharFix's function, and every request sent to the model it is given. The file does nothing else when imported.
It returns an object with the answer and a stop reason: { answer: the answer's text, stop: 'answered' } when the model answers; { answer: null, stop: 'max_steps' } when it has sent maxSteps requests and the last one still asked for tools.
The check runs it with lab-chat, and with lab-chat-loopy (a model that asks for a call again after every result) with several caps.
- Task 2
repeat-guard.ts: a repeat guard
Write and export runAgent(question, { model = 'lab-chat', maxSteps = 6 } = {}) in repeat-guard.ts: task 1's loop with a repeat guard. Keep every call the run has made, as its tool name and its arguments.
When a reply asks for a call the run already made (the same tool with the same arguments, where spacing and key order in the JSON do not count), run nothing from that reply: send the conversation so far once more, without that reply, with tool_choice: 'none', and return { answer: that answer's text, stop: 'repeated' }. Otherwise it behaves as task 1.
- Task 3
budget.ts: a budget in tokens and rupees
In budget.ts, export three things. loadPrices(): an async function returning an object from each model's id to its price_inr_per_million (input, cached_input and output, in rupees per million tokens), read from the lab's model list, the one lab models prints; models without prices are left out.
A class Budget, made with new Budget(prices, { maxTokens, maxRupees }), both limits optional. tokens and rupees are the totals so far, starting at 0. add(model, usage) adds one response's usage: its prompt and completion tokens to tokens, and their price to rupees. A response's cached prompt tokens (usage.prompt_tokens_details.cached_tokens) cost the cached_input price, the rest of its prompt tokens the input price, and its completion tokens the output price. over() is true when tokens are more than maxTokens, or rupees more than maxRupees; a missing limit is no limit.
And runAgent(question, { model = 'lab-chat', budget } = {}): task 1's loop with at most 10 requests. After every request, add its usage to the budget. If the model answered, return { answer, stop: 'answered' }; otherwise, if the budget is over, return { answer: null, stop: 'budget' } without running that reply's calls. After 10 requests, { answer: null, stop: 'max_steps' }.
- Task 4 · interview question
Interview: fix-forever.ts, the loop that runs forever
fix-forever.ts has a repeat guard, and it still never finishes with lab-chat-loopy. Fix runAgent(question, model) so that it always ends: when the model asks for a call the run already made (the same tool with the same arguments), run nothing from that reply, send the conversation once more with tool_choice: 'none', and return that answer. Never send more than 6 requests in the loop; if it gets there, end the same way.
Keep the function's name and parameters, the system message, the question and the two answers it prints.
What you will learn
- A cap on requests, with a stop reason the rest of the code can use.
- A repeat guard: the same tool with the same arguments, noticed.
- tool_choice: 'none': making the model answer from what it has.
- A budget from each response's usage and the model's prices, including a field the SDK's types do not know about.
More in The loop
Build "Budgets and loops" 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.
The first 2 chapters of Agents from scratch (TypeScript) are free. This one comes with the all labs plan.