MODULE 03.2 · PUBLISHED · ~3h

When Not to Use Open-Ended Agents

Evaluate when a deterministic pipeline, router, or bounded graph outperforms an open-ended agent loop on reliability, latency, and cost, and implement an architecture decision evaluator in fde-03-2 with pytest and GitHub Actions.

Open-ended agents are easy to demo and tempting to use everywhere, but autonomous loops introduce non-determinism, variable token spend, harder debugging, and wider blast radius when calling tools.

In this module, you will compare deterministic pipelines, classifier-plus-template routers, bounded graphs, and open-ended agent loops under explicit budget, latency, and side-effect constraints, handle infeasible constraint combinations cleanly, and verify everything with pytest and GitHub Actions in fde-03-2.

Enterprise Scenario: Northwind Freight

Northwind’s operations team handles thousands of daily shipment status checks, invoice PDF lookups, and exception escalations. A stakeholder asks for an open-ended agent to handle every request autonomously, even when steps are fixed, latency budgets are tight, or external side effects are irreversible without human sign-off.

What You Will Build

  • Workflow and decision schemas: Define strict Pydantic v2 models for WorkflowProfile, ArchitectureOption, and ArchitectureDecision with extra="forbid", strict=True, deduplicated lists, trimmed, non-blank workflow names, and cross-field feasibility validation.
  • Constraint-aware selector, cost estimator, and latency estimator: Enforce has_bounded_state_space=True and disallow open-ended agents for external side effects, require approval checkpoints for irreversible side effects, evaluate eligible candidates against budget and latency limits, and report the true lowest-cost eligible candidate when returning infeasible.
  • Tested ADR-ready decision engine + CI: Verify selection, downgrades, infeasibility, strict step/multiplier validation, and overflow protection with pytest and GitHub Actions.

1. Deterministic Pipelines vs. Open-Ended Agents

  • When a deterministic pipeline or classifier plus template wins: If the steps are known ahead of time, code executes faster, costs less, and fails predictably. If inputs map to clear categories with standard replies, a classifier plus deterministic template keeps token usage low and formatting consistent.
  • When bounded graphs or open-ended agents fit: Use a bounded graph when the workflow has a bounded state space with capped transitions and explicit checkpoints. Reserve open-ended agents for exploratory tasks without external side effects where steps cannot be predetermined and budget and latency constraints allow them.
  • Side effects, reversibility, and approval checkpoints: Under this lesson’s policy, workflows with external side effects require has_bounded_state_space=True, never use an open-ended agent, and treat irreversible side effects without an approval checkpoint as infeasible. In this exercise, has_approval_checkpoint=True is an input assumption about workflow design, not proof that a real human approval service is deployed, authenticated, and enforced at runtime.
  • Illustrative cost, latency, and side-effect multiplier figures: The base cost ($0.0005 pipeline, $0.002 classifier, $0.012 bounded graph, $0.045 open-ended agent), base latency numbers, and the 1.25 side-effect multiplier (a 25% increase on estimated cost and latency when external side effects are present) in this module are hard-coded illustrative teaching assumptions, not measured production prices, SLAs, or empirical operational ratios. Actual production costs and latencies depend on model pricing, token consumption, infrastructure, tool calls, retries, and execution volume.

Architecture Selection Guide

Scenario shapePreferred patternWhy
Fixed steps and strict schemaDeterministic pipelinePredictable latency, lowest cost, easy to test
Known categories with standard repliesClassifier + templateMinimal LLM tokens, consistent formatting
Branching or side-effecting logicBounded graphExplicit transitions, step caps, and checkpoints
Exploratory multi-step investigation (no side effects)Open-ended agent (guarded)Adapts path dynamically when constraints allow
Impossible budget, SLA, or unapproved writeInfeasibleAvoids silently violating constraints

2. Step-by-Step Build Walkthrough

  1. Create the fde-03-2 repository and virtual environment:
    mkdir -p fde-03-2/src/fde_03_2 fde-03-2/tests fde-03-2/.github/workflows
    cd fde-03-2
    python3 -m venv .venv
    source .venv/bin/activate
    python -m pip install --upgrade pip
    python -m pip install -e ".[dev]"
    cp .env.example .env
  2. Define strict Pydantic v2 schemas in src/fde_03_2/schemas.py: Enforce extra="forbid", strict=True, trimmed, non-blank workflow names, deduplicated reasons and trade_offs, and cross-field validation between recommended and feasible.
    """Strict Pydantic v2 schemas for workflow architecture evaluation."""
    
    from __future__ import annotations
    
    import math
    from typing import Literal
    from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
    
    ArchitectureOption = Literal[
        "deterministic_pipeline",
        "classifier_plus_template",
        "bounded_graph",
        "open_ended_agent",
        "infeasible",
    ]
    
    
    def _require_non_blank(value: str, field_name: str) -> str:
        cleaned = value.strip()
        if not cleaned:
            raise ValueError(f"{field_name} must not be blank")
        return cleaned
    
    
    def _require_finite_non_negative(value: float, field_name: str) -> float:
        if not math.isfinite(value) or value < 0.0:
            raise ValueError(f"{field_name} must be finite and non-negative")
        return value
    
    
    def _dedupe_preserve_order(items: list[str], field_name: str) -> list[str]:
        seen: set[str] = set()
        result: list[str] = []
        for item in items:
            cleaned = _require_non_blank(item, field_name)
            if cleaned not in seen:
                seen.add(cleaned)
                result.append(cleaned)
        return result
    
    
    class WorkflowProfile(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
    
        workflow_name: str = Field(min_length=1)
        steps_known_in_advance: bool
        has_fixed_categories: bool
        requires_dynamic_exploration: bool
        has_bounded_state_space: bool = False
        has_external_side_effects: bool = False
        reversible_side_effects: bool = True
        has_approval_checkpoint: bool = False
        max_budget_usd_per_run: float
        max_latency_ms: float
    
        @field_validator("workflow_name")
        @classmethod
        def _validate_name(cls, value: str) -> str:
            return _require_non_blank(value, "workflow_name")
    
        @field_validator("max_budget_usd_per_run", "max_latency_ms")
        @classmethod
        def _validate_positive_limits(cls, value: float, info) -> float:
            _require_finite_non_negative(value, info.field_name)
            if value <= 0.0:
                raise ValueError(f"{info.field_name} must be greater than 0")
            return value
    
    
    class ArchitectureDecision(BaseModel):
        model_config = ConfigDict(extra="forbid", strict=True)
    
        workflow_name: str = Field(min_length=1)
        recommended: ArchitectureOption
        feasible: bool
        estimated_cost_usd: float
        estimated_latency_ms: float
        reasons: list[str] = Field(min_length=1)
        trade_offs: list[str] = Field(min_length=1)
    
        @field_validator("workflow_name")
        @classmethod
        def _validate_workflow_name(cls, value: str) -> str:
            return _require_non_blank(value, "workflow_name")
    
        @field_validator("estimated_cost_usd", "estimated_latency_ms")
        @classmethod
        def _validate_non_negative_estimates(cls, value: float, info) -> float:
            return _require_finite_non_negative(value, info.field_name)
    
        @field_validator("reasons", "trade_offs")
        @classmethod
        def _validate_string_lists(cls, values: list[str], info) -> list[str]:
            return _dedupe_preserve_order(values, info.field_name)
    
        @model_validator(mode="after")
        def _validate_decision_consistency(self) -> "ArchitectureDecision":
            if self.recommended == "infeasible" and self.feasible:
                raise ValueError("recommended='infeasible' requires feasible=False")
            if self.recommended != "infeasible" and not self.feasible:
                raise ValueError("feasible=False requires recommended='infeasible'")
            return self
  3. Implement constraint-aware selection and illustrative cost/latency estimation in src/fde_03_2/selector.py: Enforce bounded state space and approval rules on external side effects, disallow open-ended agents on external side effects, evaluate all eligible candidates, and report the actual lowest-cost eligible candidate when returning infeasible.
    """Constraint-aware architecture selection and illustrative cost/latency estimation."""
    
    from __future__ import annotations
    
    import math
    from typing import Literal
    
    from fde_03_2.schemas import (
        ArchitectureDecision,
        WorkflowProfile,
        _require_finite_non_negative,
    )
    
    CandidateOption = Literal[
        "deterministic_pipeline",
        "classifier_plus_template",
        "bounded_graph",
        "open_ended_agent",
    ]
    
    # Illustrative teaching assumptions only, not measured production prices or SLAs.
    _OPTION_BASE_COST_USD: dict[CandidateOption, float] = {
        "deterministic_pipeline": 0.0005,
        "classifier_plus_template": 0.002,
        "bounded_graph": 0.012,
        "open_ended_agent": 0.045,
    }
    
    _OPTION_BASE_LATENCY_MS: dict[CandidateOption, float] = {
        "deterministic_pipeline": 120.0,
        "classifier_plus_template": 350.0,
        "bounded_graph": 1400.0,
        "open_ended_agent": 4200.0,
    }
    
    # Illustrative teaching assumption: 1.25x (25% increase) when external side effects are present.
    _ILLUSTRATIVE_SIDE_EFFECT_MULTIPLIER = 1.25
    _MAX_REASONABLE_MULTIPLIER = 100.0
    _MAX_EXPECTED_STEPS = 1000
    
    
    def _validate_positive_int_steps(expected_steps: int) -> int:
        if isinstance(expected_steps, bool) or not isinstance(expected_steps, int):
            raise ValueError("expected_steps must be a positive integer (not bool or float)")
        if expected_steps < 1:
            raise ValueError("expected_steps must be at least 1")
        if expected_steps > _MAX_EXPECTED_STEPS:
            raise ValueError(f"expected_steps must not exceed {_MAX_EXPECTED_STEPS}")
        return expected_steps
    
    
    def _validate_multiplier(multiplier: float, name: str) -> float:
        if isinstance(multiplier, bool) or not isinstance(multiplier, (int, float)):
            raise ValueError(f"{name} must be a finite positive number (not bool)")
        try:
            numeric_multiplier = float(multiplier)
        except (OverflowError, TypeError, ValueError) as exc:
            raise ValueError(f"{name} must be a finite positive number") from exc
        _require_finite_non_negative(numeric_multiplier, name)
        if numeric_multiplier <= 0.0:
            raise ValueError(f"{name} must be greater than 0")
        if numeric_multiplier > _MAX_REASONABLE_MULTIPLIER:
            raise ValueError(f"{name} exceeds maximum allowed value ({_MAX_REASONABLE_MULTIPLIER})")
        return numeric_multiplier
    
    
    def estimate_run_cost_usd(
        option: CandidateOption,
        expected_steps: int = 1,
        side_effect_guard_multiplier: float = 1.0,
    ) -> float:
        """Estimate illustrative per-run cost in USD for a candidate workflow option."""
        steps = _validate_positive_int_steps(expected_steps)
        mult = _validate_multiplier(side_effect_guard_multiplier, "side_effect_guard_multiplier")
    
        base = _OPTION_BASE_COST_USD[option]
        if option in {"deterministic_pipeline", "classifier_plus_template"}:
            cost = base
        elif option == "bounded_graph":
            cost = base * min(steps, 6)
        else:
            cost = base * steps
    
        try:
            total = cost * mult
        except OverflowError as exc:
            raise ValueError("Estimated cost overflowed") from exc
        if not math.isfinite(total):
            raise ValueError("Estimated cost overflowed")
        return round(total, 8)
    
    
    def estimate_run_latency_ms(
        option: CandidateOption,
        expected_steps: int = 1,
        side_effect_guard_multiplier: float = 1.0,
    ) -> float:
        """Estimate illustrative per-run latency in ms for a candidate workflow option."""
        steps = _validate_positive_int_steps(expected_steps)
        mult = _validate_multiplier(side_effect_guard_multiplier, "side_effect_guard_multiplier")
    
        base = _OPTION_BASE_LATENCY_MS[option]
        if option in {"deterministic_pipeline", "classifier_plus_template"}:
            latency = base
        elif option == "bounded_graph":
            latency = base + (250.0 * min(steps - 1, 5))
        else:
            latency = base + (750.0 * (steps - 1))
    
        try:
            total = latency * mult
        except OverflowError as exc:
            raise ValueError("Estimated latency overflowed") from exc
        if not math.isfinite(total):
            raise ValueError("Estimated latency overflowed")
        return round(total, 4)
    
    
    def _fits_constraints(
        cost_usd: float,
        latency_ms: float,
        profile: WorkflowProfile,
    ) -> bool:
        return (
            cost_usd <= profile.max_budget_usd_per_run
            and latency_ms <= profile.max_latency_ms
        )
    
    
    def recommend_architecture(profile: WorkflowProfile) -> ArchitectureDecision:
        """Select a workflow architecture respecting capability, budget, latency, and side-effect rules."""
        reasons: list[str] = []
        trade_offs: list[str] = []
    
        if (
            profile.has_external_side_effects
            and not profile.reversible_side_effects
            and not profile.has_approval_checkpoint
        ):
            return ArchitectureDecision(
                workflow_name=profile.workflow_name,
                recommended="infeasible",
                feasible=False,
                estimated_cost_usd=0.0,
                estimated_latency_ms=0.0,
                reasons=[
                    "Irreversible external side effects require an approval checkpoint before execution"
                ],
                trade_offs=[
                    "No architecture meets the supplied safety constraints without adding approval or reversibility"
                ],
            )
    
        if profile.has_external_side_effects and not profile.has_bounded_state_space:
            return ArchitectureDecision(
                workflow_name=profile.workflow_name,
                recommended="infeasible",
                feasible=False,
                estimated_cost_usd=0.0,
                estimated_latency_ms=0.0,
                reasons=[
                    "External side effects require has_bounded_state_space=True under this lesson's policy"
                ],
                trade_offs=[
                    "Declare a bounded state space with explicit checkpoints before enabling external side effects"
                ],
            )
    
        # Determine functional eligibility before comparing cost or latency.
        # External side effects strictly require a bounded graph and disallow open-ended agents.
        eligible_options: list[CandidateOption] = []
    
        if profile.has_external_side_effects:
            eligible_options.append("bounded_graph")
        else:
            if profile.steps_known_in_advance and not profile.requires_dynamic_exploration:
                eligible_options.append("deterministic_pipeline")
            if profile.has_fixed_categories and not profile.requires_dynamic_exploration:
                eligible_options.append("classifier_plus_template")
            if profile.has_bounded_state_space:
                eligible_options.append("bounded_graph")
            if profile.requires_dynamic_exploration:
                eligible_options.append("open_ended_agent")
    
        if not eligible_options:
            return ArchitectureDecision(
                workflow_name=profile.workflow_name,
                recommended="infeasible",
                feasible=False,
                estimated_cost_usd=0.0,
                estimated_latency_ms=0.0,
                reasons=[
                    "No architecture is eligible for the declared workflow capabilities"
                ],
                trade_offs=[
                    "Revisit the workflow requirements or declare a supported execution pattern"
                ],
            )
    
        if profile.has_external_side_effects:
            preferred: CandidateOption = "bounded_graph"
            reasons.append("External side effects require a bounded graph with explicit checkpoints")
            trade_offs.append("Requires explicit state transitions and checkpoints before external side effects")
        elif profile.steps_known_in_advance and not profile.requires_dynamic_exploration:
            preferred = "deterministic_pipeline"
            reasons.append("Steps are known in advance without dynamic exploration")
            trade_offs.append("Less adaptable to novel multi-step edge cases than a graph or agent")
        elif profile.has_fixed_categories and not profile.requires_dynamic_exploration:
            preferred = "classifier_plus_template"
            reasons.append("Inputs map to fixed categories with deterministic response templates")
            trade_offs.append("Limited to predefined output patterns and categories")
        elif profile.has_bounded_state_space:
            preferred = "bounded_graph"
            reasons.append("The workflow has a bounded state space with explicit transitions and checkpoints")
            trade_offs.append("Requires the state space and maximum transitions to be defined up front")
        else:
            preferred = "open_ended_agent"
            reasons.append("The workflow requires dynamic exploration and has no declared bounded state space")
            trade_offs.append("Higher token variance, harder debugging, and requires strict tool guardrails")
    
        if profile.has_external_side_effects and not profile.reversible_side_effects:
            reasons.append("Irreversible side effects are guarded by a declared approval checkpoint")
            trade_offs.append("Human approval step adds latency before external side effects complete")
    
        multiplier = _ILLUSTRATIVE_SIDE_EFFECT_MULTIPLIER if profile.has_external_side_effects else 1.0
    
        preferred_steps = (
            4 if preferred == "bounded_graph" else (6 if preferred == "open_ended_agent" else 1)
        )
        fallback_order: list[tuple[CandidateOption, int]] = [(preferred, preferred_steps)]
        if "bounded_graph" in eligible_options:
            fallback_order.append(("bounded_graph", 2))
        if "classifier_plus_template" in eligible_options:
            fallback_order.append(("classifier_plus_template", 1))
        if "deterministic_pipeline" in eligible_options:
            fallback_order.append(("deterministic_pipeline", 1))
        if "open_ended_agent" in eligible_options:
            fallback_order.append(("open_ended_agent", 6))
    
        # Deduplicate by (option, steps), retaining distinct eligible configurations.
        seen_candidates: set[tuple[CandidateOption, int]] = set()
        ordered_candidates: list[tuple[CandidateOption, int]] = []
        for opt, steps in fallback_order:
            candidate = (opt, steps)
            if candidate not in seen_candidates:
                seen_candidates.add(candidate)
                ordered_candidates.append(candidate)
    
        evaluated: list[tuple[CandidateOption, int, float, float]] = []
        for index, (candidate_opt, steps) in enumerate(ordered_candidates):
            est_cost = estimate_run_cost_usd(
                candidate_opt,
                expected_steps=steps,
                side_effect_guard_multiplier=multiplier,
            )
            est_latency = estimate_run_latency_ms(
                candidate_opt,
                expected_steps=steps,
                side_effect_guard_multiplier=multiplier,
            )
            evaluated.append((candidate_opt, steps, est_cost, est_latency))
            if _fits_constraints(est_cost, est_latency, profile):
                if index > 0:
                    reasons.append(
                        f"Selected {candidate_opt} ({steps} steps) to satisfy per-run budget (${profile.max_budget_usd_per_run}) and latency ({profile.max_latency_ms} ms) limits"
                    )
                    trade_offs.append(
                        "Reduces multi-step flexibility in exchange for meeting cost and latency ceilings"
                    )
                return ArchitectureDecision(
                    workflow_name=profile.workflow_name,
                    recommended=candidate_opt,
                    feasible=True,
                    estimated_cost_usd=est_cost,
                    estimated_latency_ms=est_latency,
                    reasons=reasons,
                    trade_offs=trade_offs,
                )
    
        cheapest_opt, cheapest_steps, cheapest_latency_ms = min(
            ((opt, steps, lat) for opt, steps, _, lat in evaluated),
            key=lambda item: (
                estimate_run_cost_usd(
                    item[0],
                    expected_steps=item[1],
                    side_effect_guard_multiplier=multiplier,
                ),
                item[2],
            ),
        )
        min_cost = estimate_run_cost_usd(
            cheapest_opt,
            expected_steps=cheapest_steps,
            side_effect_guard_multiplier=multiplier,
        )
        return ArchitectureDecision(
            workflow_name=profile.workflow_name,
            recommended="infeasible",
            feasible=False,
            estimated_cost_usd=min_cost,
            estimated_latency_ms=cheapest_latency_ms,
            reasons=[
                f"No eligible architecture meets budget (${profile.max_budget_usd_per_run}) and latency ({profile.max_latency_ms} ms) limits; lowest-cost eligible candidate ({cheapest_opt}, {cheapest_steps} steps) has illustrative estimate ${min_cost} and {cheapest_latency_ms} ms"
            ],
            trade_offs=[
                "Revisit the budget ceiling, latency SLA, or workflow requirements before deploying"
            ],
        )

    Approval enforcement boundary: The selector treats has_approval_checkpoint as a trusted workflow-profile input. This sample does not implement a human approval service or verify that approval was actually granted. In production, the side-effect handler must pause and verify an authenticated, auditable approval decision immediately before the irreversible action. Do not let a model or untrusted request set this flag to bypass the approval requirement.

  4. Run tests and commit to Git:
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 03.2"

3. Common Pitfalls and Operational Hygiene

  • Using an open-ended agent for fixed CRUD or lookup flows, or allowing open-ended loops on external side effects: Keep external side effects on a bounded graph with explicit checkpoints and never run an open-ended agent for external side effects under this lesson’s policy.
  • Assuming the last fallback candidate is the cheapest: Always compute the minimum-cost candidate across evaluated eligible options using estimate_run_cost_usd when constructing an infeasible reason.
  • Skipping the ADR when choosing a simpler architecture: Write down why a deterministic pipeline, classifier plus template, or bounded graph was chosen over an agent loop so trade-offs stay clear to the team.

4. Completion Criteria

  • WorkflowProfile and ArchitectureDecision validate inputs strictly with Pydantic v2, deduplicate lists, and enforce decision feasibility consistency.
  • recommend_architecture, estimate_run_cost_usd, and estimate_run_latency_ms enforce bounded state space and approval rules for external side effects, validate positive integer steps and multipliers, and report the actual lowest-cost eligible candidate when returning infeasible.
  • All pytest tests pass locally and in GitHub Actions, and fde-03-2 is pushed to GitHub.
Practice assignment

Build this

In fde-03-2, implement strict Pydantic v2 schemas in src/fde_03_2/schemas.py (WorkflowProfile, ArchitectureOption, and ArchitectureDecision) and decision logic in src/fde_03_2/selector.py (recommend_architecture, estimate_run_cost_usd, and estimate_run_latency_ms).

  • Enforce max_budget_usd_per_run, max_latency_ms, and side-effect constraints (including reversible_side_effects and has_approval_checkpoint), downgrading from more complex options to cheaper/faster ones only when the downgraded option actually satisfies both budget and latency limits.
  • Return recommended="infeasible" and feasible=False with clear reasons when no option satisfies the budget, latency, or side-effect constraints, and strictly reject non-integer or boolean expected_steps values and overflowed cost estimates.
  • Add unit tests in tests/test_selector.py covering latency/SLA violations, budgets below the minimum feasible architecture cost, side-effect approval and reversibility requirements, invalid expected_steps values (including booleans and floats), cost estimation overflow and extreme multipliers, architecture downgrades, and verification that downgraded recommendations satisfy both budget and latency constraints, then run python -m pytest -v and push fde-03-2 (including .github/workflows/pytest.yml) to GitHub.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why is an open-ended agent loop often the wrong choice when a workflow already has known steps and clear input/output contracts?
  2. When does a classifier plus deterministic template or pipeline beat a tool-using agent on cost, latency, and auditability?
  3. How do variable tool-call counts, retries, side-effect reversibility, and approval checkpoints affect architectural feasibility?
  4. Why should the decision model support an explicit infeasible outcome, and what belongs in an Architecture Decision Record (ADR)?
Reveal self-review answers (attempt the questions first)
  1. Known steps and contracts: When steps, validations, and side effects are predictable, a deterministic pipeline or bounded graph avoids extra LLM reasoning turns, lowers failure modes, and makes behavior easier to test and audit.
  2. Classifier plus template or pipeline: High-volume routing, standard status lookups, and templated responses often need only a fast classification step plus deterministic code or templates, reducing LLM calls, token cost, and tail latency while keeping outputs consistent.
  3. Loops, side effects, and approvals: Open-ended loops can run variable steps or retries that blow cost and latency ceilings, while irreversible external side effects without approval checkpoints increase operational risk.
  4. Infeasible outcomes and ADR contents: When constraints are too tight for any pattern (such as a budget below the minimum cost or an impossible latency SLA), returning an explicit infeasible decision is more honest than forcing a non-compliant option; an ADR records context, options considered, chosen design, trade-offs, and revisit triggers.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.