Skip to content

Module 06 · Lesson 6.4

Avoiding Infinite Loops and Unnecessary Agent Handoffs

35 minUpdated 18 Nov 2026Part of Multi-Agent Systems and Orchestration · AI Agent Development
On this page
  1. What you will learn
  2. Why agents pass a case back and forth
  3. Set a handoff limit in code
  4. Detect repeated routes before the limit is reached
  5. Stop the case and hand it to a person
  6. Unnecessary handoffs cost money even without a loop
  7. Try it: a handoff guard in Python
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

Think of a phone call where the first desk says "that is a billing question, let me transfer you", and the billing desk says "that is a delivery question, let me transfer you". You are passed around until you hang up. Nobody was lazy. Each desk followed its own rule, and the rules disagreed.

Agents can do the same thing, and every transfer costs a model call. In this lesson you learn why ping-pong happens, how to stop it with a handoff limit and a cycle check written in code, and how to hand the case to a person with a clear reason. Most of the lesson needs no coding. One short Python example at the end shows the checks working.

What you will learn

  • Explain how agents end up passing a case back and forth.
  • Set a handoff limit and enforce it in code, not in instructions.
  • Detect repeated routes, such as A to B to A, before they cost more calls.
  • Stop a looping case, hand it to a person and record the reason.

Before you start

Why agents pass a case back and forth

A handoff is the moment one agent passes a case to another agent. A loop happens when the case keeps moving without anyone finishing it. The most common shape is ping-pong: agent A hands to B, and B hands straight back to A.

In the Quillfeather Cycles shop, picture a customer who writes: "Is my refund on its way?" The orders_specialist sees the word "refund" and thinks it belongs to the help_specialist, who knows the refund policy. The help_specialist sees that the customer needs an order looked up, and thinks it belongs to the orders_specialist. Neither is wrong. Neither finishes the job.

CauseWhat it looks likeFix
Overlapping jobsTwo specialists both think the other one owns a question.Give each kind of question exactly one owner. See the routing table in the pattern lesson.
Vague instructions"Hand over if you are not sure" makes every unsure agent pass the case on.Say what to do when unsure: answer with what you have, or hand to a person.
Missing informationThe case needs an order number the customer never gave, so everyone passes it on.Ask the customer. Do not hand off for something only the customer can supply.
No limit in codeNothing stops the cycle, so it runs until money or time runs out.Count handoffs in the orchestrator and stop at a fixed number.
Most loops start with unclear ownership. The limit in code is the safety net for the rest.

Set a handoff limit in code

The simplest protection is a counter. The orchestrator, the plain program that moves cases between agents, adds one each time a handoff happens. When the counter reaches the limit, it refuses further handoffs.

In this program the limit is MAX_HANDOFFS = 3. Think of it as the number of times a parcel may change hands before someone checks why it is still not delivered. It works like the MAX_ROUNDS limit on a single agent's steps from the first modules, but it counts handoffs between agents.

How do you choose the number? Count how many handoffs your normal, successful cases need. If the longest happy path uses two, a limit of three leaves one spare. Review the number again when real traces show cases that were stopped.

Detect repeated routes before the limit is reached

A limit of three still allows two wasted handoffs in a ping-pong case. A cycle check stops it sooner. It looks at the trail, the list of agents that have held the case so far, and refuses a handoff that only repeats earlier work.

Same agent twice in a row
The case is handed to the agent that already has it. This is almost always a bug or a confused agent. Stop it.
Going back to the previous agent
The trail shows A, then B, and B now wants to hand to A. This is the ping-pong shape. Stop it.
Trail
The ordered list of agents that have held the case, for example supervisor, then orders_specialist, then help_specialist.

Is returning to the previous agent ever correct? Sometimes. A specialist may fetch one fact and legitimately send the case back to the supervisor. Treat such return trips as a design choice: allow them only by a named rule, such as "the supervisor may receive a finished result", and never allow two specialists to bounce a question between themselves.

The checks before every handoff
  1. Agent asks for a handoff

    It names the next agent

  2. Limit check

    Fewer than MAX_HANDOFFS so far?

  3. Cycle check

    Not the same agent, not going back?

  4. Allowed

    Add to the trail, count one handoff

All three checks run in the orchestrator, before the next agent is called.

Stop the case and hand it to a person

When a check fails, the orchestrator must do something useful. It should not crash, and it should not keep guessing. The safe choice is to stop the agents and hand the case to a person, the same way the agent hands over for refunds or safety problems.

  • Set the case route to person, using the case record from the earlier lesson.
  • Add a note that says why, for example "orchestrator: stopped, going back to the previous agent". Notes are append-only, so the reason stays in the record.
  • Keep the work done so far in the case, so the person does not start from zero.
  • Tell the customer honestly that a team member will follow up. Use the needs_person status from the reply contract.

Logging the reason matters as much as stopping. Later you will count how often each reason appears. Many "limit reached" stops point to a vague instruction. Many "going back" stops point to two specialists with overlapping jobs.

Unnecessary handoffs cost money even without a loop

A case that ends after one wasted handoff is not a loop, but it is still a cost. If every customer message goes through the supervisor, then to a specialist, then back for a final check, you pay for three model calls where one might do.

  • Handoff only when the tools differ. If the current agent already has the tool it needs, it should finish the job itself.
  • Do not hand off to ask a question the customer can answer. Ask the customer directly.
  • Skip the supervisor for obvious cases. A message containing a valid order id can go straight to the orders specialist by a plain code rule, with no model call at all.
  • Count handoffs per task. If the average is higher than your design expected, look at the traces for steps that add nothing.

Try it: a handoff guard in Python

This script has no model. Each case is a small table saying which agent would hand the case to which next. The guard decides whether each handoff may go ahead. Four cases run: a normal one, a ping-pong, a repeat and a long chain.

Pythonhandoff_guard.py
MAX_HANDOFFS = 3


def check_handoff(trail, next_agent):
    """Return a reason to stop, or None if the handoff may go ahead."""
    if len(trail) - 1 >= MAX_HANDOFFS:
        return "handoff limit reached"
    if trail[-1] == next_agent:
        return "same agent twice in a row"
    if len(trail) >= 2 and trail[-2] == next_agent:
        return "going back to the previous agent"
    return None

Part 1: the limit and the checks.

Pythonhandoff_guard.py
def run_case(case_id, script):
    trail = ["supervisor"]
    while True:
        next_agent = script[trail[-1]]
        if next_agent == "done":
            return f"{case_id}: finished after {len(trail) - 1} handoffs ({' > '.join(trail)})"
        reason = check_handoff(trail, next_agent)
        if reason:
            return f"{case_id}: STOP, {reason}. Handed to a person. Trail: {' > '.join(trail)}"
        trail.append(next_agent)


cases = {
    "C-001": {"supervisor": "orders", "orders": "done"},
    "C-002": {"supervisor": "orders", "orders": "help", "help": "orders"},
    "C-003": {"supervisor": "help", "help": "help"},
    "C-004": {"supervisor": "orders", "orders": "help", "help": "check", "check": "audit", "audit": "done"},
}
for case_id, script in cases.items():
    print(run_case(case_id, script))

Part 2: the loop that follows a case, and four test cases. Add it below part 1.

What each part does

  • MAX_HANDOFFS = 3 is the limit. A capital-letter name is the usual way to mark a setting that never changes while the program runs.
  • trail is a list that starts with supervisor. len(trail) - 1 is the number of handoffs so far, because the supervisor holding the case at the start is not a handoff.
  • trail[-1] is the last item, the agent holding the case now. trail[-2] is the one before it.
  • check_handoff returns a reason as text when something is wrong, or None when the handoff is fine. Returning a reason, instead of only True or False, gives you something to log.
  • script is a dictionary that says who each agent would hand to. "done" means the agent finished the case. In a real system a model or a tool decides this.
  • The while True loop asks for the next agent, runs the checks, and either stops with a reason or adds the agent to the trail.
OutputCaptured from a real run
C-001: finished after 1 handoffs (supervisor > orders)
C-002: STOP, going back to the previous agent. Handed to a person. Trail: supervisor > orders > help
C-003: STOP, same agent twice in a row. Handed to a person. Trail: supervisor > help
C-004: STOP, handoff limit reached. Handed to a person. Trail: supervisor > orders > help > check

Read the results one by one. The normal case finishes. The ping-pong stops after two handoffs, before the limit, because of the cycle check. The repeat stops immediately. The long chain has no repeats, so only the limit stops it, after three handoffs. Each stop names its reason.

In the lab at the end of this module you add the same guard to a real supervisor and write each reason into the case notes.

Conclusion and your next step

Loops usually start with unclear ownership, and unnecessary handoffs quietly add cost. Give each kind of question one owner. Then add the safety net in code: a handoff limit, a cycle check, a stop that goes to a person and a logged reason.

Your next step: list the handoffs your own multi-agent design allows and mark any pair that could bounce a case between them. Then continue to Orchestration, Concurrency and Task Coordination, where agents work at the same time and you must stop them overwriting each other.

For related ideas, read Tool Errors, Retries, Timeouts and Idempotency on bounding retries, and Budget Limits, Rate Limits and Runaway Execution Controls in the next module.

Common errors and how to fix them

Two specialists keep handing the same case to each other.

Why it happens: Their jobs overlap, and each instruction says "hand over if the question is not yours".

Fix: Give every question type one owner, and tell each specialist to answer or hand to a person when unsure, never to hand to the other specialist.

The handoff limit is in the instructions only, and a case still runs for dozens of calls.

Why it happens: A model can lose count or ignore a request. Instructions are not enforcement.

Fix: Count handoffs in the orchestrator and refuse the next one at the limit.

Stopped cases reach a person with no explanation.

Why it happens: The orchestrator stopped the agents but did not write down why.

Fix: Append a note with the reason and the trail to the case before handing it over.

Every customer message is routed through the supervisor, even simple ones.

Why it happens: No rule sends obvious cases straight to the right specialist.

Fix: Add a plain code rule for clear cases, such as a valid order id, and keep the supervisor for unclear ones.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Test a handoff guard on your own cases

Take handoff_guard.py and add two new cases to the cases dictionary: one that should finish with two handoffs, and one that ping-pongs between help and orders but starts at help. Predict each result before you run the script.

You will need

  • The handoff_guard.py script from this lesson.
  • MAX_HANDOFFS = 3.
  • The agent names supervisor, orders and help.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • A finishing case ends when an agent maps to "done".
  • Remember the trail starts with the supervisor, so the check compares against it too.
  • With a limit of 2, the longest finishing case may now be stopped.
Show a model answer

One valid pair is: "C-005": {"supervisor": "orders", "orders": "help", "help": "done"}, which finishes with two handoffs and the trail supervisor > orders > help. And "C-006": {"supervisor": "help", "help": "orders", "orders": "help"}, which stops at the third request because the trail is supervisor, help, orders and the next agent, help, is the previous one. With MAX_HANDOFFS set to 2, C-005 still finishes, because it needs exactly two handoffs, but C-004 from the lesson now stops one step earlier at the limit. The exercise shows why the limit should sit just above your longest normal case.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Where should the handoff limit be enforced?
    Show the answer and explanation

    Answer: B. A counter in code cannot be forgotten or argued with. Instructions feel natural and are worth having, which makes the first option tempting, but a model can lose count or drift, so they cannot be the only protection.

  2. 2.The trail so far is supervisor, then orders_specialist. The orders specialist asks to hand the case to the supervisor. What does the cycle check do?
    Show the answer and explanation

    Answer: B. Going back to the previous agent is the ping-pong shape. The first option checks only the current agent, which is the tempting mistake. The check must also look at who held the case before.

  3. 3.A looping case is stopped. What should happen next?
    Show the answer and explanation

    Answer: B. A person can finish the job, and the note tells them what went wrong. Raising the limit hides the cause and spends more money, and a raw error leaves the customer without help.

Frequently asked questions

What is an infinite loop in an AI agent?

It is when an agent or a group of agents repeats the same steps without finishing. In a multi-agent system the usual form is two agents passing a case back and forth. In practice it ends when money, time or a limit in your code runs out, so you need that limit before you go live.

How many handoffs should I allow?

Count the handoffs your normal successful cases need and add one or two. For a small system with a supervisor and two specialists, three is a sensible start. Check your traces later and adjust the number if good cases are being stopped.

Can the model detect its own loop?

You cannot rely on it. A model may notice a pattern sometimes, but it can also repeat the same mistake with full confidence. Detect loops with plain code that looks at the trail, and treat anything the model says as extra help.

Is it ever fine for an agent to hand a case back?

Yes, when a rule names it. For example, a specialist may return a finished result to the supervisor. The problem is an open-ended return, where two agents may keep sending the same question to each other. Allow named returns and block the rest.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.