Long-Running Workflow Agents for Inspection: Engineering Practices Toward 60% Cost Reduction

    This article examines why long-running workflow agents in scenarios such as aquaculture, equipment O&M, and campus security can incur high costs during continuous inspection tasks. It introduces a calculable cost model and presents engineering practices for reducing cost across four dimensions: call count, context size, empty-inspection ratio, and tool rounds. The practices include context layering and caching, externalized workflow state with incremental context, empty-inspection suppression, tool-call governance, model routing, and budget observability. The article also outlines a phased implementation path and key boundaries, with the goal of reducing average cost per task by 60% as a target range without lowering alert recall.

    In scenarios such as aquaculture, equipment O&M, and campus security, an agent is often not a single-turn chat assistant but a long-running workflow: scheduled inspections, sensor reads, anomaly judgment, tool calls, state recording, and alerts when necessary. The core difference from general conversational models is not whether the agent can answer, but how many steps it must execute continuously, how much context each step carries, and how many ineffective calls it produces. Without engineering governance, cost is rapidly amplified by system prompts, conversation history, and multi-turn tool calls.

    1. Why Costs Inflate: Start with a Calculable Model

    The cost of a single task in a long-running workflow can be abstracted as:

    1. Single-task cost ≈ number of calls × token volume of (static system prompt + historical context + current input + tool returns) × unit price
    2. + tool-call and orchestration resource cost

    Three variables are most likely to spiral out of control:

    1. Many calls: a complex task may include dozens of tool-call rounds, and each round resubmits context.
    2. Heavy static context: system prompts, business rules, and tool descriptions are carried in full every time, often reaching thousands to tens of thousands of tokens.
    3. High empty-inspection ratio: checking every 30 minutes can produce more than twenty “no anomaly” empty checks overnight. A single check looks cheap, but the accumulated bill becomes obvious. In publicly reported practice estimates, high-frequency empty inspections can accumulate a bill in the hundreds of RMB overnight, before any real business action occurs.

    Therefore, cost reduction cannot rely only on switching to a cheaper model. It must govern four dimensions at the same time: call count, context size, idle ratio, and tool rounds.

    2. Context Layering and Caching: Stop Paying Repeatedly for Static Content

    Split context into four layers:

    • Static layer: role setting, safety boundaries, output format, and general business rules;
    • Semi-static layer: pond IDs, device list, threshold table, and tool descriptions;
    • Dynamic layer: current sensor readings, the latest feeding record, and pending alerts;
    • Session layer: summaries of recent decisions and tool returns.

    The governance strategy is to template and version the static and semi-static layers, and make use of available model-side context caching where possible. The dynamic layer should send only changed fields. The session layer should not retain the full history; instead, use a rolling summary plus a key-event table. Tool descriptions should also be concise: name, purpose, input parameters, return fields, and failure semantics. Do not stuff large documents into every round’s prompt.

    Example structure:

    1. [Static rules v3] Submit in full only on first use or version change
    2. [Business snapshot] Submit only changed pond IDs, metrics, and thresholds
    3. [Event summary] Last 3 key events, each no more than 50 characters
    4. [Current decision] Whether inspection is needed, whether budget is exceeded, fields pending confirmation

    The key is not simple truncation. It is ensuring that the model still receives the minimum information set needed for the current decision.

    3. Externalized State and Incremental Context: Put Workflow State in the Database

    A long-running workflow should not stuff all state into the conversation history. A more reasonable approach is: a task state machine maintains state, a database or object storage saves snapshots, a message queue drives the next step, and the model is responsible only for the current node decision.

    For example, an inspection task state can be defined as: Pending inspection → Collecting → Judging → Normal/Abnormal → Alerted/Closed. Each round submits only:

    • Current state;
    • Structured summary of the previous tool return;
    • Unfinished subgoals;
    • Budget and time limit.

    Tool returns should not be fed back verbatim. For long lists, logs, and time-series data, aggregate first: maximum, minimum, mean, out-of-bounds points, trend direction, and anomaly count. The model needs the basis for a decision, not the full raw data set. Use idempotency keys and result caching for repeated queries. Set a short TTL cache for inspection results with the same pond ID and the same time window to avoid repeated reads across rounds.

    4. Empty-Inspection Suppression: Rules First, Model Later

    Empty inspections are the largest hidden cost in long-running workflows. The optimization principle is: if a rule can decide, do not call the model; if checks can be merged, do not split them into multiple calls.

    An actionable process:

    1. Put the threshold and rule engine first: when water-quality metrics are within the safe range and the device heartbeat is normal, generate a “normal” event directly without model inference.
    2. Use a lightweight classifier or small-model prefilter: call the model only for gray-zone data, such as metrics close to a threshold but not out of bounds.
    3. Merge scheduled tasks: batch-check multiple pond IDs and devices in the same time window to reduce scheduling rounds.
    4. Backoff and suppression: after consecutive empty checks, gradually lengthen the interval; do not repeat an alert before the same anomaly is closed.
    5. Short path for empty results: the model outputs only a structured judgment and does not generate a long explanation; explanations are generated only on anomalies.

    This reduces both call count and output tokens per round. Note that empty-inspection suppression must not sacrifice safety boundaries. Critical metric out-of-bounds, device offline, and sensor loss must use independent alert channels and must not depend on model judgment.

    5. Tool-Call Governance: Reduce Rounds and Return Size

    Tool-call cost includes not only tokens but also latency and failed retries. Governance points:

    • Tool allowlist and budget: set a maximum number of tool rounds, maximum retries, and maximum duration for each task; when over budget, defer to a human or degrade.
    • Batch APIs first: query multiple pond IDs at once instead of calling pond by pond.
    • Return trimming: keep only decision fields in tool returns; store log-type data and return a summary and reference.
    • Structured output: require the model to output fixed fields such as decision, reason_code, and next_action to reduce free text.
    • Fast failure termination: stop retrying after the same tool fails twice consecutively, record an observable event, and avoid long-tail consumption.

    6. Model Routing and Budget Observability: Turn Cost Reduction into a Continuous Mechanism

    Different nodes have different complexity. Threshold judgment, field extraction, and format validation can use small models or rules; complex anomaly attribution can then use a stronger model. The routing strategy should dynamically select based on task complexity, historical success rate, and remaining budget, while keeping a “failure escalation” path.

    At the same time, build a cost dashboard that monitors at least: tokens per task, calls per task, empty-inspection rate, tool rounds, cache hit rate, summary compression ratio, and cost distribution of anomalous tasks. The optimization goal can be set as “reduce average cost per task by 60% without lowering alert recall.” It is advisable to instrument for one week first, identify the top 20% most costly tasks, and then transform them in the order above.

    Pseudocode example:

    1. def handle_inspection(task, state, budget):
    2. if budget.exceeded():
    3. return defer_to_human(task)
    4. quick = rule_engine.check(task, state)
    5. if quick.decided:
    6. return quick.result
    7. key = cache_key(task.pool_id, task.window, state.version)
    8. if cache.has(key):
    9. return cache.get(key)
    10. ctx = build_context(
    11. static=rule_template(task.rule_version),
    12. delta=state.changed_fields(),
    13. summary=state.event_summary(limit=3),
    14. budget=budget.snapshot()
    15. )
    16. route = model_router.select(complexity=estimate(task), budget=budget)
    17. plan = route.plan(ctx)
    18. for step in plan.steps:
    19. if not budget.allow_tool(step.tool):
    20. break
    21. if step.tool not in allowlist:
    22. continue
    23. obs = call_tool(step.tool, trim_args(step.args))
    24. state = reduce_state(state, summarize(obs))
    25. result = normalize(plan.decision, state)
    26. cache.set(key, result, ttl=short_ttl)
    27. return result

    7. Implementation Path and Boundaries

    A three-phase approach is recommended. In the first week, complete call-chain instrumentation and cost attribution. In weeks two and three, launch rule fronting, caching, return trimming, and budget limits. In week four, introduce model routing and rolling summaries, and run an A/B comparison. The 60% cost reduction should be treated as a target range, not a commitment; actual results depend on the empty-inspection ratio, context size, and tool rounds.

    Finally, clarify the boundaries: safety alerts cannot rely only on cached results; summary compression may lose detail, so key events need to retain original references; caches must have invalidation policies; and any degradation must have auditable logs. The essence of cost reduction for long-running workflows is to change “make the model understand all context from scratch every round” into an engineering system of “externalized state, rules first, incremental decisions, and controllable budget.” Only when cost is observable, attributable, and reversible can a 60% cost-reduction target be sustainable.