# Designing Hallucination-Resistant Multi-Agent Workflows: From Free Chat to Deterministic State Machines

> Why autonomous agent demos fail in production, and four battle-tested architectural constraints from running daily automated intelligence and video pipelines.

- **Author**: Hahaxiong
- **Published**: 2026-12-01
- **Canonical URL**: https://blog.aibuildon.com/en/posts/deterministic-agent-workflows

---

Over the past six months, I automated everything from daily 8-source commercial signal distillation to programmatic video storyboarding using Multi-Agent pipelines. After debugging countless context-pollution failures, one lesson stands above all else: **reliable agents come from deterministic code boundaries, not unconstrained autonomy.**

## 1. Narrow DTO Handoffs Over Full History Passing

Passing raw tool outputs and full chat transcripts across every agent turn causes quadratic token growth and rapid **Lost-in-the-Middle** degradation:

$$
C_{\text{total}} = \sum_{t=1}^{T} \left( L_{\text{sys}} + \sum_{k=1}^{t} L_{\text{turn}, k} \right) = \mathcal{O}(T^2)
$$

By isolating each stage behind a narrow, schema-validated DTO contract, downstream steps receive only clean structured facts—reducing token cost to $\mathcal{O}(T)$ while sharply improving precision.

## 2. Hard Schema Gates with Targeted Self-Repair

Never pipe raw LLM prose directly into a database or downstream prompt without a deterministic schema gate:

```ts title="src/pipeline/validate-step.ts"
export async function runStructuredStep<T>(
  prompt: string,
  schema: ZodSchema<T>,
  maxRetries = 2
): Promise<T> {
  let lastError = '';
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const raw = await callModel(
      attempt === 0 ? prompt : `${prompt}\n\nFix schema error:\n${lastError}`
    );
    const parsed = schema.safeParse(extractJson(raw));
    if (parsed.success) return parsed.data;
    lastError = parsed.error.message;
  }
  throw new Error(`Deterministic gate rejected output: ${lastError}`);
}
```

## 3. Never Ask an LLM to Do Deterministic Math

Currency conversions, date offsets, word counts, and SHA-256 content diffing belong in pure TypeScript functions. Reserve LLM tokens strictly for semantic synthesis, cross-lingual nuance, and unstructured signal extraction.
