Writing

Tool or Sub-Agent? A Decision Tree Forced Out of Me by Four Bugs

2026-07-17

13 mins to read

Share article

In the last round of self-testing before handing the feature to QA, I played the visitor and walked through the appointment flow from start to finish. I wanted a treatment on Saturday afternoon, and the AI enthusiastically recommended a specialist named Anna the whole way through: "Anna is free on Saturday afternoon, and this treatment is one of her specialties." Fine, I said, let's go with her. The AI replied: "You're all booked!"

I opened the admin console. The name on the appointment was Bella.

It took a dig through the logs to see what had happened. At the submit step, the API returned a list of available specialists in which Anna came later, and the model simply picked whoever was first. What gets promised in the conversation is one thing, and what gets submitted is another. Nothing forced the two to agree.

My first reaction was still that the prompt wasn't tight enough and one more sentence would fix it. Then I kept testing, and the problems kept coming. In a fresh session, the AI got the available slots and placed the booking without ever collecting my contact details, even though the prompt said in plain words "collect the name and phone before booking". In another scenario I said "I'll arrive at 14:00" and was rejected outright: the backend schedule was a single row covering 13:30–15:00 that only accepts the row's start time, 14:00 was not a start time, and what the visitor experiences is "there's clearly a free slot, yet I can't book it". And one that wasn't serious but looked bad: before booking, the AI had a habit of querying the slots once more "just to confirm", so the availability card showed up twice in the conversation.

Add the booking where I asked for Anna and got Bella, and that's one afternoon of self-testing and four bugs. All of them were behavioral. Not one was an API error.

The architecture of the appointment feature at the time was very straightforward: check availability, create the appointment, write back a summary. Three tools attached directly to the main agent. The main agent's system prompt was simultaneously in charge of persona, language rules, emoji usage, and three rules of appointment discipline on top.

A prompt can lower the odds, but it can't give a guarantee

The first round of fixes naturally took the cheapest route: edit the prompt. The rather soft "ideally collect the visitor's name and phone" was upgraded to MUST, bolded, and moved to the top of the list. It worked, in the sense that the bug reproduced noticeably less often. But less often is not never. A prompt's hold on behavior is probabilistic; however harsh the wording, it only pushes the violation rate down, never to zero, and after a few more rounds of conversation I would still hit a case of "got the slots, booked right away". One bad phrasing in chat does no harm. Booking is a write operation, and one miss is a real order with no contact details on it. That kind of place needs a 0-or-1 guarantee, not a score of 95.

This approach also has a hidden cost that I only saw clearly after a few rounds: the model isn't short on intelligence, it's that one brain is in charge of too many things. Instruction adherence gets diluted as the number of concerns in the prompt grows. Bolding the contact-details rule amounts to turning down the volume on the specialist-selection rule. Bug fixing turns into whack-a-mole: press one down and another pops up.

What needed fixing wasn't any single instruction. It was the structure.

Before touching code: a sub-agent is a tool too

The direction of the refactor wasn't hard to come up with: move appointments out as a whole block and give them a brain of their own. But before I started, there was one concept I was forced to get straight.

Discussions of multi-agent architecture tend to describe "tools" and "sub-agents" as two parallel things. Down at the code level, though, in the main agent's eyes a sub-agent is just a @tool: it sits in the same tool list and goes through the same function calling protocol. The main agent has no idea, and has no need to know, whether three lines of code or another LLM sits behind that tool.

So the precise way to ask "tool or sub-agent" is really this:

Inside this tool's implementation, is there a piece of deterministic code, or is another LLM hidden in there, with its own prompt, its own context, and its own loop?

Here are the two execution paths side by side:

DimensionPlain toolSub-agent
ImplementationDeterministic codeAnother LLM (plus its own tools)
Where instructions liveOnly the docstring (weak constraint)A dedicated system prompt (strong constraint)
Where intermediate output goesStraight into the main conversation history, costing tokens foreverStays in the worker's temporary context and is destroyed with the task
Decision structureOne brain makes every decisionLayered: the supervisor hands out work, the worker decides how to do it
Extra cost0 LLM calls+1 to N LLM calls, plus one hop of latency
Iteration radiusChanging behavior means touching the main prompt, with global regression riskOnly the worker prompt changes; the main conversation notices nothing

The last row of that table is both the root cause of those four bugs and the cure.

The refactor: the main agent only hands out work

After the refactor, the main agent no longer carries the three appointment tools. It carries a single dispatch tool, handle_appointment(request). Its docstring is itself a "dispatch contract" that forces the main agent to pack up, in one go, the information scattered across the conversation:

@tool
async def handle_appointment(request: str) -> str:
    """Handle anything appointment-related: check availability, create
    a booking, or update the appointment summary.

    Hand off ONE clear English request carrying everything known from
    the conversation: the concrete date (convert relative dates first)
    and time; the specialist by name whenever a specific one came up —
    or an explicit note that the visitor said anyone is fine; the
    visitor's name / phone if collected; and a 2-3 sentence summary
    of the visitor's needs for the store staff.
    """
    task = task_mgr.create(request)
    await run_booking_subagent(task)   # awaited in the same turn; returns only when the worker is done
    return task.result                  # only the compressed factual report goes back to the main conversation

On the worker side I didn't bring in a heavy framework. It's a small hand-written ReAct loop (the LLM picks a tool, the tool runs, the result is fed back, the LLM thinks again) plus a step budget:

_MAX_LLM_STEPS = 5   # check slots → create → final report fits in this; guards against runaway loops

async def run_booking_subagent(task):
    messages = [
        SystemMessage(content=BOOKING_WORKER_PROMPT),  # dedicated prompt
        HumanMessage(content=task.request),            # only the task description; no conversation history
    ]
    for _ in range(_MAX_LLM_STEPS):
        ai = await worker_llm.ainvoke(messages)
        if not ai.tool_calls:               # no more tool calls = the final report
            task.result = ai.text
            break
        messages.append(ai)
        for tc in ai.tool_calls:            # tool results are fed back only into the worker's own context
            out = await tools[tc["name"]].ainvoke(tc["args"])
            messages.append(ToolMessage(content=out, tool_call_id=tc["id"]))
    else:
        # budget exhausted while still picking tools: return a fallback report
        # the main agent can phrase, rather than coming back empty-handed
        task.result = ("Booking task did not complete within the step budget; "
                       "suggest the visitor contact the store directly.")

The full path of one booking:

Only after it had been running in production for a while did the real value of this refactor gradually show, and it went beyond "the bugs are fixed".

The raw response of a slot query is a large JSON of "many specialists × many time ranges". In the direct-attach days, that blob entered the main conversation history permanently as a ToolMessage, and every later turn paid tokens to carry it. Now it lives only in the worker's one-off context and is destroyed when the task ends. All that comes back to the main conversation is a single line: "Anna is available at 14:00 on Saturday, booked, id=xxx".

The behavioral discipline of booking (don't query slots before booking, don't submit without contact details, how to read the specialist signal) moved wholesale into the worker's own system prompt, and the three appointment bullets in the main agent collapsed into one dispatch guideline. I tuned booking behavior several more rounds after that, each time touching only the worker's prompt, and the persona and language style of the main conversation never regressed once. The blast radius is locked inside the worker, and that is the most valuable thing the refactor bought.

There is one more, less visible layer: the act of packing the task description is itself an inventory of information. Has the date been converted to an absolute one? Is there a specialist signal? Have the contact details been collected? Whatever is missing is exposed at packing time, rather than blowing up at submit time.

The worker can't see the conversation history, so there has to be code that says "no"

The sub-agent pattern has a structural risk that should be stated openly: the worker can't see the conversation history. If the main agent, while packing, drops the phone number the visitor mentioned five turns ago, the worker has no way of ever knowing. This is an inherent flaw of free-text dispatch. "Writing a stricter prompt" can only make it rarer, never seal it off, and I had already paid the tuition for that lesson.

So every hard constraint was pushed down into deterministic code. However freely the worker improvises, if the code doesn't let it through, nothing gets submitted:

# Gate 1: specialist selection. With no explicit signal (a given id / an explicit
# "anyone is fine") and several people available, never pick silently. Return the
# candidate list and bounce it back so the main agent asks the visitor.
if not specialist_id and not any_specialist and len(available_at_time) > 1:
    return {
        "success": False,
        "needs_specialist_choice": True,
        "specialists": [{"id": sp_id, "name": sp_name} for ...],
    }

# Gate 2: contact details. Intercept after the slot and specialist have passed
# validation and before submitting. The bounce carries the fact that "this time is
# confirmed available", so the main agent can mention it when asking for contact details.
if not customer_name.strip() or not phone.strip():
    return {
        "success": False,
        "needs_contact": True,
        "verified_available": True,   # availability already verified; don't waste it when following up
        "date": date, "start_time": start_time,
    }

# Gate 3: time alignment. The backend schedule only accepts a row's start time, but a
# visitor saying 14:00 shouldn't be rejected. Snap to the free row that covers it (13:30)
# and write the visitor's actual arrival time into the note for the store staff.
if booked_start != start_time:
    note += f" Customer plans to arrive at {start_time}."

Count them off against the four bugs from the beginning. Silently swapping the specialist: sealed by gate 1. Skipping contact details: sealed by gate 2. The rejected 14:00: resolved by gate 3. The card showing twice: handled by one rule in the worker prompt, "for a booking task, submit directly; the tool validates on its own; do not query slots first". That rule is followed reliably precisely because the worker's prompt does this one thing only.

The prompt guides, and the code says "no". That is the precondition for free-text dispatch to work safely.

The knowledge base: is a one-step job worth another layer?

Putting appointments behind a sub-agent makes obvious sense: multiple steps, dependencies, fallbacks. What actually made me hesitate was knowledge base retrieval. It is a single step: pick a query and search the vector store. Why not attach knowledge_retrieve(query) straight to the main agent and save an LLM call?

In the end I wrapped it in a layer anyway, as a "single-shot sub-agent": the worker calls the LLM exactly once to translate the goal given by the main agent into retrieval queries (several can run in parallel), and after retrieval it returns the factual digest as is, without even a second summarization pass.

async def run_knowledge_subagent(task):
    # exactly 1 LLM call: decide which queries to send
    ai = await worker_llm.ainvoke([
        SystemMessage(content=KNOWLEDGE_WORKER_PROMPT),  # prompt dedicated to retrieval engineering
        HumanMessage(content=task.goal),
    ])
    facts = []
    for tc in ai.tool_calls:          # one decision can fan out into several parallel retrievals
        out = await tools[tc["name"]].ainvoke(tc["args"])
        facts.append(out)
    task.result = "\n".join(facts)    # the factual digest goes straight back to the main agent, no second summary

What convinced me to pay for that extra LLM call was something that kept happening in the direct-attach days: the main agent tends to use the visitor's own words as the query. A visitor asks in Chinese "can I cancel my appointment?", while the knowledge base documents are in English. The original Chinese sentence doesn't line up with the English documents in embedding space, and the retrieval misses. A goal and a query are two different things, and translating the former into the latter is a craft: one query for a single topic, two parallel queries for a double topic, always phrased in the language of the documents. That body of retrieval know-how deserves a dedicated prompt. And stuffing it into the main prompt? That would be whack-a-mole again, the pit I had just climbed out of.

As for why even the second summary is dropped: the main agent has to compose the final reply from the digest anyway, so having the worker summarize once more is a double rewrite, the classic source of distortion in a RAG pipeline, with an extra call paid for nothing. Retrieved facts should simply be passed up as they are. If I later add a reranker, hybrid search, or a retry with rephrased queries on empty results, all of it happens inside the worker, and the query_knowledge_base(goal) that the main agent sees doesn't change by a single character.

One point that is easy to confuse, while I'm here: "single-shot" limits the number of decision rounds, not the number of queries. In the function calling protocol, one LLM response can carry several parallel tool calls, so the worker can fan out three queries at once from a single decision. What costs money is each round of decision (one LLM call plus a few hundred milliseconds), not each execution.

Conversely, if your knowledge base is monolingual and the user's own words hit as a query, attaching the retrieval tool directly is entirely valid, and the call you save is pure gain. Where the line falls depends on one thing: whether "how to search" involves expertise independent of "how to talk". Only if it does is it worth giving it a brain.

Four capabilities that happen to form a tree

This project has four capabilities: showing the store card, getting the current time, knowledge base retrieval, and appointments. Having stepped on every one of them, I found they cover the whole spectrum, and the selection logic grew into a tree on its own:

Every step from left to right on the tree buys something and adds cost. These are the signals that it is time to move right:

SignalKeep it attached directlyTime to upgrade
Size of tool outputSmall; fine to put straight into the contextLarge raw payload that needs digesting and compressing
Shape of the stepsA single callA chain of tools plus retries and fallbacks
Iteration rhythmTuning it together with the main conversation is fineNeeds frequent tuning independent of the main conversation
Number of tools on the main agentStill modest after adding it (no more than 6 or 7)Tool selection has already started going wrong

The depth of the loop likewise follows the dependencies, not the importance of the task. The multiple queries of a retrieval are independent of each other, so one decision with parallel fan-out is enough, and one more step buys no new information. Booking is a dependency chain of "specialist name → id → submit → fallback on failure", where you must observe a result before deciding again, and only that earns a loop. And the loop must have a step budget and a fallback for exhaustion; otherwise you have merely moved "runaway" from the main conversation into the worker, to run away somewhere else.

This layer of abstraction is billed per call

The muscle memory I built writing frontend code hurt me here for a while: when logic gets complicated, extract a component or a composable, since abstraction is nearly free and costs two more files at most.

Not so in agents. Every sub-agent layer you extract costs real money on every call: 1 to N more LLM calls and one more hop of latency. And that is only the visible bill. There are two hidden ones. First, in the direct-attach days the tool parameters were a strongly typed schema (date must be a date, phone must be present); after dispatch, what the main agent passes to the worker is a piece of free text, so the type constraints moved down a whole layer, and the code gates exist to make up for exactly that. Second, debugging: for any behavioral problem you first have to work out whether the main agent dropped information while packing or the worker went off track while executing. The investigation path gets longer, and none of the supporting pieces, such as task ids and per-step logs, can be skipped.

So every time I feel like extracting a layer now, I ask myself first: do leaner context, isolated iteration, and better decisions, added together, outweigh a cost that is billed per call? If not, I attach the tool directly and leave it at that. No symmetry for symmetry's sake, and no paying for architectural neatness.


This structure is a lightweight version of the same idea behind LangGraph's supervisor pattern: a supervisor turns sub-agents into graph nodes dispatched by a routing function, whereas we wrap the sub-agent inside a tool implementation. It is transparent to the main agent, leaves the main graph untouched, and reuses the existing tool-calling infrastructure. The price is that workers can't talk to each other directly, and everything has to be relayed through the main agent. For a customer service scenario, that is enough.

If one day it isn't, upgrading then won't be too late. Architecture has always been pushed forward by problems. Had it not been for those four bugs, starting with asking for Anna and getting Bella, I would probably still think "the difference between a tool and a sub-agent" was a question that only mattered on paper.