Skip to content
Deploying agents is hard, and the difficulty lies beyond the model

Getting an agent online is hard; the difficulty lies in the shell around the model

When building an Agent that generates weekly reports, the demo phase often goes so smoothly it makes you a little giddy. You enter a project name, and it pulls tickets, digs through commit history, applies a template, and outputs a nicely formatted weekly report.

In its first week live, it wrote an unfinished milestone as completed and sent it to the owner.

Digging through the logs revealed that it had actually “seen” the correct status. It was only during the twelfth round of context compression that this status got summarized away, and the model continued writing based on an earlier version of the information. No errors were thrown throughout the process, and the output read as completely reasonable.

That was the moment I realized the problem wasn’t the prompt. No matter how well-written the prompt is, it can’t make a fact that’s no longer in the context reappear.

What separates demo from production isn’t the model

There’s a saying I agree with: an Agent equals the model plus the harness. The model decides what to do next; the harness ensures that decision is executed continuously, recoverably, and audibly in the real environment.

These two things optimize for different goals. Prompts optimize single-turn quality; the harness manages multi-step reliability. The former determines whether an answer is good; the latter determines whether a task can be finished.

The difference between demo and the real environment isn’t just “messier data.” The real environment has timeouts, permission denials, changes in return formats, tasks interrupted halfway through, and external state modified between two calls. These aren’t language problems; they’re runtime problems. Expecting the model to “remember to retry” in natural language is equivalent to handing execution control to a probabilistic system.

Failure modes are also basically fixed and can be grouped into a few categories: fabricating non-existent tools or parameters; repeatedly searching and summarizing, appearing to work hard but actually making no progress; forgetting the original goal after context overflow; having to start over from scratch after a mid-way failure; and the most troublesome one—output that looks completely correct but has no mechanism to verify it.

That last category is the hardest to detect, because monitoring usually only watches for errors. A system that “successfully produces a wrong result” looks healthy on the dashboard.

I once saw a very typical cascading failure. The task was to add a status page to a service and deploy it to the test environment. It first modified the frontend and casually called a deployment script it shouldn’t have touched; during the fix it entered a loop, repeatedly restarting and repeatedly modifying the same config section; as the session grew longer, compression dropped the constraint that “the test database is read-only”; finally it glanced at the diff and replied “completed,” but never actually visited the page. Four errors, none fatal on its own, but chained together they became an incident.

So when I judge whether an Agent is close to usable, I don’t look at how long the prompt is—I look at four things: whether the context is layered, whether tools have contracts, whether permissions sit at the execution layer, and whether results have external verification. Miss one, and it’s more like a chat box that can call tools.

Add one more: when something goes wrong, can you reconstruct what it actually went through—that’s what I care about most right now. Tool names, parameter summaries, latency, return codes, retry counts, compression trigger times—if these aren’t recorded, troubleshooting is just guessing. I’ve since treated these five signals as the minimum configuration; they’re more useful than any new prompt.

This minimum configuration sounds like observability, but what it’s really calculating is the cost of incident postmortems. I later started storing the complete trajectory of every task, including context snapshots the model saw, raw returns from every tool call, and discarded intermediate results. Storing these isn’t cheap—logs for a long task can reach tens of megabytes—but when something actually goes wrong, you can cut the guessing in half. The more practical benefit is that they can become regression samples: once the same failure is fixed, keep that input, and the next time you change a prompt, swap a model, or adjust a tool, run it first. Without this batch of samples, so-called optimization is basically guesswork.

I also no longer believe that “switching to a stronger model will fix it.” Model upgrades do eliminate a batch of low-level errors, but the gaps in the harness don’t disappear because of that. Permissions, timeouts, idempotency, auditing—these are system properties, not intelligence properties. A sufficiently smart model can still forget the original goal at step two hundred, or mistake a correctly formatted empty result for success. Capability improvements change probabilities, not structure. This is also why I’m reluctant to bet all my resources on “waiting for the next generation of models”: if it arrives, the problem gets a little smaller; if it doesn’t, the system still can’t go live.

Framework selection sits at this layer too. Code-first frameworks are flexible and suit scenarios where the behavior itself is the product, but state persistence, idempotency, rollback, approval, and auditing usually have to be added yourself. Workflow orchestrators are the opposite: controllable processes and strong recovery, but not good at open-ended reasoning. My current view is to first see whether the difficulty lies in “thinking” or “running,” and not expect a universal framework to solve both at once.

Looking back at that weekly report Agent, what actually took time wasn’t fixing the prompt—it was adding three things: a test set that can replay historical inputs, a set of parameter validations for tool calls, and a switch that refuses to continue executing when state is inconsistent. Together these took two weeks to write; fixing the prompt took half a day. This ratio is completely the opposite of what I initially expected.

Context needs to be layered

The most expensive pit I’ve fallen into was stuffing everything into one long prompt.

In the short term the information looks complete, but in the long term it inevitably becomes more expensive, slower, and messier. After thirty rounds, old plans and new states conflict with each other, and the model treats expired arrangements as current facts—and it has no reason to doubt itself.

I later split it into three layers:

The most recent few rounds of conversation and the latest tool results go into short-term context, rolled off once used.

Things that might be useful across sessions but don’t constitute current facts go into retrievable memory.

The state that actually determines the direction of the task is written as a structured object.

The third layer is the easiest to overlook, but it’s the source of truth. Vector retrieval is good at finding “relevant content,” not at answering “where exactly are we now.” If the state already says waiting for approval, but retrieval pulls back “continue deployment” from step four, without an explicit state object the model will just keep going.

The state looks roughly like this—what matters is the fields, not the format:

PLAINTEXT8 lines
1
2
3
4
5
6
7
8
{
"goal": "修复结算服务超时",
"current_step": "run_regression",
"completed": ["read_logs", "patch_retry"],
"blocked_on": null,
"constraints": ["禁止改生产配置", "发布前必须过集成测试"],
"last_error": "payment mock mismatch"
}

Summaries should also be execution-oriented, not reading-oriented. Goal, completed, not completed, reason for the most recent failure, hard constraints—these five must be present. Writing a fluent meeting minutes is useless; what the model needs next round is information that directly determines the action.

Compression and reset are two strategies and must be used separately. Compression is cheap but loses detail, and the way it loses it is uncontrollable; reset is clean but requires the handoff document to be complete enough. My experience is that once a task crosses dozens of rounds, reset plus structured handoff is more stable than repeated compression—the cost is writing an extra “handoff sheet.”

There’s another easily overlooked rule for state objects: writes must converge. When multiple steps update the same field simultaneously, the later write overwrites the earlier one, and if no one is responsible for arbitration, the state becomes self-contradictory after a few retries. My approach is to designate a unique writer for each field; other steps can only read. When a change is truly needed, go through an explicit transition action and record the reason. It looks verbose, but it gives “where are we now” exactly one answer.

Another detail: don’t put long natural-language paragraphs in the state. The goal can be one sentence; constraints are best written as conditions a program can check—for example, “must not modify production config” is worse than “target environment is not equal to prod.” The latter can be blocked directly at the execution layer; the former relies only on the model’s self-discipline. I’ve been burned by this: the more a constraint reads like advice, the easier it is to bypass.

State also expires. A task marked “waiting for approval” three days ago may well have been handled by another process by today. So before every resumption, I first run a state check, pulling the real state from the external system and comparing it. If they disagree, the external system wins. This step is tedious, but it blocks a lot of false progress that comes from “continuing to run on stale state.”

Retrieval itself also needs constraints. High similarity does not mean useful—especially when the query is short, almost anything gets pulled back a little. I generally add two filters: time window and source. Memories older than a certain number of days are down-weighted by default; the model’s own speculation does not enter retrieval; only facts the user has confirmed or that have been externally verified get high weight. The cost is lower recall, but so is the probability of mistaking an old conclusion for the current state.

The bar for writing to memory should also be tightened. The model’s self-repetition, unverified speculation, and the previous round’s plan should not go directly into long-term memory. Only write preferences the user explicitly stated, facts that have been verified, and reusable conclusions. Otherwise retrieval will keep pulling back noise, and the further it runs, the more it drifts.

A more concrete example. A bug-fixing agent has to work across twenty steps: read the requirement, run the tests, locate the file, change the code, run the tests again. If it relies only on chat history, by step fifteen it may have forgotten which test case originally failed, or which files it just changed. The point of a state object is to make these facts independent of memory. After a context reset, a new instance reads the state once and picks up, instead of guessing from a long stretch of natural language.

The cost of this setup is direct: more code, more synchronization points, and every state update can be written wrong. I found it annoying at first and held it off with one long prompt for two months—and ended up spending all of it patching. Layering is not for elegance; it is to save debugging time later.

Tools are contracts; permissions cannot live in prompts

Giving the model one universal tool is the easiest and most dangerous approach.

I have seen systems that expose run_sql directly to the model. It is indeed flexible—it can query anything and change anything. One mistyped parameter and a query becomes an update.

Later I split it into three read-only tools: look up an order by email, look up details by order number, check refund status. Parameters have types and ranges, returns are structured fields, and timeouts and row counts have upper limits. The model can do less, but every call is verifiable, countable, and accountable.

A tool’s parameter definition is not just a manual for the model; it is an execution contract. It blocks dirty input like "limit": "all", and it lets permissions attach to specific fields instead of stopping at sentences like “please operate carefully.”

The cost of splitting tools is also direct: more calls, higher latency, more complex orchestration. Something one universal interface could query in one go may take three rounds after being split into three. I accept this cost, because verifiability matters more than a few hundred milliseconds, and latency can be made up with parallelism and caching—things broken by unauthorized writes cannot be made up.

Permissions must be judged by the execution layer, not negotiated in prompts. Deny by default is safer than allow by default; read-only is safer than writable; narrow tools are safer than all-purpose tools. High-risk actions should be pulled out separately: deploy, write to the database, send external email, push to the main branch—these should all go through human confirmation, not let the model jump straight there.

The tiers are roughly three. Read-only tools are open by default, with row and timeout limits; controlled write tools go through a parameter allowlist, with human confirmation when necessary; high-risk execution tools go into a sandbox, with strong approval and least privilege. Sounds heavy, but what actually goes wrong is usually “give it a shell and let it figure it out.”

Loops are the same. I have seen an agent, trying to fix one failing test, repeatedly run tests, change files, and run tests again, making hundreds of calls in twenty minutes. It is not dumb; nobody told it when to stop. Steps, call count, execution time, cost—if any one exceeds its limit, it should be interrupted, rather than waiting for it to realize on its own that there is no progress.

Sandboxes too. For personal experiments, a container plus a temp directory is enough; once multi-tenancy, executing model-generated code, network access, or real data are involved, stronger isolation should be considered. The cost is higher infrastructure complexity, and I accept it, because the cost of fixing one unauthorized write is far higher.

Retries should be designed as part of the interface. Network jitter, rate limiting, and upstream timeouts are all normal in real environments, and after seeing a failure the model will very naturally call again. If a write operation has no idempotency key, the second call becomes a duplicate order, a duplicate email, a duplicate charge. My approach is to require write tools to carry a key generated by the caller; the server deduplicates by that key and returns the first result for duplicate requests. The model does not need to understand idempotency; it only needs to see a stable return.

Tool returns should also be restrained. Stuffing the entire response body back into context looks information-complete, but in practice it quickly fills the window and mixes irrelevant fields into judgment. My habit now is to have the tool layer trim first: return only the fields needed for this decision, and normalize errors into a few handleable types instead of throwing the upstream stack trace at the model as-is. Stack traces are for humans; the model sees conclusions.

Human confirmation also needs design. A confirmation box that only says “allow execution?” is meaningless; the approver needs to see the parameters of this call, the scope of impact, and whether it can be rolled back after failure. I have seen approval flows degenerate into mindless clicking of agree, because every popup fails to provide the information needed to judge. That is not human negligence; it is the interface turning responsibility into a formality.

Auditing is not a decoration for compliance. Every tool call should record who initiated it, what the parameters were, what was returned, and how long it took—only then, when something goes wrong, can you answer “what did it actually do.” Without this layer of records, troubleshooting degenerates into rereading prompts.

External content should be treated as untrusted. Web pages, search results, READMEs in repositories, ticket bodies—all may hide instructions. If the model reads them and follows them, it is not that the prompt was badly written; it is that the permission boundary was not drawn. So the real defense is at the execution layer: network egress allowlists, command allowlists, write approval—not writing “do not trust web content” in the prompt.

Verification must be externalized; bear the cost yourself

The sentence I trust least is “the model self-checked and confirmed there are no issues.”

If generation and review are in the same context, they most likely share the same set of biases. It will confidently approve its own wrong answer, with ample justification. This is not an attitude problem; it is a structural one.

Verification that can be externalized must be externalized, ordered by objectivity: rule validation, static checks, programmatic tests, real-environment smoke tests, and only then model review. Rule checks are fastest and cheapest, and can only catch explicit problems; tests are closest to the real delivery standard, but require building assets in advance; model review covers subjective dimensions, but cannot be the only gate.

A minimal loop looks like this: generate a small step, run verification, feed the failure signal back in a structured way, generate again, stop after too many attempts, hand it to a human.

The quality of feedback matters more than the number of times. Stuffing two thousand lines of logs back unchanged only wastes tokens. Useful feedback is the failing test case name, the error stack, expected vs. actual values, and the relevant file line numbers.

There is another habit I only developed later: before each round of a long task, run a basic check first to confirm the environment is not in a “broken but unrecorded” state. Without this, earlier errors keep rolling forward, and by the time you notice, you can no longer tell which step broke it.

The verification loop needs someone to maintain it, and this is the most underrated cost. Tests expire, external interfaces change, and samples gradually stop representing production traffic. I’ve seen teams build an eval set and then leave it alone; six months later it’s still running, the scores look great, but it has nothing to do with real failures anymore. A more realistic approach is to assign an owner and a quarterly review to the eval set, add newly observed production failures, and delete samples that no longer work.

One more thing: passing verification does not mean the task is done. What a program can prove is limited; the rest relies either on human spot checks or on business metrics as a backstop. I now output a checkable list at the end of a task, clearly stating which conclusions have evidence, which are only inferences, and which steps were skipped. This list isn’t for the model; it’s for the person taking over. It lets me know what I’m signing before I sign it.

Cost also needs to be calculated in advance. Running verification three times per task drives up tokens and latency, and some scenarios simply can’t afford it. So I tier it first: low-risk query tasks get rule validation plus one smoke test; only tasks involving write operations and external communication get the full loop. A uniform standard looks fair, but in practice it makes teams bypass it at critical moments.

Verification granularity should also be small. Changing a dozen files and then running the full test suite makes failures impossible to localize. Change one function, run one group of tests, move on once it passes—slower, but every step is trustworthy.

Don’t go all the way to production in one step either. My order is: local replay of the eval set, pre-production shadow, read-only mode, small-traffic canary, and only then enable write permissions. Each layer observes the same few metrics, and any anomaly at any layer stops the rollout. This order is slow, but it turns “finding out after launch” into “knowing before launch.”

The cost of this setup is also clear: slower, more expensive, and tests need maintenance. On small tasks it’s a net negative; for something I can just run once myself, I won’t write a verification loop for it.

When a harness is finished, the evaluation criterion is actually quite plain: if someone else takes over, can they understand within half an hour why it stopped, where it stopped, and what to do next. If yes, the shell is effective; if not, no amount of prompting will do anything but push the problem further down the road.

The thicker the harness, the more stable the system, and the less flexible it is. Some guardrails I now consider essential may just be patches for current model capabilities. Once models can maintain state across long workflows on their own, the first layer’s summaries and state objects may not need to be so heavy.

But I suspect the gap between “can run for three days” and “can run for three minutes” won’t disappear on its own. As long as an Agent has to touch real systems, interruptions, drift, privilege escalation, and false completion will persist, and none of these can be solved with a single sentence.

My current approach is: first admit that the model is an unreliable executor, then decide which unreliabilities are acceptable. Reverse that order and you usually get a beautiful demo and a system no one dares to launch.

Further reading: The orchestrator’s job is to decide, on the model’s behalf, where to stop

About this Post

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

#Agents #Engineering Trade-offs #Runtime Control

Comments