Quick revision
The short answer
First we make every step visible: trace prompts, tool calls, arguments, results and token counts under one request id, with Micrometer observations or OpenTelemetry. Then we add hard limits on steps, tokens and time so no request can run away, look for tools that return errors, huge payloads or overlapping descriptions, and stop hallucinated actions by only stating that a refund happened when a tool result in code confirms it. Finally, the failing conversations become an evaluation set that runs before every prompt or model change.
What to remember
In this answer, we debugged an agent that looped and invented refunds. We traced every prompt, tool call, result and token count under one request id, capped steps, tokens and time, fixed tools that returned errors, huge payloads or overlapping descriptions, required that claims about actions be backed by tool results checked in code, and turned the failing conversations into an evaluation set that runs before every change.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First we make every step visible: trace prompts, tool calls, arguments, results and token counts under one request id, with Micrometer observations or OpenTelemetry. Then we add hard limits on steps, tokens and time so no request can run away, look for tools that return errors, huge payloads or overlapping descriptions, and stop hallucinated actions by only stating that a refund happened when a tool result in code confirms it. Finally, the failing conversations become an evaluation set that runs before every prompt or model change.
Why this question is asked
Agents fail differently from normal code. Nothing throws an exception; instead a request quietly costs fifty times more than expected, or the agent tells a customer something that is not true. Both symptoms in this question, runaway tool calls and invented refunds, are common in production, and interviewers ask about them because they show whether we can debug a probabilistic component with engineering discipline. In this answer, we will make the agent observable, stop the bleeding with limits, find the usual causes of looping, deal with hallucinated actions, and prevent regressions with an evaluation set.
1A Quick Recap: Why One Request Can Make 40 Calls
An agent runs a tool-calling loop: the model either answers or asks the application to run a tool, the result goes back to the model, and the cycle repeats. Each round trip resends the whole conversation, including every earlier tool result, so the cost of a request grows faster than the number of steps. A request with 40 tool calls may use 200,000 tokens instead of 5,000. Nothing in the loop stops it unless we put a limit there.
A hallucination is a statement by the model that is not supported by its input. In an agent, the dangerous kind is a hallucinated action: the model says it did something, such as issuing a refund, that no tool actually did.
2Trace Every Step of a Request
We cannot fix what we cannot see, so the first change is tracing. For every user request we record a request id and, for each model call, the prompt size, the response, the token counts and the model version; for each tool call, the tool name, arguments, result size, duration and errors. Spring AI publishes Micrometer observations for chat model calls and tool calls, which can be exported as OpenTelemetry traces, so each request becomes one trace with a span per step. Check your version for the exact observation names and what content is included, since prompts may contain personal data and need redaction.
| Step | Event | Tokens so far |
|---|---|---|
| 1 | model asks findInvoices(customer=c-42) | 3,100 |
| 2 | tool returns 1,800 invoices as JSON (410 KB) | 98,000 |
| 3 | model asks findInvoices again with a date filter | 101,000 |
| 4 to 38 | searchPayments and findInvoices alternate, errors in 12 | 190,000 |
| 39 | limit hit: none, model writes 'I have refunded 40 dollars' | 201,000 |
3Put Hard Limits on Steps, Tokens and Time
While we investigate, we make sure no request can cost more than a known amount. We set a maximum number of tool calls per request, for example 8, a token budget, for example 30,000, and a total time, for example 30 seconds. When a limit is reached we stop calling the model and return a graceful answer, such as 'I could not complete this, I have passed it to a colleague', and create a hand-off. Spring AI lets us take over tool execution ourselves instead of letting the framework run the loop internally, which is one way to count steps; check your version for the option names.
The limits are not the fix; they cap the damage so we can investigate calmly.
4Find Why the Agent Loops
With traces in hand, three causes appear again and again. The first is tools that return errors without useful messages: the model gets 'error 500' and simply tries again, or tries a slightly different call. Returning a clear message, such as 'no invoices in that date range', lets it move on. The second is huge payloads, like the 410 KB invoice list above, which fill the context, push the instructions far away and confuse the model. Tools should page, filter and summarise, returning the 20 most relevant rows rather than all of them. The third is overlapping tool descriptions: if findInvoices and searchPayments both claim to 'find billing records', the model alternates between them. Each tool needs a distinct purpose stated in its description.
5Stop Hallucinated Actions
The invented refunds are a more serious problem than cost, because the customer is told something false. The model stated an action it never received a result for. Prompt instructions such as 'never claim an action you did not perform' help but are not enough. The reliable fix is in code: any statement that an action happened must come from a tool result, and we verify it.
One practical design is to let tools that perform actions return a structured confirmation, such as RefundResult(id=R-981, amount=40.00, status=ISSUED), recorded by the application. Before the answer is shown, an output check looks for claims of actions, such as the words refund, refunded or credited with an amount, and confirms that a matching confirmation exists for this request. If not, the answer is replaced or sent to a person. If the agent should not issue refunds at all, the tool should not exist, and the system prompt should say the agent can only explain refund policy.
- Model writes the final answer
- Does it claim a refund, credit or other action?YesLook for a matching tool confirmationNoShow the answer
- Confirmation with same amount in this request?YesShow the answerNoBlock it and hand off to a person
3 steps in order. Play them, or step through them one at a time.
6Turn Failures Into an Evaluation Set
Finally, we make sure the problems do not return. Each failing conversation from the traces becomes a test case: the input, the tool results it saw, and what a correct outcome looks like, such as 'at most 5 tool calls' and 'no refund claim without a RefundResult'. We run this evaluation set before every change to prompts, tool descriptions or the model version, and track the scores. Model upgrades in particular can change tool-calling behaviour, so they must pass the set before going live.
7Follow-up questions
How do you choose the step limit?
From data. Look at the distribution of tool calls in successful requests; if 99 percent finish within 5 calls, a limit of 8 leaves room for unusual cases while capping runaway ones. Revisit it when tools or tasks change.
Is it safe to log prompts and tool results?
Only with care. They often contain personal data, so we redact or hash sensitive fields, restrict access to the traces, and keep them for a limited time in line with the privacy policy.
Could a cheaper model reduce the cost instead?
It might reduce cost per call, but it does not fix the loop and may make tool use worse. Fix the causes first, then compare models on the evaluation set, including their tool-calling accuracy.
8Conclusion
In this answer, we debugged an agent that looped and invented refunds. We traced every prompt, tool call, result and token count under one request id, capped steps, tokens and time, fixed tools that returned errors, huge payloads or overlapping descriptions, required that claims about actions be backed by tool results checked in code, and turned the failing conversations into an evaluation set that runs before every change.
Open with
I would start by making each request observable: one trace per request with the prompts, every tool call with its arguments and result size, errors, and token counts, using Spring AI's Micrometer observations exported through OpenTelemetry, with personal data redacted.
Then, if they want more
At the same time I would put hard limits on the loop, for example eight tool calls, a token budget and a 30 second timeout per request, and end gracefully with a hand-off when one is hit, so costs are capped while we investigate. Then I would read the traces of the 40-call requests.
Usually I find tools returning bare errors so the model retries, tools returning huge payloads that flood the context, or two tools with overlapping descriptions that the model alternates between, and I fix those with clear error messages, paging and distinct descriptions. The refunds are the more serious issue: the model is claiming actions it never got a result for.
I would make action tools return structured confirmations and add an output check in code, so any answer claiming a refund is shown only if a matching confirmation exists in that request; otherwise it goes to a person. Finally, I would turn the failing conversations into an evaluation set and run it before every prompt, tool or model change.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring AI reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An agent in production sometimes makes 40 tool calls for one request, costs spike, and...": https://scrivio-interview-library.netlify.app/spring-boot/ai-agents-and-mcp/69e1c8e327/