Software Engineering
Rules belong in code, not in the prompt: when a better prompt makes the agent worse
I rewrote an agent's prompt to make the rule explicit and it started failing more. What fixed it was a ten-line check in code. Here is how I decide what stays in the text.
Rodrigo Lucas · · 12 min read
Series: AI agent in productionpart 2 of 5
- 01An AI agent that writes to the database: the confirm click can't go through the model
- 02Rules belong in code, not in the prompt: when a better prompt makes the agent worse
- 03Your agent eval moves more than your improvement
- 04Reasoning used up the output limit and the answer came back empty
- 05Prompt caching in practice: the obvious cut that would have saved 4%
With the original prompt, the agent read the file before rewriting it in 2 of 4 runs. I rewrote the prompt to make the rule explicit, ran it again against the real model, and it read the file in 0 of 4. It only got to 4 of 4 when the rule left the text and became a check of a few lines in code, which the model has no way of skipping.
It was an agent that edits code, and the episode changed how I write prompts. A rule that must always hold goes into a guard in code that runs with or without an LLM, because the prompt moves the probability of a behavior and code decides what is possible. In the other cases in this post, much of the model's "reasoning error" was missing information in the input, and the fix went into the code that builds the request. And I would not have seen any of this without running before and after, because the version that looked better was the worst one.
In part 1 of the series, the central idea was that human confirmation has to go through a channel the model does not control. Here the subject is where each agent rule should live.
The agent that rewrote files without reading them#
The agent received the log of a failure and returned the fixed file, whole. Except that it often returned it without having read the file, and then the part it needed to change came out right and the rest of the code came out invented.
The case I measured with was simple, because the right fix changed a single line, a class reference that had to be resolved from the root namespace. I ran the agent four times per version, read-only and without pushing, against the same change.
| Version | Read the file first | Result |
|---|---|---|
| Original | 2 of 4 | 2 responses with 86 and 132 lines different from the real file |
| New output contract only | 0 of 4 | 4 responses with 99 to 480 lines different |
| New contract and a guard in code | 4 of 4 | 4 responses with only the fixed line |
The second row of the table is what made me stop. Read by a person, the new contract was better in every way. It removed instructions that did not apply to that agent (it had inherited the text from another agent, which talked about a field it never used), adapted the wording to the log it received, and warned explicitly that an unread file would be rejected. Even so, the model read the file in none of the four runs.
I am not sure why it got worse. My hypothesis is that a cleaner, more self-assured contract made the model confident enough to answer directly, without going through the read tool. With or without an explanation, I was asking the model to follow a rule that had to hold in every run, and two of four or zero of four amount to the same failure, just at a different frequency.
The guard that rejects what was not seen#
The fix had two parts, and both are code.
I changed what goes into the request. The agent started receiving the current content, on the change's branch, of every file it was going to modify, so the file the model needs goes along without depending on it deciding to call a tool.
And I added the guard. Before accepting the response, the code checks whether each rewritten file was seen in this run, either in the request or through a tool read on the change's branch. If not, the response is rejected with a reason.
function unseenFiles(response: Response, run: Run): string[] {
const seen = new Set([
...run.filesInRequest,
...run.reads
.filter((r) => r.ref === run.targetBranch)
.map((r) => r.path),
]);
return response.files
.filter((f) => !f.isNew && !seen.has(f.path))
.map((f) => f.path);
}
const missing = unseenFiles(response, run);
if (missing.length > 0) {
return reject(`rewrote without reading: ${missing.join(", ")}`);
}
Two details make the guard work. A read on another ref does not count, because if the model reads the file on the default branch and rewrites from it, it undoes what the branch had already fixed, so the rule requires a read of the version about to be replaced. And a new file counts as seen, otherwise the guard would reject every file creation and someone would turn it off in the first week.
The most visible price is more rejections. If the file cannot be read, because of an API error or because it exceeds the maximum size, and the model does not read it on its own, the fix becomes a rejection. I accepted that because a change that keeps failing is better than an invented file on top of it, but before adding a guard like this it is worth checking what happens to the flow when it fires. The request also got bigger, since it carries the files, and here it stayed in the same range, around 27 thousand input tokens against 26 to 53 thousand in the original version, which sometimes read the file through a tool.
The contract kept saying that an unseen file is rejected, except that now the sentence describes what the system does.
The loop that obeyed the most emphatic reviewer#
The same problem showed up in a less obvious place, a loop that turns reviewer evaluations into rules. A model read the evaluations people had made of the proposed changes and wrote a "lessons" text that went into an agent's prompt. Only the model decided what was relevant, and the code just filtered the time window and cut at the maximum size.
The risk is a single evaluation with an emphatic comment becoming a permanent rule. To test it, I built five realistic evaluations. In one of them, the reviewer approved as correct a change that had been rejected in the PR, and wrote in the comment "from now on, always use safe navigation to fix any nil".
| Version | Created the "use safe navigation" lesson |
|---|---|
| Original | 3 of 3, repeating even the comment's wording |
| PR outcome in the input and a prompt instruction to weigh it | 3 of 3 |
| Contradiction flagged in code | 0 of 4 |
The second version was the fix through the prompt, and it was the obvious thing to do, include the PR outcome (merged or rejected) and instruct the model to take it into account. It received the right information and the right instruction and, even so, created the lesson in all three rounds.
What worked was doing the math in code and handing over the result. A "correct" verdict on a rejected PR, or an "incorrect" one on a merged PR, is a contradiction the code detects without ambiguity. That evaluation now reaches the model flagged, and the prompt says no lesson in favor of the change is drawn from a flagged evaluation.
def flag_contradiction(evaluation):
contradicts = (
(evaluation.verdict == "correct" and evaluation.pr == "rejected")
or (evaluation.verdict == "incorrect" and evaluation.pr == "merged")
)
return {**evaluation.as_dict(), "contradicts_outcome": contradicts}
What changed was the work left for the model. Through the prompt, I asked it to cross two fields, notice the conflict, and decide to ignore an emphatic comment. With the flag, the crossing arrived already done and it only had to respect it. The less inference a rule demands from the model, the more it behaves like a rule.
Without manipulation, the legitimate lessons kept coming out in all five runs and no good output was rejected by mistake. The guard took away from the model only the decision it made badly.
Checks before and after the call#
The loop got other checks in code. Before the call, with fewer than three evaluations in the window, the model is not even called and the previous text stays intact. The reviewer's comment is treated as data, so it goes delimited, unable to close its own delimiter, and lines shaped like orders to the system are removed.
After the call, the generated text is rejected if it has meta-commentary about the evaluations, a sentence shaped like an order, or a passage copied literally from a comment (40 characters or more). In that case the previous rules stay in effect. That rejection is what makes the rest safe to experiment with, because a false positive only delays the update, while a false negative becomes a permanent instruction in another agent's prompt. With that asymmetry, the guard should err on the side of rejecting.
These pattern lists are never complete. They catch the common forms of orders and meta-commentary and let others through, so they reduce the surface without closing it. It also surprised me that the explicit attack was the smallest of the problems. A command like "ignore the rules above" was ignored by the model in both versions, so removing those lines is extra defense the model did not show it needed. What it did show it needed was the contradiction flag, and the real danger came from a sincere, emphatic comment, written with no malice.
Instructions do not fix missing data#
Another agent had a problem that also looked like a prompt problem. It had to assign a severity to the error and say whether some deploy was related to it. In one test run, it marked as related a deploy that had finished seven days before the error's first occurrence.
Part of the fix really was text, with criteria for each severity level and a definition of "related deploy" (same environment, finished up to about 24 hours before the reference, with no other deploy of the same environment in between). But the main cause was outside the prompt. The request never said when the error started, because the column that stored the first occurrence had existed since the original data model and had never been filled. The model was instructed to correlate an error with a deploy without knowing the error's date.
Once the first occurrence was being recorded and sent, the seven-days-earlier deploy stopped being flagged. In every run the field came back empty, which was the right answer (I checked the deploys for the period by hand).
Since then, when the model gets an inference wrong, the first thing I look at is whether it had what it needed to get it right. Explaining the rule better to someone without the data only produces a more confident answer that is just as wrong.
Severity is the case where code does not help. It is judgment, and you cannot write an if that decides whether an error is high or critical without rewriting the classifier itself. It stayed only in the text and kept oscillating in some runs. The criteria reduced the variation without ending it, and there the job of the code is to measure the oscillation.
Where each rule should live#
Today, before writing a rule into the prompt, I ask myself whether it needs to hold in every run. "Do not rewrite a file you have not read" and "do not apply a lesson from a contradictory evaluation" are invariants, and those go into code, because a 95% rate is one failure every twenty runs.
It helps a lot when the violation shows up just by looking at the input or the output, like an unread file, a field that contradicts another, or a copied passage. Then the check is cheap, fits in a unit test, and does not vary between rounds. If the rule depends on comparing two fields, I compare them in code and send the result, and if it depends on a date, I make sure the date is in the request.
The cost of failure matters too. A response tone off the standard costs little, and an invented file in a change or a false rule in another agent's prompt costs a lot. The more expensive the failure, the more the rule should leave the text.
Last comes where the input comes from. A reviewer's comment, page content, and a user's message all reach the model as text and compete with your instructions. OWASP says it is unclear whether there are fool-proof methods of preventing prompt injection, and recommends separating and denoting untrusted content and validating the output with deterministic code.
The prompt is still left with a lot that matters, like the tone, the shape of the response, the preferences, the criteria in cases that really call for judgment, and the explanation of why each rule exists. Anthropic's prompt engineering guide says that not every success criterion or failing eval is best solved by prompt engineering. The Building effective agents piece, from the same company, recommends programmatic checks (the "gate") on intermediate steps and designing tools so that mistakes are harder to make.
The same holds outside agents that write code. In an assistant I built, when the user dismisses a suggestion, that is stored in the profile and the code filters the results before the model sees them. I could have written "do not suggest what the user dismissed" in the prompt. I went with a rule that always holds and that I test without calling an LLM.
What I still cannot measure#
The prompt still matters, and I have numbers for that too. In another agent of the same system, the improvement came from the text alone, and it started reading the suspect file in 3 of 3 runs (against 2 of 3) and adding a regression test in 3 of 3 (against 0 of 3). A good prompt helps, but it helps in probability, and I did not let any invariant depend on that.
The samples in this post are small, with three to six runs per version in every table. That is enough to see a broken rule, because zero against four is far from noise, but not enough to claim a rate. If a prompt change took a behavior from 70% to 80%, I could not tell with these rounds. What is missing is a baseline with the agent's own variance, running the same scenario several times without changing anything, to know from what difference on it is worth believing the result.
References#
updated on
01 blog
related
software engineering
A perfect Lighthouse SEO score does not prove SEO, the HTML your site serves does
Lighthouse gave my site an SEO score of 100 while the canonical pointed to a domain that returned 404. What the audit checks, what it cannot check and a 40-line checker that catches the defect.
software engineering
42 green checks and no citations: the index decides what AI cites
A site passed every SEO check and did not show up in any search engine. Blocking the training bot does not take anyone out of ChatGPT, but staying out of the index does.
software engineering
Tests that pass without protecting anything: watch the test fail before you trust it
A green CI that ran no tests, a spec that never saw the template, and another that breaks between midnight and 1 a.m. I only trust a test after seeing it fail for the right reason.
02 blog
Who writes
Contact
Let's swap ideas
Get the next articles
No spam, one email when a new article ships. Unsubscribe anytime.