Putting AI Agents into Production Pipelines Without Losing Control
Why autonomous tool-calling loops silently degrade in real pipelines, and how splitting deterministic DAG steps from LLM steps keeps outputs auditable and safe to publish.
Most AI agent demos look great in a terminal recording: give a model ten tools, a vague objective, and let it loop until it declares victory. Put that exact pattern on a daily cron job that feeds a real publication channel or internal ops system, and it breaks in surprisingly mundane ways.
The worst failure mode is not a crash — it is a polite, schema-valid piece of garbage. An upstream feed returns zero new items, a fallback path feeds placeholder metadata into the prompt, and the model obediently writes a confident summary about two 2-star repositories nobody has ever heard of, then publishes it straight to production.
After hitting that class of bug more than once while building automated content and engineering pipelines, I stopped treating "an agent" as the top-level orchestrator. Instead, the workflow engine owns the control flow, and the model only runs inside narrow, auditable steps.
Separate Deterministic Plumbing from Probabilistic Reasoning
In any real pipeline, 70% of the work does not need an LLM at all: fetching feeds, deduplicating URLs, checking rate limits, validating schemas, and executing side effects. Letting a model drive those steps wastes tokens and introduces non-deterministic retry behavior.
[fetch] -> [dedupe] -> [triage (LLM)] -> [quality gate] -> [draft (LLM)] -> [approval gate] -> [publish]
| | | | | | |
code code bounded call hard rules context pack human sign-off idempotentThe rule of thumb that has held up well:
- Code decides what runs next, when it retries, and whether a threshold passed.
- The LLM only transforms structured input into structured output or prose inside one step.
- Zero-data or low-signal runs short-circuit at a hard gate before any drafting prompt runs.
That last rule alone eliminates an entire category of "obviously fake" automated output. If a daily digest finds fewer than N items that pass a deterministic floor (star velocity, content length, non-empty body), the run terminates cleanly as skipped_low_signal instead of asking a model to improvise filler.
Hand Off Context Packs, Not Raw Transcripts
Multi-step agent pipelines degrade quickly when step 4 receives the entire raw conversation transcript from steps 1 through 3. Tool responses carry HTML noise, partial retries, and superseded drafts; the model spends attention on stale errors and drifts from the current objective.
Instead, every handoff between stages should be an explicit context pack: a small, typed payload containing only the verified artifacts needed for the next step plus its acceptance criteria.
export interface StepContextPack {
workItemId: string;
runId: string;
objective: string;
inputs: Array<{
assetId: string;
kind: 'source' | 'triage' | 'draft';
summary: string;
uri?: string;
}>;
constraints: string[];
acceptanceChecks: string[];
}Building context packs forces you to model intermediate work as first-class assets rather than ephemeral chat turns. It also makes debugging drastically faster: when a draft looks off, you inspect one JSON object instead of scrolling through 40 KB of tool logs.
Gate Every External Side Effect
Read-only tool calls (search, fetch, classify, draft) can run autonomously. External writes — publishing a post, sending a team notification, opening a PR, or modifying a production record — need two safeguards:
- An explicit approval boundary when quality cannot be verified purely by tests. The pipeline pauses in
waiting_approval, surfaces the exact rendered payload and diff to a human, and resumes only on an explicit approve/reject event. - Idempotent execution keys on every write connector. Networks time out after the remote server already committed the write; retrying without an idempotency key creates duplicate posts or double notifications.
For example, when publishing an approved Markdown article into a Postgres-backed blog via PostgREST, keying the upsert on slug makes retries completely safe:
const response = await fetch(`${baseUrl}/rest/v1/posts?on_conflict=slug`, {
method: 'POST',
headers: {
apikey: serviceKey,
Authorization: `Bearer ${serviceKey}`,
'Content-Type': 'application/json',
'Accept-Profile': 'website',
'Content-Profile': 'website',
Prefer: 'resolution=merge-duplicates,return=representation'
},
body: JSON.stringify({
slug,
title,
content,
excerpt,
published: true,
updated_at: now.toISOString()
})
});One subtle detail here: if a slug already exists, do not overwrite published_at on re-publish, or fixing a typo will silently bump an old article back to the top of the feed.
Make Every Step Replayable and Cost-Accounted
When you swap prompts or upgrade models, "feels better on two examples" is not enough. Recording each step in an append-only journal — stepId, rendered prompt, model identifier, latency, token usage, cost, and raw output — pays for itself within a week:
| Failure Symptom | What the Step Journal Shows Immediately |
|---|---|
| Hallucinated facts in draft | Whether the upstream inputs pack was missing data or the model ignored it |
| Sudden cost spike | Which step retried in a tight loop or received an oversized tool output |
| Regression after prompt edit | Side-by-side replay of the exact same historical context packs against the new prompt |
Because each step reads a self-contained context pack, you can replay a single step offline against a golden set of historical runs without re-scraping upstream sites or touching external APIs.
Where Agents Still Earn Their Keep
Constraining an agent inside a DAG does not mean giving up flexibility. For messy, open-ended tasks — triaging ambiguous articles against personal interest criteria, extracting structured claims from inconsistent HTML, synthesizing a first draft from scattered notes, or investigating a failing test suite — LLMs are genuinely transformative.
The difference between a toy and a system you can leave running for months comes down to boring backend engineering: hard input gates, bounded context, idempotent writes, and an audit log that lets you see why the machine did what it did.