Agent Loop
🎯 Introduction
When one tool call cannot answer a question, the application must return its result to the model so it can keep selecting tools until it answers. This is the role of the agent loop. In this article, we will implement one with the OpenAI SDK, covering repeated model calls, tool result messages, and stopping conditions.
🧱 How the Agent Loop Works
Suppose the user asks, “Are there enough mechanical keyboards to buy 15 units?” The model first needs the product ID, then its stock level. After each tool execution, the application appends the model’s tool call message and the tool result to messages, then calls the model again with the updated history and tool list.
Here is one possible sequence:
| Model request | New information this round (retained in later requests) | Model response |
|---|---|---|
| First | System prompt and user question | Look up the product ID |
| Second | ID lookup request and result: P100 | Check stock |
| Third | Stock lookup request and result: 12 units | Insufficient stock; 3 more are needed |
Each request retains the previous messages, allowing the model to use earlier results when selecting tools. The application ends the loop when no new tools are requested and sets a maximum number of rounds to prevent indefinite execution.
🛠 Set Up the Example Project
This course uses the agent-demo project throughout. Later articles reuse its dependencies and files without initializing another project.
Use Node.js 24 LTS and OpenAI SDK 7.62.0:
mkdir agent-demo
cd agent-demo
npm init -y
npm install --save-exact openai@7.62.0
Reuse the working model configuration from the AI SDK course and create .env in the project root:
AI_API_KEY=YOUR_API_KEY
AI_BASE_URL=https://api.openai.com/v1
AI_MODEL=gpt-4o-mini
The example uses the OpenAI Chat Completions API. Other compatible services must support both tool calls and tool result messages. Use an endpoint, key, and model you have verified. Add .env and node_modules/ to .gitignore.
Prepare the Business Functions
Create shop.mjs with product data and lookup functions shared by later articles:
const products = [
{ id: 'P100', name: 'mechanical keyboard', stock: 12 },
{ id: 'P200', name: 'wireless mouse', stock: 0 },
];
// Look up the ID and name by product name, without returning stock
export function findProduct(name) {
const product = products.find(item => item.name === name);
return product ? { id: product.id, name: product.name } : { error: 'Product not found' };
}
// Look up stock by product ID
export function getStock(id) {
const product = products.find(item => item.id === id);
return product ? { id: product.id, stock: product.stock } : { error: 'Product does not exist' };
}
Separating product search from stock lookup makes their dependency easier to observe. In a real project, these functions could call business APIs.
🧱 Let the Model Select Tools
Create 02.agent-loop.mjs and start with the model client and tool list:
import OpenAI from 'openai';
import { findProduct, getStock } from './shop.mjs';
const ai = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL,
});
const tools = [
{
type: 'function',
function: {
name: 'find_product',
description: 'Look up a product ID by name, without returning stock',
parameters: {
type: 'object',
properties: { name: { type: 'string' } },
required: ['name'],
additionalProperties: false,
},
},
},
{
type: 'function',
function: {
name: 'get_stock',
description: 'Look up stock using a known product ID',
parameters: {
type: 'object',
properties: { id: { type: 'string' } },
required: ['id'],
additionalProperties: false,
},
},
},
];
The tool definitions follow the function calling format introduced earlier. Append the initial messages and model request function:
// Keep the task history and append tool call messages and results as execution proceeds
const messages = [
{
role: 'system',
content:
'You are a product assistant. Always use tools for product data. Never guess IDs or stock levels. Report failed lookups accurately.',
},
{ role: 'user', content: 'Are there enough mechanical keyboards to buy 15 units?' },
];
async function askModel() {
const response = await ai.chat.completions.create({
model: process.env.AI_MODEL,
messages,
tools,
// Request at most one tool per response to make the sequence easier to observe
parallel_tool_calls: false,
});
const choice = response.choices[0];
// Accept only normal answers or tool requests; reject truncated responses
if (!choice || !['stop', 'tool_calls'].includes(choice.finish_reason)) {
throw new Error('The model response did not finish normally');
}
return choice.message;
}
parallel_tool_calls, remove it. The loop below also handles multiple tool requests in one response.Temporarily append these two lines:
const message = await askModel();
console.log(JSON.stringify(message.tool_calls, null, 4));
Run:
node --env-file=.env 02.agent-loop.mjs
One possible output follows (the model service generates the call ID):
[
{
"id": "call_1",
"type": "function",
"function": {
"name": "find_product",
"arguments": "{\"name\":\"mechanical keyboard\"}"
}
}
]
At this point, the model has only requested a tool call. No product data has actually been queried.
🧱 Execute Tools and Return Results
Remove the two temporary lines that call askModel() and print its result. Add the tool execution function:
function executeTool(call) {
if (call.type !== 'function') {
return { error: 'Unsupported tool type' };
}
try {
const args = JSON.parse(call.function.arguments);
// Execute only allowed business functions and check required arguments
if (call.function.name === 'find_product' && typeof args.name === 'string') {
return findProduct(args.name);
}
if (call.function.name === 'get_stock' && typeof args.id === 'string') {
return getStock(args.id);
}
return { error: 'Unknown tool or invalid arguments' };
} catch {
// Return the failure to the model instead of ending the loop immediately
return { error: 'Failed to parse tool arguments or execute the tool' };
}
}
The application uses executeTool() to turn a model tool request into a function call. For example, find_product returns product ID P100.
Retain the original assistant message containing the tool call and append its corresponding tool result message:
{
"role": "tool",
"tool_call_id": "call_1",
"content": "{\"id\":\"P100\",\"name\":\"mechanical keyboard\"}"
}
tool_call_id must match the call ID supplied by the model so the API can associate the result with the original request.
🧱 Implement the Complete Loop
With the model request and tool execution functions in place, append the loop:
const maxRounds = 6;
let stopped = false;
for (let round = 1; round <= maxRounds; round++) {
// Call the model with the current history and tool list
const message = await askModel();
const calls = message.tool_calls ?? [];
// Without new tool requests, save and print the answer, then end the loop
if (calls.length === 0) {
messages.push(message);
console.log('Final answer:', message.content ?? 'The model returned no text');
stopped = true;
break;
}
// The last round has no budget for another model request, so execute no new tools
if (round === maxRounds) break;
// Save the tool call message from the model
messages.push(message);
// Execute this round’s tools and append their results to the history
for (const call of calls) {
const result = executeTool(call);
console.log(`Round ${round}:`, call.function?.name, result);
messages.push({
role: 'tool',
tool_call_id: call.id,
content: JSON.stringify(result),
});
}
// The next round sends the updated messages to the model
}
if (!stopped) {
console.log('Maximum rounds reached. Task completion has not been confirmed.');
}
The outer loop repeatedly calls the model. The inner loop executes every tool requested in the current round. The code does not prescribe which tool comes first; the model decides what to do next from each result.
Run it again:
node --env-file=.env 02.agent-loop.mjs
One possible execution result:
Round 1: find_product { id: 'P100', name: 'mechanical keyboard' }
Round 2: get_stock { id: 'P100', stock: 12 }
Final answer: There are 12 units in stock, so you need 3 more.
The first two lines are actual tool results. The third model request produces the final answer. Call counts and wording may vary; check the answer against the tool results.
How Do We Keep the Loop Bounded?
maxRounds allows at most 6 calls to askModel(). The final round can still return an answer, but it cannot execute new tools. One model response may request multiple tools, so rounds and tool calls are not equivalent.
stopped only indicates that the model stopped requesting tools; it does not guarantee the business goal was achieved. This example exits with an error if a model request fails. Later articles cover more complete execution controls.❓ Questions and Answers
Q1: Must every round of the agent loop call a tool?
No. The model may answer directly or request multiple tools in one round. Handle the actual response rather than assuming a fixed number of calls.
🧪 Exercises
- Change the question to “Is P200 still in stock?” Check whether the model calls
get_stockdirectly and reports 0 units. - Restore the mechanical keyboard question and set
maxRoundsto 1. If the model requests a tool, the program should report that completion is unconfirmed without executing it.
Restore the original configuration after the exercises.
🎉 Congratulations! You have implemented an agent loop with explicit stopping conditions.
