The application executes the tool requests a model returns. If the model keeps asking for another lookup, your loop decides whether to keep spending time and memory or stop with the evidence already collected.
Ollama’s chat API can return several tool calls in one response. Count both rounds and individual calls, limit each tool result, and reject missing or unknown tool names. The loop below also gives Ollama fetches a shared deadline; tools need cancellation or execution limits appropriate to their own work.
A bounded local example
Prerequisites: Node.js 20 or newer, Ollama running on localhost, and a model that supports tool calling already available in Ollama. This example exposes only a bounded multiplication function. It makes no external requests besides the local Ollama API.
Save as bounded-agent.mjs and run OLLAMA_MODEL=your-model node bounded-agent.mjs (PowerShell: $env:OLLAMA_MODEL='your-model'; node .\bounded-agent.mjs).
const model = process.env.OLLAMA_MODEL; if (!model) throw new Error('Set OLLAMA_MODEL to an installed tool-capable model'); const controller = new AbortController(); const deadline = setTimeout(() => controller.abort(), 60_000); const MAX_ROUNDS = 4; const MAX_TOOL_CALLS = 4; const MAX_TOOL_BYTES = 2_048; const tools = [{ type: 'function', function: { name: 'multiply', description: 'Multiply two finite numbers between -100000 and 100000', parameters: { type: 'object', required: ['a', 'b'], additionalProperties: false, properties: { a: { type: 'number' }, b: { type: 'number' } } }, } }]; async function chat(messages) { const response = await fetch('http://localhost:11434/api/chat', { method: 'POST', signal: controller.signal, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model, messages, tools, stream: false }), }); if (!response.ok) throw new Error(`Ollama returned HTTP ${response.status}`); return response.json(); } try { const messages = [{ role: 'user', content: 'Use the multiply tool to calculate 125 times 32.' }]; let toolCalls = 0; for (let round = 0; round <= MAX_ROUNDS; round++) { const result = await chat(messages); const assistant = result.message; const requests = assistant?.tool_calls ?? []; if (!Array.isArray(requests)) throw new Error('Invalid tool_calls response'); if (requests.length === 0) { console.log(assistant?.content ?? 'No final text returned'); break; } if (round === MAX_ROUNDS) throw new Error('Tool-round budget exhausted'); if (requests.length > MAX_TOOL_CALLS - toolCalls) { throw new Error('Total tool-call budget would be exceeded'); } toolCalls += requests.length; messages.push(assistant); for (const request of requests) { controller.signal.throwIfAborted(); const fn = request.function; if (fn?.name !== 'multiply') throw new Error(`Unknown tool rejected: ${fn?.name}`); const args = fn.arguments; if (!args || typeof args !== 'object' || Array.isArray(args) || Object.keys(args).some((key) => key !== 'a' && key !== 'b')) { throw new Error('Invalid multiply argument object'); } const { a, b } = args; if (![a, b].every(Number.isFinite) || Math.abs(a) > 100_000 || Math.abs(b) > 100_000) { throw new Error('Invalid multiply arguments'); } const text = JSON.stringify({ value: a * b }); if (Buffer.byteLength(text, 'utf8') > MAX_TOOL_BYTES) throw new Error('Tool output too large'); messages.push({ role: 'tool', tool_name: 'multiply', content: text }); } } } finally { clearTimeout(deadline); } The example limits both tool-request rounds and total tool calls. It rejects a batch that would exceed the remaining call budget before dispatching any item in that batch. The AbortController deadline applies to the Ollama fetches, and the explicit signal check prevents dispatch after the deadline has fired. Abort signals are cooperative: JavaScript cannot preempt a synchronous tool already running. Keep synchronous tools trivially bounded, and isolate or separately time-limit any expensive process or network operation.
Make the budget match the work
A lookup assistant may need one call; a workflow that searches and then reads three results needs four. Set the ceiling from the task and return a clear “budget exhausted” state when it is reached.
The byte limit matters too. A tool can return a whole directory or a huge database row even when the model asked a small question. Enforce limits where the tool reads or serializes data, truncate only when the caller can recognize truncation, and avoid converting a large result into tokens before checking its size. This example checks a tiny JSON result because its tool produces one number.
Before dispatching through handlers[modelName], check that the handler exists and is approved for this task. Validate arguments independently of the JSON schema: the schema helps the model form a request, while host-side validation controls what actually runs.
A single call can still delete a directory or send private data. Restrict the available operations and require approval for consequential actions. Ollama’s tool-calling guide describes the request-and-result cycle, and the chat API reference documents messages and tool calls.

