Skip to content
I write agents as distributed systems

The hard part of an agent isn't getting it to run, but being able to converge after it goes wrong

The first Agent that went live had a problem on day one. It called the inventory query API, which returned 200 with an empty array. The model read “can’t find it” as “no restrictions,” and went on to recommend a bunch of items that shouldn’t have been sold.

The code threw no errors, the logs were clean, and the pipeline was connected.

Since then I’ve stopped trusting the word “working.” This is also where Agents differ most from ordinary services: their failures usually don’t show up as exceptions.

Planning and execution must be written separately

The upside of ReAct is that each step can adjust based on observations; the downside is that it has no global view. Once there are many steps, the model probes locally over and over: it calls the same tool with the same parameters repeatedly, gets identical observations, and calls it again.

Writing “don’t repeat” in the prompt is basically useless. What works is engineering: a hard step limit, injecting a system prompt to force a strategy change when consecutive identical actions are detected, and a timeout for each subtask. These are dumb methods, but they provide determinism. Detecting repetition also can’t just compare strings: if the parameters carry timestamps or random IDs, every call looks different while actually being the same action. I usually normalize the parameters before comparing.

Plan-and-Solve goes the other direction: generate a complete plan first, then execute in batches. It saves tokens and won’t drift midway, at the cost of being hard to turn back once the plan is wrong. It suits tasks with clear steps and dependencies, such as generating reports from a fixed template, or converting a piece of structured data into multiple formats.

I’ve only used Tree of Thoughts in offline scenarios. Expanding multiple branches and evaluating them at each step is absurdly expensive, and the latency doesn’t suit user-facing products. It is indeed effective on puzzle-type tasks, but those tasks don’t require real-time responses anyway.

In real systems I usually mix them: the top layer uses a large model for planning and outputs only a structured step list; the execution layer uses a smaller model for each step, or simply code. Let the model make judgments, and let code handle computation and format conversion.

I once handed the request “help me book the whole trip” directly to a single Agent. It flip-flopped between budget and preferences, and the hotel it had just settled on in one step was overturned by the transport arrangement in the next. The problem wasn’t the model’s capability; the task itself requires fixing constraints before expanding details. Later I changed it so the planning layer first produces a constraint list and the execution layer fills it in item by item, and the stability was immediately different.

Whether a task is decomposed correctly matters more than whether the model is chosen correctly. Each decomposed step must have a clear completion condition; otherwise the Agent can’t tell whether it should move to the next step and can only keep trying. The completion condition is best made checkable: a field exists, a value is within range, a specified number of results was returned.

Intermediate state must be visible. Once the plan gets long, users can only wait for a final result, and when something goes wrong they don’t know where it’s stuck. I prefer pushing step status to the frontend—even just “checking inventory”—which greatly improves both experience and debuggability. This counts as engineering cost, but it’s cheaper than guessing afterward.

Anything that can be computed directly with code, I never leave to the model’s mental arithmetic. Amounts, date differences, sorting, field mapping—all go through deterministic code; the model only decides which function to call and what parameters to pass. Mental arithmetic looks smart, but when it’s wrong there’s no warning, and it’s wrong consistently, which is also hard to cover with tests.

The planning layer’s output is best a verifiable structure, not a paragraph of natural language. If the structure is wrong, just retry; don’t let it proceed with a vague plan. Each step in the plan should declare its dependencies—which can run in parallel and which must wait—so the execution layer has a basis for scheduling.

The cost is heavier upfront design. Writing an Agent that can freestyle is fast; writing a system with separated planning, execution, and validation is much slower. But as long as the task recurs, the debugging time saved later far exceeds this investment.

Multiple Agents are for isolating context

A single Agent can’t handle complex tasks, usually not because it isn’t smart enough, but because too many conflicting instructions are stuffed into the context. Put the code writer and the code reviewer in the same context, and the model struggles to truly find its own mistakes.

Once split, each Agent has its own system prompt, toolset, and context window. The writer only writes, the reviewer only finds problems, and after reviewing, returns conclusions to the orchestration layer. The motivation is much like microservice decomposition: not for sophistication, but so each piece can be changed and evaluated independently.

Isolation must be thorough. When the orchestrator hands a subtask to an executor, it passes only the necessary input, not the entire conversation history. The more it carries, the more easily the sub-Agent is led astray by irrelevant information; and each additional executor adds another share of token cost.

The cost is also real. Token consumption doubles, the pipeline gets longer, debugging gets harder by a notch, and you have to handle state inconsistency between Agents—two Agents understand the same data differently, the aggregated result is self-contradictory, and it’s hard to tell who’s wrong.

So I usually ask first: does this task really need multiple roles? If it’s just that the context is a bit long, try summarizing and trimming irrelevant history first; if it’s just that there are too many tools, try grouping and routing first. Splitting is only worth it when different parts need conflicting instructions, or need different permission boundaries. Splitting for the sake of a good-looking architecture will make life painful for whoever maintains it.

For orchestration I prefer a master-worker structure: one orchestrator understands requirements, splits tasks, and merges results; multiple executors work in parallel; executors don’t communicate directly, and all information flows through the orchestration layer. The topology is clear, and when something goes wrong you can pinpoint a specific call. Letting Agents converse freely with each other looks flexible, but in practice it’s hard to reproduce and hard to guarantee convergence.

Routing is another place that’s easy to do sloppily. Using a large model for intent classification is accurate but adds an inference per request; using vector matching against capability descriptions has low latency but is insensitive to vague intents. My approach is to coarse-filter with vectors first, hand the low-confidence ones to a small model, and if neither is sure, ask a follow-up question rather than guessing.

If routing is wrong, every subsequent step is wrong, and wrong very plausibly—the Agent very earnestly does what the user didn’t ask for. I wrote that sentence down after an online incident.

For state management, a linear chain quickly becomes insufficient. Real collaboration has loops: write, review, revise, review again. A graph structure expresses this more naturally: share one state object, and conditional edges decide where to go next. Circuit breakers like “maximum rounds” also become easy to implement, since they’re just a termination condition on the graph.

The granularity of splitting must also be restrained. I’ve seen designs that cut a task into a dozen roles, each doing a one-sentence job, until the orchestration cost exceeds the task itself. My current standard is: split only when the context truly conflicts, or when different tool permissions are truly needed.

Tool definitions are interface design

The stability of Function Calling depends 80% on how the tools are defined, not on how strong the model is.

The function description is itself part of the prompt. Writing “search data” is as good as writing nothing; writing “query the last thirty days of orders by user ID, excluding cancelled ones” lets the model judge whether to call it. Constrain parameters with strong types, which blocks most invalid input. Put numeric ranges, date formats, and enum values into the schema; don’t expect the model to remember them.

Tools should be atomic. A universal tool taking twenty parameters has a far higher error rate than three small tools taking five parameters each. List enum values fully in the description, and do another fuzzy match on case and whitespace at the code layer—model output enums often come with quotes or inconsistent casing.

Tool count also needs to be controlled. Hand the model several dozen tools at once and it will hesitate between similar ones, or just pick the one that looks most general. My experience: keep tools exposed in a single turn to under ten, group the rest by scenario, and let a router decide which group to load. This is both an accuracy problem and a context-cost problem.

Parallel calls are easy to overlook. When several tools have no dependencies between them, have the model emit multiple calls at once and let the system execute them concurrently—end-to-end latency goes from additive to max. The precondition is that these tools are idempotent, or at least tolerate repeated execution; otherwise one retry produces two side effects.

Return values should carry status. If you only return data, the model can’t tell whether the step actually succeeded; return “succeeded but 0 results” and it knows to change strategy. This design is more effective than most prompt tricks, because it separates “no results found” from “query failed.”

Don’t throw exceptions straight to the user after an error. Convert the error message into natural language and feed it back to the model as an observation, letting it fix its parameters and retry. This reflection loop is especially effective on parameter-format errors: with a wrong date format, the model can usually correct it in one shot after seeing the error.

But the loop must be bounded. A maximum retry count is mandatory—terminate once exceeded—otherwise an unstable API can burn a large number of tokens while the Agent loops.

Error messages also need cleaning. A full stack trace is long and contains paths; stuffing it back in both eats context and distracts. Keeping only the error type and key hints works better.

Errors also need classification. Invalid parameters, insufficient permissions, resource not found—retrying these three is pointless and the strategy should change directly; only timeouts, rate limits, and connection interruptions are worth backing off and retrying. Handle them all the same way and the Agent will repeatedly burn cycles on calls destined to fail.

When a tool is unavailable, besides reporting the error, explicitly tell the model “this tool is currently unavailable”—otherwise it will try again with different parameters. Degradation should also be designed in advance: if the primary search API is down, switch to a backup source or go straight to the knowledge base—this decision is best written in config, not left to the model to improvise.

Security boundaries are the part I’m least willing to compromise on. Tools that write, pay, or delete must have human confirmation, or at least an independent permission check—you can’t rely on a line in the prompt saying “please be careful.” Prompt-injection defense belongs at this layer too: tag the source when external content enters context, run whitelist validation on tool parameters before execution, and don’t let the model concatenate SQL or command lines directly.

Memory and operations are the real long-term cost

Stuffing the entire conversation history into a vector store is the most common lazy approach, and also the least effective.

Vector retrieval is good at semantic association, not precise state. A user’s membership tier, current order number, or allergy mentioned last time—these are fields that need overwriting updates, not text that needs similarity matching. Vector stores append writes; after the user changes their story, the old information stays in the recall pool, and the model can’t tell which entry is the current state.

My current layering is this: the most recent few turns are kept verbatim in a sliding window so references resolve; older content is periodically compressed into summaries, accepting detail loss; key facts go into structured storage, updated during conversation via an extraction side chain.

Summaries themselves hallucinate—compression can turn “possibly” into “definitely.” So summaries are only used for background recall, not as a factual basis.

Structured memory is especially obvious in scenarios requiring hard constraints. If the user mentioned an allergy once a month ago, recommendations must hit it. Relying on vector similarity to get lucky is inappropriate here; the cost of one structured lookup is nearly zero.

The price is maintaining extraction logic and handling conflicts: the user first says they like coffee, then says they quit—who overrides whom, how are timestamps set. I’m still figuring this out; currently I only use the simple rule “later writes override earlier ones,” which occasionally errs.

Memory also needs forgetting. What to remember, for how long, when to actively delete—right now it’s basically guesswork. Remember too much and it pollutes context; remember too little and the user feels it has no memory. This isn’t really an engineering problem, more a product problem, and I don’t have an answer yet.

Retrieval timing also needs design. Don’t query the vector store every turn—that raises latency and pulls in irrelevant historical fragments. I split it into two cases: for user preferences and state, query structured storage every turn, which is cheap; for “what we talked about before,” query only when the user explicitly reviews or the topic switches.

After launch, what actually takes time isn’t making it smarter—it’s making it observable.

A single request may involve a dozen or more model and tool calls; without traces you’re just guessing. I want to see the input, output, latency, token count, and raw tool return for every step. Especially tool returns—many cases of “the model is hallucinating” turn out to be the API returning dirty data.

I only watch a few metrics: end-to-end latency, per-session cost, tool error rate, loop count, and the proportion requiring human takeover. The last one is the most telling—it maps directly to whether the product can scale.

Cost needs a hard circuit breaker. The token cap per session, the daily budget per user, and the maximum steps per task—these three thresholds must live in code, not in the prompt. When an Agent gets stuck in a loop it can’t notice; all it sees is “task not yet complete.” By the time the bill arrives, it’s too late.

Evaluation is done in three layers. The bottom layer is deterministic checks—is the format right, are the fields complete—fastest to run; the middle layer uses model scoring to see whether the task is complete and the tools chosen correctly; the top layer is manual spot checks plus online metrics. The first two layers go into continuous integration, the third is done weekly.

The hardest part is the evaluation cases themselves. An Agent’s execution path isn’t unique—the same task can use different tool combinations and all be correct. Comparing against a fixed path will judge correct behavior as wrong; you can only fall back to checking whether the final state and key constraints are satisfied. I haven’t found a particularly clean solution to this yet.

Releases should be canary. Model non-determinism means the same code behaves differently on different traffic; if something breaks after a full switch, rolling back just rolls back to another non-deterministic version. My approach: route a portion of traffic to the new version, watch the human-takeover rate and tool error rate, and scale up only after both stabilize.

Logs need to preserve enough of the scene. Model input/output, raw tool returns, and the prompt version at the time—at minimum you must be able to reconstruct a complete snapshot by request ID. Miss any one and reproduction is impossible. Snapshots also need a retention period, or storage cost will collapse first. Set retention by business risk—keep longer for anything involving money or compliance.

Further reading: Tool calling is a protocol, not a set of function signatures, When context is nearly full, what I compress and what I externalize

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Agent #Engineering Practices #Memory #Tool Calling

Comments