A prompt rule is a suggestion; a code rule is a constraint. Here is how to split an agent's publishing rules between the two, with runnable guards for daily caps, duplicates, and spacing.
In this article (10)Expand ↓Collapse ↑
- The rule was in the prompt. The model forgot it.
- Four rules, five placements
- Hard caps belong in code
- Duplicate checks need an idempotency key
- Space posts out with a timestamp, not a sentence
- Dry-run mode and logging make the guardrail visible
- The cost of over-constraining the model
- What to do on Monday
- Further reading
- Sources
The rule was in the prompt. The model forgot it.
You have a scheduled agent. A cron job (a time-based scheduler on Unix-like systems) wakes it twice a day. It reads a system prompt (the standing instructions given to a language model before the user message) and publishes an article under your name.
The prompt says: never publish more than five articles in a UTC day. Never publish zero unless the cap is hit or a credential is missing. Space posts out. Check for duplicates.
Those are four rules. All four are English sentences. On every run, the model reads them and decides what to do. That is the problem. The model is not a rule engine. It is a next-token predictor that usually follows instructions and occasionally does not.
A developer writing on DEV described a very similar setup: a scheduled task that writes and publishes articles, with the daily cap, spacing and duplicate checks living in plain-English instructions. The author noticed that the rules were being re-derived by the model on every run, not enforced by anything.
That is the gap this post is about. A rule in a prompt is a suggestion. A rule in code is a constraint. They are not the same thing, and mixing them up is how agents publish six posts in a day.
Four rules, five placements
The useful exercise is to take each prompt rule and ask one question: if the model ignores this, what breaks?
If the answer is "nothing important, the output is just slightly off", leave it in the prompt. If the answer is "we publish a duplicate, blow the daily cap, or lose money", move it into code.
Here is a worked split for the publishing agent. The cap of five comes from the source agent; the placements are my worked example, not measured. The source prompt has four rules; I add a fifth (house style) to show where a preference lands.
Rule — Where it lives — Why · Max 5 posts per UTC day — Code, hard cap — A count is a fact. Code can count. · Never publish zero — Prompt, plus a code alarm — Zero can be legitimate. Judgment stays with the model; the alarm catches silence. · Space posts out — Code, minimum interval — Time math is deterministic. · Check for duplicates — Code, idempotency key — Deduplication needs a stable identity, not a vibe. · Match the house style (added example) — Prompt — Style is judgment. Code cannot grade it.
The pattern: anything that is a count, a timestamp, an identity or a budget goes into code. Anything that is a preference, a tone or a judgment call stays in the prompt.
Hard caps belong in code
A daily cap is the easiest rule to move and the most important. The prompt says "no more than five". The model reads that and usually complies. Usually is not a guarantee.
In code, the cap is a query against your own records. Count today's published rows. If the count is at or above the limit, exit before calling the model at all.
import os
import sqlite3
from datetime import datetime, timezone
DAILY_CAP = 5
def published_today(db_path: str) -> int:
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
with sqlite3.connect(db_path) as conn:
row = conn.execute(
"SELECT COUNT(*) FROM posts WHERE substr(published_at, 1, 10) = ?",
(today,),
).fetchone()
return row[0]
def main() -> None:
db_path = os.environ.get("POSTS_DB", "posts.db")
if published_today(db_path) >= DAILY_CAP:
print("daily cap reached, exiting without calling the model")
return
run_agent()Two things matter here. First, the check runs before the model is invoked, so a confused model cannot spend tokens to break the rule. Second, the cap is read from the database, not from the model's memory of the conversation.
One caveat on the query: substr(published_at, 1, 10) assumes published_at is stored as an ISO-8601 UTC string starting with YYYY-MM-DD. If it is stored as a Unix epoch integer or another format, the count silently returns 0 and the cap never fires, which is exactly the failure this section warns about. Store the column as an ISO string or a proper date column, and verify the count on a known day.
If you are still storing posts in a JSON file, the same logic works but the count gets slower and the file gets riskier to write concurrently. The tradeoffs are covered in Python persistence: when to move from JSON to SQLite.
A cap you cannot see is a cap you cannot trust. Log the count on every run, even when the run proceeds.
Duplicate checks need an idempotency key
"Check for duplicates" is the rule most likely to fail quietly. The model reads the last few titles, decides the new one is different, and publishes. Two days later you find two posts with the same argument and slightly different wording.
Idempotency is the property that running the same operation twice has the same effect as running it once. An idempotency key is a stable identifier for the operation, so the second run can recognize the first.
For a publishing agent, the key should be derived from the content, not from the timestamp or the model's chosen title. A hash of the normalized body is a reasonable start.
import hashlib
import sqlite3
def content_key(body: str) -> str:
normalized = " ".join(body.lower().split())
return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
def claim_key(db_path: str, key: str) -> bool:
"""Return True if this key is new. False if already published."""
with sqlite3.connect(db_path) as conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS published_keys ("
" \"key\" TEXT PRIMARY KEY, claimed_at TEXT NOT NULL)"
)
try:
conn.execute(
"INSERT INTO published_keys (\"key\", claimed_at) "
"VALUES (?, datetime('now'))",
(key,),
)
conn.commit()
return True
except sqlite3.IntegrityError:
return FalseThe key column is declared PRIMARY KEY, and the insert either succeeds or raises IntegrityError. That is the duplicate check, and it does not depend on the model remembering to perform it. Two details matter: the unique constraint must actually exist for IntegrityError to fire (otherwise a missing table raises OperationalError instead), and key is quoted because it is a reserved-ish word in some engines. Commit explicitly rather than relying on context-manager exit semantics.
One caveat: a content hash catches exact repeats after normalization. It does not catch a paraphrased post on the same topic. That is a judgment call, and judgment belongs in the prompt or in a separate review step. Do not pretend a hash solves semantics.
Space posts out with a timestamp, not a sentence
"Space posts out" is vague in a prompt and trivial in code. Pick a minimum interval in seconds. Store the last publish time. Refuse to publish before last + interval.
from datetime import datetime, timezone, timedelta
MIN_INTERVAL = timedelta(hours=4)
def too_soon(last_published_iso: str | None) -> bool:
if last_published_iso is None:
return False
last = datetime.fromisoformat(last_published_iso)
if last.tzinfo is None:
last = last.replace(tzinfo=timezone.utc)
return datetime.now(timezone.utc) - last < MIN_INTERVALThe tzinfo normalization is not optional. SQLite's datetime('now') yields a naive UTC string like 2024-01-01 12:00:00, and subtracting a naive datetime from an aware one raises TypeError. Either normalize on read, as above, or store ISO strings with an explicit offset.
This is the kind of rule that looks silly to put in code until the day the model decides to publish two posts back-to-back because it misread the clock. Time arithmetic is deterministic. Let code do it.
Dry-run mode and logging make the guardrail visible
A guardrail that fires silently is hard to debug. Two additions pay for themselves quickly.
A dry-run mode runs the full pipeline except the final side effect. It answers the question "what would have happened" without publishing. Wire it to an environment variable so you can flip it in a scheduled job without editing code.
import os
def publish(body: str, dry_run: bool) -> None:
if dry_run:
print(f"[dry-run] would publish {len(body)} chars")
return
# real publish call goes here
print("published")
def main() -> None:
dry_run = os.environ.get("DRY_RUN", "0") == "1"
publish("example body", dry_run)Structured logging is the second addition. Log one line per decision: cap check result, key claim result, interval check result, and the final action. When a scheduled job misbehaves at 3 a.m., that log is the only witness. The general problem of trusting weak signals from automation is covered in the script ran: that is the weakest signal you have.
A log line like cap=3/5 key=new interval=ok action=publish tells you more than any prompt ever will.
The cost of over-constraining the model
Moving every rule into code is its own failure mode. If you encode too much, you have built a brittle script with an expensive text generator bolted on.
Three costs show up in practice.
First, code rules cannot read intent. A cap of five is fine until a major news event makes you want a sixth post. Now you are editing code at the worst possible time. Leave a manual override path, and log when it is used.
Second, every code rule is a new failure point. A database lock, a clock skew, a missing environment variable: each one can stop the agent entirely. A prompt rule degrades gracefully. A code rule fails hard. A hard failure is what you want for a cap; for spacing you may want the code check to log and skip rather than crash the whole run.
Third, over-constraining removes the flexibility you chose the model for. If the agent can only do exactly what the code allows, you did not need an LLM. You needed a script.
The split that holds up: code enforces the invariants (things that must never be violated), the prompt handles the preferences (things that should usually be true). Invariants are counts, identities, budgets and time windows. Preferences are tone, ordering, topic choice and style.
What to do on Monday
Open your agent's system prompt and list every rule. For each one, write down what breaks if the model ignores it. If the answer is "a duplicate post" or "we overspend", move it into code this week. If the answer is "the post is a bit off-brand", leave it where it is.
Then add three things: a dry-run flag, one structured log line per decision, and a manual override that records itself. Those three turn a prompt full of hopes into a system you can reason about.
If you are still shaping the project layout so the agent has stable files to work against, setting up a Python project so your AI agent stops guessing is the natural next read. The rules are only as strong as the code that enforces them.
Further reading
- Why Tool-Calling Agents Fail on Formatting: Preference Data
- The script ran. That is the weakest signal you have.